import { AndroidOutlined, AppleOutlined, ArrowDownOutlined, ArrowUpOutlined, DeleteOutlined, EditOutlined, EllipsisOutlined, ExclamationCircleOutlined, SettingOutlined, } from '@ant-design/icons';
import {
  Button,
  Divider,
  message,
  Drawer,
  Modal,
  Tabs,
  Card,
  Avatar,
  Switch,
  Row,
  Col,
  Statistic,
  Space,
  Form,
  Input,
  Layout,
  Select,
  Cascader,
  InputNumber,
  AutoComplete,
  Checkbox,
  SelectProps
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar, PageLoading } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import MemberAddressModal from "@/pages/ums/member/components/MemberAddressModal";
import MemberLogModal from "@/pages/ums/member/components/MemberLoginLogModal";
import Meta from 'antd/lib/card/Meta';
import Editor from './editor';

import { useRouteMatch, history } from 'umi'

import '@toast-ui/editor/dist/toastui-editor.css';



import { NewsItem } from '../news/data';
import { queryAllTags } from '../tag/service';
import { QADraftParams } from './data';
import { editQADraftItem, newsQADraftPublish, queryQADraftItem } from './service';
import { QADataInfo } from '../qa/data';
import { handleRemove } from '../qa';

const { Header, Footer, Sider, Content } = Layout;

const { Option } = Select;

const { confirm } = Modal;

const Edit = "edit"
const Add = "add"
const Sub = "sub"


export interface CreateFormProps {
  // itemList: QADataInfo[];
  // label: number;
  // onCancel: () => void;
  // onSubmit: () => void;
  // addressModalVisible: boolean;
  // memberId: number;
}

interface RouteParams {
  article_id: string; // 这里假设article_id是字符串类型
  option: string;
  currTags: string
  // 如果article_id是数字类型，可以将其定义为number
}



const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
};

const toolbarItems = [
  ["heading", "bold", "italic", "strike"],
  ["hr", "quote"],
  ["ul", "ol", "task", "indent", "outdent"],
  ["table", "image", "link"],
  ["code", "codeblock"],
  // Using Option: Customize the last button
  [
    {
      name: "export",
      tooltip: "Export logbook",
      command: "export",
      className: "toastui-editor-toolbar-icons last",
      style: { backgroundImage: "none" },
      text: "↓",
    },
  ],
];



/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (id: number, fields: QADraftParams, content: string) => {
  const hide = message.loading('正在保存');
  try {
    fields.id = Number(id)
    fields.answer = content
    console.log("======", fields)
    await editQADraftItem(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};

/**
 * 发布文章
 * @param fields
 */
const handlePublish = async (id: number) => {
  const hide = message.loading('正在发布');
  try {
    let result = await newsQADraftPublish(id);
    hide();
    message.success('添加发布');
    return result;
  } catch (error) {
    hide();
    message.error('发布失败请重试！');
    return {
      data: 0,
      success: false,
    };;
  }
};


const EditQAView: React.FC<{}> = () => {
  // const [addressModalVisible, handleAddressModalVisible] = useState<boolean>(false);
  // const [logModalVisible, handleLogModalVisible] = useState<boolean>(false);
  // // const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  // const [showDetail, setShowDetail] = useState<boolean>(false);
  // const actionRef = useRef<ActionType>();

  // const editorRef = useRef(null);
  const editorRef = useRef<Editor>();
  const [form] = Form.useForm();

  const [initPage, setInitPage] = useState<boolean>(false);
  const [dataInfo, setDataInfo] = useState<QADataInfo>();
  const [contentMK, setContentMK] = useState<string>();
  const [options, setOptions] = useState<SelectProps['options']>();
  const match = useRouteMatch<RouteParams>();

  const [markdownEditor, setEditorInstance] = useState(null);

  const [draftId, setDraftId] = useState<number>();

  const onMdContentChange = () => {
    if (!editorRef.current) return;

    const editor = editorRef.current.getInstance();
    const content = editor.getMarkdown();

    // console.log(content)
    // const value = editorRef?.current.getInstance().getValue();

    setDataInfo({
      ...dataInfo as any,
      content: content,
    })
    setContentMK(content)
    window.localStorage.setItem('mdContent', content);
  }


  const handleSave = () => {
    if (!editorRef.current) return;

    const editor = editorRef.current.getInstance();
    const content = editor.getMarkdown();

    console.log(content)
  };



  console.log(match.params)
  const id = Number(match.params.article_id)
  const option = (match.params.option)
  const currTags = (match.params.currTags)


  const initFunc = async () => {

    if (!id) {
      message.error("无效文章")
      return
    }

    console.log(id)
    queryQADraftItem(id).then((res: any) => {
      console.log("--initFunc---->", res)



      if (!res.success) {
        message.warn("请求失败")

        return
      }

      const result = res.data

      if (result.length == 0) {
        message.warn("无文章")

        return
      }

      setDataInfo(result[0] as QADataInfo)

      setContentMK(result[0].answer)

      console.log("------", dataInfo)

      // setTimeout(() => {

      // })

      setInitPage(true)



      form.setFieldsValue({
        ...result[0],
        // deptId: values.deptId + '',
      });



    });
  }

  const initTagsFunc = async () => {
    queryAllTags({ pageSize: 100, current: 0 }).then((res) => {
      console.log("--queryAllTags---->", res)

      setInitPage(true)

      let newRes = res.data



      newRes.map((_item: any, _index: any) => {
        newRes[_index] = {
          ...newRes[_index],
          label: _item.name,
          value: _item.name,
        }

      })

      setOptions(newRes)

      // console.log("items", items)

    });
  }

  useEffect(() => {
    let isMounted = true
    const fetchPost = async () => {

      if (option != Add) {
        initFunc()
        setDraftId(id)
      } else {
        setInitPage(true)
      }


      // initTagsFunc()

    }

    fetchPost()

    return () => {
      isMounted = false
    }
  }, [])


  // const options: SelectProps['options'] = [];
  // for (let i = 10; i < 36; i++) {
  //   options.push({
  //     value: i.toString(36) + i,
  //     label: i.toString(36) + i,
  //   });
  // }

  const handleChange = (value: string | string[]) => {
    console.log(`Selected: ${value}`);
  };

  const showDeleteConfirm = (item: NewsItem) => {
    confirm({
      title: '是否删除记录?',
      icon: <ExclamationCircleOutlined />,
      content: '删除的记录不能恢复,请确认!',
      onOk() {
        handleRemove(currTags, [item]).then((r) => {
          // actionRef.current?.reloadAndRest?.();
          history.goBack();
        });
      },
      onCancel() {
      },
    });
  };


  const onFinish = async (values: any) => {
    console.log('Received values of form: ', values);

    if (contentMK && !!id) {
      await handleUpdate(id, values, contentMK)
    }


  };



  const [autoCompleteResult, setAutoCompleteResult] = useState<string[]>([]);

  const onWebsiteChange = (value: string) => {
    if (!value) {
      setAutoCompleteResult([]);
    } else {
      setAutoCompleteResult(['.com', '.org', '.net'].map(domain => `${value}${domain}`));
    }
  };

  const websiteOptions = autoCompleteResult.map(website => ({
    label: website,
    value: website,
  }));




  return (
    <Layout>

      {(!initPage && !contentMK) ? <PageLoading /> : <Content>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            fontSize: "12px",
            padding: " 20px 3px"
          }}
        >
          <Button type="primary"
            onClick={() => {
              history.goBack();
            }}

          >返回</Button>

          <Space wrap size={30}>


            <Button type="primary"
              style={{
                marginRight: "120px"
              }}

              onClick={() => {
                if (draftId) {
                  handlePublish(draftId);
                }

              }}
            >发布</Button>

            <Button type="primary" onClick={() => {
              showDeleteConfirm({
                id: id,
              });
            }}>删除</Button>
          </Space>

        </div>

        <div
          style={{
            // display: "flex",
            // alignItems: "center",
            // justifyContent: "space-between",
            // fontSize: "12px",
            // padding: " 20px 3px"

            position: "relative"
          }}
        >
          <Form
            {...formItemLayout}
            form={form}
            name="addQA"
            onFinish={onFinish}
            initialValues={{
              // residence: ['zhejiang', 'hangzhou', 'xihu'],
              prefix: '86',
            }}
            scrollToFirstError
          >


            <Form.Item
              name="language"
              label="语言"
              rules={[{ required: true, message: '请选择语言' }]}
            >
              <Select placeholder="请选择语言">
                <Option value="zh-CN">简体中文</Option>
                <Option value="en">English</Option>
              </Select>
            </Form.Item>


            <Form.Item
              name="question"
              label="问题"
              tooltip="问题"
              rules={[{ required: true, message: '问题', whitespace: true }]}
            >
              <Input />
            </Form.Item>


            <Form.Item {...tailFormItemLayout}
              style={{
                position: "absolute",
                right: "130px",
                top: "-52px"
              }}

            >
              <Button type="primary" htmlType="submit">
                保存
              </Button>
            </Form.Item>
          </Form>


        </div>

        {((!!contentMK) || option == Add) && <Editor
          ref={editorRef as React.LegacyRef<Editor>}
          previewStyle="vertical"
          initialEditType="wysiwyg"
          initialValue={contentMK}
          // onBlur={handleSave}
          onChange={onMdContentChange}
          // toolbarItems={toolbarItems}
          height="auto"
        />}



        {/* <Editor
          previewStyle="vertical"
          height="auto"
          initialValue={dataInfo?.content}
          initialEditType="wysiwyg"
          useCommandShortcut={true}
          usageStatistics={false}
          hideModeSwitch={true}
          ref={editorRef as React.LegacyRef<Editor>}
          onBlur={handleSave}
          toolbarItems={toolbarItems}
        /> */}


      </Content>}
    </Layout>
  );
};

export default EditQAView;
