/* eslint-disable */
import React, { useEffect, useState, useReducer } from "react";
import {
  Button,
  Form,
  Input,
  Space,
  Upload,
  Select,
  Switch,
  message,
  DatePicker,
  Spin
} from "antd-v4";
import { CheckOutlined, CloseOutlined } from "@ant-design/icons";
import BraftEditor from "braft-editor";
import "braft-editor/dist/index.css";
import styles from "./index.less";
import * as commonServices from "@/services/services";
import commonConfig from "@/utils/config";
import * as commonUtils from "@/utils/utils";
import moment from "moment";
import WorkOrderSystemService from "./WorkOrderSystemService";
import WorkOrderSystemConfig from "./WorkOrderSystemConfig";

let _dispatch, _props;
const reducer = (state, action) => {
  const [type, payload] = action;
  switch (type) {
    case "set":
      return {
        ...state,
        ...payload
      };
    default:
      return {
        ...state,
        ...payload
      };
  }
};

// 主入口
const WorkOrderSystemAdd = props => {
  const [state, dispatch] = useReducer(reducer, {
    sType: 4,
    sBug: '0',
    bVsersion: false
  });
  const { customerData, moduleData, userData, loading = false } = state;
  const [form] = Form.useForm();
  const [formState] = useState(state); // 表单数据
  const [files, setFiles] = useState([]); // 附件数据
  const [customerOption, setCustomerOption] = useState([]); // 【所属客户】下拉选项
  const [moduleOption, setModuleOption] = useState([]); // 【所属模块】下拉选项
  const [userOption, setUserOption] = useState([]); // 【处理人、抄送人】下拉选项
  const { priorityOption, sBugOption } = WorkOrderSystemConfig; // 各种固定下拉选项

  // 初始化加载数据
  useEffect(() => {
    _dispatch = dispatch;
    _props = props;
    handleGetsCustomerData();
    handleGetsModuleData();
    handleGetUserData();
  }, []);

  // 设置【所属客户】下拉值
  useEffect(
    () => {
      commonUtils.isNotEmptyArr(customerData) &&
        setCustomerOption(
          customerData.map(item => ({
            label: item.sCustomerName,
            value: item.sCustomerId || item.sId
          }))
        );
    },
    [customerData]
  );

  // 设置【处理人、抄送人】下拉值
  useEffect(
    () => {
      commonUtils.isNotEmptyArr(userData) &&
        setUserOption(
          userData.map(item => ({
            label: item.sHanldeName,
            value: item.sHanldeId
          }))
        );
    },
    [userData]
  );

  // 设置【所属模块】下拉值
  useEffect(
    () => {
      commonUtils.isNotEmptyArr(moduleData) &&
        setModuleOption(
          moduleData.map(item => ({
            label: item.sModuleName,
            value: item.sModuleId
          }))
        );
    },
    [moduleData]
  );

  // 提交
  const onFinish = values => {
    const { app } = props;
    const { userinfo, currentPane } = app;
    const { companyName, sUserName: sMakePerson, sId: sLoginId } = userinfo;
    // const { title: sModuleName, formId: sModuleId } = currentPane;
    const commonData = {
      sCustomerName: companyName,
      sBrandName: companyName,
      sMakePerson,
      sLoginId
      // sModuleName,
      // sModuleId
    };

    let addState = {};
    if (values.sCopyHanldeId) {
      addState.sCopyHanldeId = values.sCopyHanldeId.toString();
      addState.sCopyHanldeName = userData
        .filter(item => values.sCopyHanldeId.includes(item.sHanldeId))
        .map(item => item.sHanldeName)
        .toString();
    }

    if (values.sRDUserId) {
      addState.sRDUserName = userData
      .find(item => values.sRDUserId === item.sHanldeId).sHanldeName;
    }

    if (values.sModuleId) {
      const iIndex = moduleData.findIndex(
        item => item.sModuleId === values.sModuleId
      );
      if (iIndex !== -1) {
        // 下拉选中的数据
        addState = { ...addState, ...moduleData[iIndex] };
      } else {
        // 手输的数据
        addState = {
          ...addState,
          sModuleName: values.sModuleId,
          sModuleId: commonUtils.createSid()
        };
      }
    }

    if (values.tDevHandleDate) {
      addState.tDevHandleDate = moment(values.tDevHandleDate).format(
        "YYYY-MM-DD"
      );
    }

    if (values.tHandleDate) {
      addState.tHandleDate = moment(values.tHandleDate).format("YYYY-MM-DD");
    }

    const submitData = {
      ...commonData,
      ...values,
      ...customerData.find(
        item => (item.sCustomerId || item.sId) === values.sCustomerId
      ),
      // ...moduleData.find(item => item.sModuleId === values.sModuleId),
      ...userData.find(item => item.sHanldeId === values.sHanldeId),
      ...addState,
      sContentMemo: values.sContentMemo.toHTML(),
      fileData: []
    };

    dispatch(["set", { loading: true }]);

    // 如果有附件，先上传附件再提交保存
    if (files.length) {
      handleUpload(files, fileData => {
        handleSubmit({ ...submitData, fileData });
      });
    } else {
      handleSubmit(submitData);
    }
  };

  // 附件props
  const uploadProps = {
    accept: "*/*",
    multiple: true,
    beforeUpload: file => {
      files.push(file);
      setFiles(files);
      return false;
    },
    onRemove: file => {
      const filesNew = files.filter(item => item.uid !== file.uid);
      setFiles(filesNew);
    }
  };

  return (
    <Spin spinning={loading}>
      <Form
        form={form}
        labelCol={{
          span: 3
        }}
        wrapperCol={{
          span: 21
        }}
        // layout="vertical"
        onFinish={onFinish}
        className={styles.workOrderSystem}
        initialValues={formState}
      >
        <Form.Item name="sTitle" label="标题" rules={[{ required: true }]}>
          <Input allowClear placeholder="请输入标题" />
        </Form.Item>
        <Form.Item
          name="sCustomerId"
          label="所属客户"
          rules={[{ required: true }]}
        >
          <Select
            allowClear
            showSearch={true}
            options={customerOption}
            optionFilterProp="label"
            placeholder="请选择所属客户"
          />
        </Form.Item>
        <Form.Item
          name="sModuleId"
          label="所属模块"
          rules={[{ required: true }]}
        >
          <Select
            mode="tags"
            showSearch={true}
            options={moduleOption}
            optionFilterProp="label"
            placeholder="请选择所属模块"
            onChange={value => {
              if (value.length) {
                form.setFieldValue("sModuleId", value[value.length - 1]);
              }
            }}
          />
        </Form.Item>
        <Form.Item name="sHanldeId" label="处理人" rules={[{ required: true }]}>
          <Select
            allowClear
            showSearch={true}
            options={userOption}
            optionFilterProp="label"
            placeholder="请选择处理人"
          />
        </Form.Item>
        <Form.Item name="sCopyHanldeId" label="抄送人">
          <Select
            allowClear
            showSearch={true}
            options={userOption}
            optionFilterProp="label"
            mode="multiple"
            placeholder="请选择抄送人"
          />
        </Form.Item>
        <Form.Item name="sRDUserId" label="研发人员">
          <Select
            allowClear
            showSearch={true}
            options={userOption}
            optionFilterProp="label"
            placeholder="请选择研发人员"
          />
        </Form.Item>
        <Form.Item
          name="bVsersion"
          label="标版同样问题"
          valuePropName="checked"
        >
          <Switch checkedChildren="是" unCheckedChildren="否" />
        </Form.Item>
        <Form.Item
          className={styles.formItemBug}
          name="sBug"
          label="是否bug"
        >
          <Select
            options={sBugOption}
            optionFilterProp="label"
          />
        </Form.Item>
        <Form.Item name="sType" label="优先级">
          <Select
            className={styles.sTypeSelect}
            popupClassName={styles.sTypedDropdown}
            options={priorityOption}
            optionFilterProp="label"
          />
        </Form.Item>
        <Form.Item
          name="tDevHandleDate"
          label="开发截止日期"
          rules={[
            {
              validator: (_, chooseDate) => {
                const tHandleDate = form.getFieldValue().tHandleDate;
                if (
                  chooseDate &&
                  tHandleDate &&
                  chooseDate.isAfter(tHandleDate)
                ) {
                  return Promise.reject(
                    new Error("【开发截止日期】不能晚于【截止日期】")
                  );
                } else {
                  return Promise.resolve();
                }
              }
            }
          ]}
        >
          <DatePicker placeholder="请选择开发截止日期" />
        </Form.Item>
        <Form.Item
          name="tHandleDate"
          label="截止日期"
          rules={[
            {
              validator: (_, chooseDate) => {
                const tDevHandleDate = form.getFieldValue().tDevHandleDate;
                if (
                  chooseDate &&
                  tDevHandleDate &&
                  chooseDate.isBefore(tDevHandleDate)
                ) {
                  return Promise.reject(
                    new Error("【截止日期】不能早于【开发截止日期】")
                  );
                } else {
                  return Promise.resolve();
                }
              }
            }
          ]}
        >
          <DatePicker placeholder="请选择截止日期" />
        </Form.Item>
        <Form.Item
          name="sContentMemo"
          label="内容"
          rules={[
            {
              required: true,
              validator: (_, sContentMemo) => {
                if (sContentMemo.toHTML() === "<p></p>") {
                  return Promise.reject(new Error("请输入内容"));
                } else {
                  return Promise.resolve();
                }
              }
            }
          ]}
        >
          <BraftEditor
            className={styles.braftEditor}
            readOnly={false}
            placeholder="请输入内容"
            media={{
              uploadFn: WorkOrderSystemService.uploadFn
            }}
          />
        </Form.Item>
        <Form.Item label="附件" className={styles.annex} name="fileData">
          <Upload {...uploadProps}>
            <a>添加附件</a>
          </Upload>
        </Form.Item>
        <Form.Item />
        <Form.Item className={styles.fixedBtns}>
          <Space>
            <Button
              icon={<CloseOutlined />}
              onClick={() => {
                props.onSaveState({ workOrderSystemAddModalVisible: false });
              }}
            >
              取消
            </Button>

            <Button htmlType="submit" type="primary" icon={<CheckOutlined />}>
              提交
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Spin>
  );
};

// 【接口】获取所属客户
const handleGetsCustomerData = () => {
  const url = `${commonConfig.feedback_host}sysworkorder/getCustomerData`;
  commonServices.postValueService("", {}, url).then(({ data: result = {} }) => {
    const { code = -1, data, msg = "接口出错" } = result;
    if (code > -1) {
      _dispatch && _dispatch(["set", { customerData: data }]);
    } else {
      message.error(msg);
    }
  });
};

// 【接口】获取所属模块
const handleGetsModuleData = () => {
  const url = `${commonConfig.feedback_host}sysworkorder/getModuleData`;
  commonServices.postValueService("", {}, url).then(({ data: result = {} }) => {
    const { code = -1, data, msg = "接口出错" } = result;
    if (code > -1) {
      _dispatch && _dispatch(["set", { moduleData: data }]);
    } else {
      message.error(msg);
    }
  });
};

// 【接口】获取人员
const handleGetUserData = () => {
  const url = `${commonConfig.feedback_host}sysworkorder/getUserData`;
  commonServices.postValueService("", {}, url).then(({ data: result = {} }) => {
    const { code = -1, data, msg = "接口出错" } = result;
    if (code > -1) {
      _dispatch && _dispatch(["set", { userData: data }]);
    } else {
      message.error(msg);
    }
  });
};

// 【接口】上传附件
const handleUpload = (files, cb) => {
  if (files.length === 0) {
    cb("[]");
    return;
  }
  let formData = new FormData();
  for (let item of files) {
    formData.append("file", item);
  }
  const url = `${commonConfig.feedback_host}file/uploadMulti`;
  fetch(url, {
    method: "POST",
    body: formData
  })
    .then(res => res.json())
    .then(result => {
      const { code = -1, dataset, msg = "接口出错" } = result;
      if (code > -1) {
        const { rows } = dataset;
        const savePathStr = rows[0].savePathStr;
        const fileData = savePathStr.split(",").map(item => ({
          sPicturePath: item,
          sPictureName: item.substring(item.indexOf("_") + 1)
        }));
        if (cb) {
          cb(JSON.stringify(fileData));
        }
      } else {
        message.error(msg);
      }
    });
};

// 【接口】提交数据
const handleSubmit = submitData => {
  const url = `${commonConfig.feedback_host}sysworkorder/add`;
  commonServices
    .postValueService("", submitData, url)
    .then(({ data: result = {} }) => {
      _dispatch(["set", { loading: false }]);
      const { code = -1, msg = "接口出错" } = result;
      if (code > -1) {
        message.success(msg);
        _props &&
          _props.onAddWorkOrderSuccess &&
          _props.onAddWorkOrderSuccess();
      } else {
        message.error(msg);
      }
    });
};

export default WorkOrderSystemAdd;
