/* eslint-disable react-hooks/rules-of-hooks */
import React, { useEffect, useRef, useState } from 'react';
import { BasicLayoutProps as ProLayoutProps, PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Button,
  Card,
  Checkbox,
  DatePicker,
  Form,
  Input,
  message,
  Radio,
  Select,
  Spin,
  Upload,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
// 引入编辑器样式
import { Dispatch, history } from 'umi';
import { getArticleDetail, updateRule } from './service';
import './index.less';
import { queryAllCategory } from '../Category/service';
import { queryAllLevel } from '../level/service';
import { Editor } from '@tinymce/tinymce-react';
import moment from 'moment';

const { Option } = Select;

export interface BasicLayoutProps extends ProLayoutProps {
  ue: any;
  dispatch: Dispatch;
}

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');

  if (!fields.id) {
    // eslint-disable-next-line no-param-reassign
    delete fields.id;
    try {
      const msg = await updateRule({ ...fields });
      hide();
      if (msg.retcode) {
        message.success('添加成功');
        return true;
      }
      message.error('添加失败请重试！');
      return false;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  } else {
    try {
      const msg = await updateRule({ ...fields });
      hide();
      if (msg.retcode) {
        message.success('保存成功');
        return true;
      }
      message.error('保存失败请重试！');
      return false;
    } catch (error) {
      hide();
      message.error('保存失败请重试！');
      return false;
    }
  }
};

// eslint-disable-next-line consistent-return
const getCategoryList = async () => {
  const msg = await queryAllCategory();
  if (msg.retcode) {
    return msg.data || [];
  } else {
    return [];
  }
};

// eslint-disable-next-line consistent-return
const getLevelList = async () => {
  const msg = await queryAllLevel();
  if (msg.retcode) {
    return msg.data || [];
  } else {
    return [];
  }
};

const updateForm: React.FC<BasicLayoutProps> = (prop: any) => {
  const [form] = Form.useForm();
  const [formVals] = useState({
    id: prop.match.params.id,
    title: '',
    version: '',
    onlyFile: false,
    categoryId: null,
    levelId: null,
    keyword: '',
    currentStatus: 1,
    content: '',
    fileUrls: [],
    implementationDate: null,
    state: 1,
  });

  const [videoContent, setVideoContent] = useState('');
  const [initialContent, setInitialContent] = useState('');

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 5 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 12 },
      md: { span: 16 },
    },
  };

  const submitFormLayout = {
    wrapperCol: {
      xs: { span: 24, offset: 0 },
      sm: { span: 10, offset: 5 },
    },
  };

  const [catecoryList1, setList1Vals] = useState<any[]>([]);
  const [catecoryList2, setList2Vals] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const editorRef = useRef<any>(null);

  const normFile = (e: any) => {
    const videoArr: any = [];
    e.fileList.forEach((item: any) => {
      console.log(item);
      videoArr.push({
        uid: item.uid,
        name: item.name,
        status: item.response && item.response.location || item.status === 'done' ? 'done' : item.response && item.response.code == 2001 ? 'error' : 'uploading',
        url: item.url ? item.url : item.response ? item.response.location : item.response,
      });
    });
    setVideoContent(JSON.stringify(videoArr));
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  const getCatecoryList = async () => {
    const arr1 = await getCategoryList();
    setList1Vals(arr1);
    const arr2 = await getLevelList();
    setList2Vals(arr2);
  };

  const onFinish = async (value: any) => {
    let content = '';
    let text = '';
    if (editorRef.current) {
      //@ts-ignore
      const editBody = editorRef.current.getBody();
      editorRef.current.selection.select(editBody);
      text = editorRef.current.selection.getContent({ format: 'text' });
      text = text.replace(/\s*/g, '');
      //@ts-ignore
      content = editorRef.current.getContent();
    }
    let fileUrls = videoContent;
    const categoryName = catecoryList1.find((e) => e.id === value.categoryId)?.categoryName;
    const levelName = catecoryList2.find((e) => e.id === value.levelId)?.levelName;
    value.onlyFile = value.onlyFile ? 1 : 0;
    value.implementationDate = value.implementationDate
      ? value.implementationDate.format('YYYY-MM-DD HH:mm:ss')
      : null;
    const success = await handleUpdate({
      ...value,
      fileUrls,
      content,
      contentText: text,
      id: prop.match.params.id,
      categoryName,
      levelName,
    });
    if (success) {
      history.push('/article/article-page');
    }
  };

  useEffect(() => {
    getCatecoryList();
    if (prop.match.params.id) {
      setLoading(true);
      getArticleDetail({ id: prop.match.params.id })
        .then((res) => {
          setLoading(false);
          if (res.retcode && res.data) {
            console.log(res.data);
            let arr: any = [];
            if (res.data.fileUrls) {
              arr = JSON.parse(res.data.fileUrls);
            }
            form.setFieldsValue({
              id: prop.match.params.id,
              title: res.data.title,
              version: res.data.version,
              onlyFile: res.data.onlyFile === 1,
              categoryId: res.data.categoryId,
              levelId: res.data.levelId,
              keywords: res.data.keywords,
              currentStatus: res.data.currentStatus,
              content: res.data.content,
              implementationDate: res.data.implementationDate
                ? moment(res.data.implementationDate)
                : null,
              fileUrls: arr,
              state: res.data.state,
            });
            setVideoContent(res.data.fileUrls);
            setInitialContent(res.data.content);
          } else {
            setInitialContent('');
          }
        })
        .catch(() => {
          setLoading(false);
        });
    }
  }, []);

  return (
    <PageHeaderWrapper>
      <Spin spinning={loading}>
        <Card bordered={false}>
          <div id="components-table-demo-basic">
            <Form form={form} initialValues={formVals} onFinish={onFinish}>
              <Form.Item
                {...formItemLayout}
                name="title"
                label="名称"
                rules={[{ required: true, message: '请输入名称' }]}
              >
                <Input placeholder="请输入名称" />
              </Form.Item>
              <Form.Item {...formItemLayout} name="version" label="文号版本">
                <Input placeholder="请输入文号版本" />
              </Form.Item>
              <Form.Item {...formItemLayout} name="categoryId" label="类型">
                <Select allowClear style={{ width: '100%' }} placeholder="类型">
                  {catecoryList1.map((item: any) => (
                    <Option key={item.id} value={item.id}>
                      {item.categoryName}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item {...formItemLayout} name="currentStatus" label="现行状态">
                <Select allowClear style={{ width: '100%' }} placeholder="现行状态">
                  <Option key={1} value={1}>
                    现行
                  </Option>
                  <Option key={2} value={2}>
                    废止
                  </Option>
                </Select>
              </Form.Item>
              <Form.Item {...formItemLayout} name="levelId" label="级别">
                <Select allowClear style={{ width: '100%' }} placeholder="级别">
                  {catecoryList2.map((item: any) => (
                    <Option key={item.id} value={item.id}>
                      {item.levelName}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item {...formItemLayout} name="implementationDate" label="实施日期">
                <DatePicker />
              </Form.Item>
              <Form.Item {...formItemLayout} name="keywords" label="搜索关键字">
                <Input placeholder="多个关键字用逗号隔开" />
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                name="fileUrls"
                label="附件"
                valuePropName="fileList"
                getValueFromEvent={normFile}
              >
                <Upload name="file" action="http://47.92.229.12:8888/oss/fileUpload">
                  <Button icon={<UploadOutlined />}>上传附件</Button>
                </Upload>
              </Form.Item>
              <Form.Item {...formItemLayout} label="内容">
                <Editor
                  tinymceScriptSrc={'/tinymce/tinymce.min.js'}
                  //@ts-ignore
                  onInit={(evt, editor) => (editorRef.current = editor)}
                  initialValue={initialContent}
                  init={{
                    height: 500,
                    menubar: false,
                    branding: false, // 去掉右下角的水印
                    // language_url: '/tinymce/langs/zh-Hans.js',//注意大小写
                    language: 'zh-Hans', //注意大小写
                    images_upload_url: 'http://47.92.229.12:8888/oss/imgUpload',
                    plugins: [
                      'advlist',
                      'autolink',
                      'lists',
                      'link',
                      'image',
                      'charmap',
                      'anchor',
                      'searchreplace',
                      'visualblocks',
                      'code',
                      'fullscreen',
                      'insertdatetime',
                      'media',
                      'table',
                      'preview',
                      'help',
                      'wordcount',
                      'pastewordimage',
                    ],
                    toolbar:
                      'undo redo | blocks | ' +
                      'bold italic forecolor | alignleft aligncenter ' +
                      'alignright alignjustify | bullist numlist outdent indent | ' +
                      'removeformat',
                    content_style:
                      'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }',
                  }}
                />
                {/* <textarea id="content" /> */}
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                name="onlyFile"
                colon={false}
                label=" "
                valuePropName="checked"
              >
                <Checkbox>不设置正文，直接读取附件</Checkbox>
              </Form.Item>
              <Form.Item {...formItemLayout} name="state" label="状态">
                <Radio.Group>
                  <Radio style={{ marginRight: 10 }} value={1}>
                    启用
                  </Radio>
                  <Radio value={2}>禁用</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item {...submitFormLayout} shouldUpdate>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
                <Button
                  style={{ marginLeft: 8 }}
                  onClick={() => {
                    history.goBack();
                  }}
                >
                  返回
                </Button>
              </Form.Item>
            </Form>
          </div>
        </Card>
      </Spin>
    </PageHeaderWrapper>
  );
};

export default updateForm;
