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 { editDraftItem, editSubItem, newsDraftPublish, queryNewsDraftItem, queryNewsItem } from './service';
import { NewsItem, NewsParams } from '../news/data';
import { addNewsItem, removeNews } from '../news/service';
import { queryAllTags } from '../tag/service';
import { NewsDataInfo } from '../subscribe/data';
import { handleRemove } from '../news';

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"],
  ["table", "link"],
  // ["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 handleAdd = async (fields: NewsParams, content: string) => {
  console.log("-----fields.summary == ------", fields.summary == "", fields.summary)
  if (content == "" || content == undefined) {
    message.warn('内容不能为空');
    return
  }
  const hide = message.loading('正在添加');
  try {
    fields.content = content

    const summary = 100

    // if (fields.summary == "" || fields.summary == undefined) {
    //   let str = ""
    //   if (fields.content.length <= summary) {
    //     str = fields.content;
    //   } else {
    //     str = fields.content.substring(0, summary);

    //   }
    //   fields.summary = str;
    //   fields.sub_title = str;
    // }

    let result = await addNewsItem({ ...fields });
    hide();
    message.success('添加成功');
    return result;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return {
      data: 0,
      success: false,
    };;
  }
};


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

// /**
//  *  删除节点
//  * @param selectedRows
//  */
// const handleRemove = async (selectedRows: NewsItem[]) => {
//   const hide = message.loading('正在删除');
//   if (!selectedRows) return true;
//   try {
//     await removeNews({
//       ids: selectedRows.map((row) => row.id),
//     });
//     hide();
//     message.success('删除成功，即将刷新');
//     return true;
//   } catch (error) {
//     hide();
//     message.error('删除失败，请重试');
//     return false;
//   }
// };

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

/**
 * 更新节点 Sub
 * @param fields
 */
const handleSubUpdate = async (id: number, fields: NewsParams, content: string) => {
  const hide = message.loading('正在保存');
  try {
    // fields.deptId = Number(fields.deptId)
    fields.id = id
    fields.content = content

    const summary = 100

    // if (fields.summary == "" || fields.summary == undefined) {

    //   let str = ""
    //   if (fields.content.length <= summary) {
    //     str = fields.content;

    //   } else {
    //     str = fields.content.substring(0, summary);

    //   }

    //   fields.summary = str;
    //   fields.sub_title = str;
    // }


    console.log("======", fields)
    await editSubItem(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};

const EditView: 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<NewsDataInfo>();
  const [contentMK, setContentMK] = useState<string>();
  const [options, setOptions] = useState<SelectProps['options']>();
  const match = useRouteMatch<RouteParams>();
  const [draftId, setDraftId] = useState<number>();


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

  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)
    queryNewsDraftItem(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 NewsDataInfo)

      setContentMK(result[0].content)

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

      setTimeout(() => {
        setInitPage(true)
      }, 500)





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



    });
  }

  const initSubFunc = async () => {

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

    console.log(id)
    queryNewsItem(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 NewsDataInfo)

      setContentMK(result[0].content)

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

      setTimeout(() => {
        setInitPage(true)
      }, 500)





      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 == Edit) {
        initFunc()
        setDraftId(id)
      } else if (option == Sub) {
        initSubFunc()
        setDraftId(id)
      }
      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) {
      message.warn("请编写文章内容")
      return
    }

    console.log(option == Edit && !!id)

    if (option == Edit && !!id) {
      await handleUpdate(id, values, contentMK)
    } else if (option == Sub && !!id) {
      await handleSubUpdate(id, values, contentMK)
    } else if (option == Add) {
      let result = await handleAdd(values, contentMK)
      if (result!.success) {
        setDraftId(result!.data)
      }
    } else {
      message.warn(id + " option errr: " + option)
    }

  };



  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>

      {((option == Edit || option == Sub) && (!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}>


            {(option == Edit || option == Add) && <Button type="primary"
              style={{
                marginRight: (option == Edit) ? "120px" : "220px"
              }}
              disabled={draftId ? false : true}
              onClick={() => {
                if (draftId) {
                  handlePublish(draftId);
                }

              }}
            >发布</Button>}

            {(option == Edit) && <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="addNews"
            onFinish={onFinish}
            initialValues={{
              residence: ['zhejiang', 'hangzhou', 'xihu'],
              prefix: '86',
            }}
            scrollToFirstError
          >

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

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

            <Form.Item
              name="summary"
              label="摘要信息"
              tooltip="摘要信息"
              rules={[{ message: '摘要信息', whitespace: true }]}
            >
              <Input.TextArea showCount maxLength={200} />
            </Form.Item>

            <Form.Item
              name="image_url"
              label="主图片"
              rules={[{ message: 'Please input website!' }]}
            >
              {/* <AutoComplete options={websiteOptions} onChange={onWebsiteChange} placeholder="website">
                <Input />
              </AutoComplete> */}
              <Input />
            </Form.Item>

            <Form.Item label="语言" extra="">
              <Row gutter={24}>
                <Col span={4}>

                  <Form.Item
                    name="language"
                    label=""
                    rules={[{ required: true, message: '请选择语言' }]}
                  >
                    <Select placeholder="请选择语言">
                      <Option value="zh-CN">简体中文</Option>
                      <Option value="en">English</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  {/* <Form.Item
                    name="captcha"
                    noStyle
                    rules={[{ required: true, message: 'Please input the captcha you got!' }]}
                  >
                    <Input />
                  </Form.Item> */}

                  <Form.Item
                    name="keywords"
                    label="keywords"
                    rules={[{ required: false, message: 'Please select keywords!' }]}
                  >
                    <Select placeholder="select your keywords">
                      <Option value="Bitcoin">Bitcoin</Option>
                      <Option value="Ethereum">Ethereum</Option>
                      <Option value="Filecoin">Filecoin</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="tags"
                    label="标签"
                    rules={[{ required: false, message: '请选择标签' }]}
                  >
                    {/* <Select placeholder="选择标签">
                      <Option value="#Blockchain">#Blockchain</Option>
                      <Option value="#AI">#AI</Option>
                      <Option value="#Coincap">#Coincap</Option>
                    </Select> */}

                    <Select
                      mode="tags"
                      // size={size}
                      placeholder="Please select"
                      // defaultValue={['a10', 'c12']}
                      onChange={handleChange}
                      options={options}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form.Item>


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

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


        </div>
        {/* {JSON.stringify(dataInfo)} */}
        {/* {JSON.stringify(contentMK)} */}
        {(((option == Edit || option == Sub) && !!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 EditView;
