/* eslint-disable */
import { useEffect, useState, useRef } from "react";
import { Button, Form, Space, Upload, Select, Switch, message, DatePicker, Modal, Spin, Input, Image, InputNumber } from "antd-v4";
import { CheckOutlined, CloseCircleOutlined, EditOutlined, SendOutlined, SaveOutlined, MinusOutlined, ThunderboltOutlined } from "@ant-design/icons";
import BackIcon from "@/assets/back.svg";
import CopyAllIcon from "@/assets/copyallWhite.svg";
import moment from "moment";
import BraftEditor from "braft-editor";
import "braft-editor/dist/index.css";
import gStyles from "@/index.less";
import styles from "./index.less";
import commonConfig from "@/utils/config";
import * as commonUtils from "@/utils/utils";
import AntdDraggableModal from "@/components/Common/AntdDraggableModal";
import WorkOrderSystemService from "./WorkOrderSystemService";
import WorkOrderSystemConfig from "./WorkOrderSystemConfig";

// 主入口
const WorkOrderSystemDetail = props => {
  const [loading, setLoading] = useState(false);
  // 详情弹窗id
  const { current: detailModalId } = useRef("detailModalId_" + Math.random().toString(36).substring(2));

  // 最小化状态
  const [bMin, setBMin] = useState(false);
  window.setBMin = setBMin;
  // 强制更新视图
  const [updater, setUpdater] = useState(0);
  const forceUpdate = () => {
    setUpdater(updater + 1);
  };
  // 刷新页面
  const [refresher, setRefresher] = useState(0);
  const refresh = () => {
    setRefresher(refresher + 1);
  };
  const [form] = Form.useForm();
  const [formEnabled, setFormEnabled] = useState(false);
  const { sId, app, refreshSlaveTable, gdsjurisdiction } = props;
  const { userinfo } = app;
  const { sUserName: sMakePerson } = userinfo;
  const [detailData, setDetailData] = useState({});
  const {
    sTitle,
    fileData = [],
    replyData = [],
    sContentMemo,
    sCustomerId,
    sCustomerName,
    sModuleId,
    sModuleName,
    sHanldeId,
    sRDUserId,
    sCopyHanldeId,
    bVsersion,
    sBug,
    sType,
    tDevHandleDate,
    tHandleDate,
    sStatus,
  } = detailData;

  const [customerOption, setCustomerOption] = useState([]); // 【所属客户】下拉选项
  const [moduleOption, setModuleOption] = useState([]); // 【所属模块】下拉选项
  const [userOption, setUserOption] = useState([]); // 【处理人、抄送人】下拉选项
  const { priorityOption, sBugOption } = WorkOrderSystemConfig; // 各种固定下拉选项
  const [replyModalVisible, setReplyModalVisible] = useState(false); // 回复弹窗状态
  const [assignmentModalVisible, setAssignmentModalVisible] = useState(false); // 指派弹窗状态
  const [resolutionModalVisible, setResolutionModalVisible] = useState(false); // 解决弹窗状态
  const enabled = !["已关闭"].includes(sStatus); // 是否可操作
  const [bSoluted, setSolutedState] = useState(false); // 是否已解决状态

  // 富文本看点击图片事件
  const [imageVisible, setImageVisible] = useState(false);
  const [imageSrc, setImageSrc] = useState(null);
  useEffect(() => {
    const showImage = e => {
      if (e.target && e.target.nodeName === "IMG") {
        const { src } = e.target;
        if (src) {
          setImageSrc(src);
          setImageVisible(true);
        }
      }
    };

    document.addEventListener("dblclick", showImage);
    return () => {
      document.removeEventListener("dblclick", showImage);
    };
  }, []);

  // 判断是否已解决
  useEffect(() => {
    let result = ["已解决"].includes(sStatus);
    if (!result) {
      // 如果状态不是已解决，查看历史记录中最后一个非已指派的是否是已解决
      replyData.forEach(item => {
        const { sResult } = item;
        if (sResult === "已解决") {
          result = true;
        } else if (sResult === "已激活") {
          result = false;
        }
      });
    }
    setSolutedState(result);
  }, [detailData]);

  // 显示的按钮
  const [btnShowData, setBtnShowData] = useState([]);
  // 过滤掉没有权限的按钮
  useEffect(() => {
    let defaultBtnData = ["BtnReplyd", "BtnEdit", "BtnAssign", "BtnSolve", "BtnClose"];
    if (!enabled) {
      setBtnShowData([]);
      return;
    } else if (bSoluted) {
      defaultBtnData = ["BtnAssign", "BtnActive", "BtnClose"];
    }
    if (gdsjurisdiction) {
      gdsjurisdiction.forEach(child => {
        const index = defaultBtnData.findIndex(item => item === child.sAction);
        if (index > -1) {
          defaultBtnData.splice(index, 1);
        }
      });
    }
    setBtnShowData(defaultBtnData);
  }, [gdsjurisdiction, enabled, bSoluted]);

  // 指派/解决
  const addReplyHanle = async values => {
    if (values.sContentMemo === "<p></p>") {
      delete values.sContentMemo;
    }
    const response = await WorkOrderSystemService.addReplyHanle({
      ...values,
      sId,
      sMakePerson,
    });
    setLoading(false);
    if (commonUtils.isNotEmptyObject(response)) {
      refreshSlaveTable();
      if (["已激活"].includes(values.sResult)) {
        refresh();
      } else {
        props.onSaveState({
          workOrderSystemDetailModalVisible: false,
        });
      }
    }
  };

  // 初始化加载数据
  useEffect(() => {
    const handleDetailData = async () => {
      setDetailData(await WorkOrderSystemService.getDetailData({ sId }));
      setCustomerOption(
        (await WorkOrderSystemService.getsCustomerData()).map(item => ({
          label: item.sCustomerName,
          value: item.sCustomerId || item.sId,
          item,
        }))
      );
      setModuleOption(
        (await WorkOrderSystemService.getsModuleData()).map(item => ({
          label: item.sModuleName,
          value: item.sModuleId,
          item,
        }))
      );
      setUserOption(
        (await WorkOrderSystemService.getUserData()).map(item => ({
          label: item.sHanldeName,
          value: item.sHanldeId,
          item,
        }))
      );
    };

    handleDetailData();
  }, [refresher]);

  // detailData变化时，给表单赋值
  useEffect(() => {
    if (commonUtils.isNotEmptyArr(detailData) && commonUtils.isNotEmptyArr(customerOption) && commonUtils.isNotEmptyArr(moduleOption)) {
      const temp = {};
      replyData.forEach((item, index) => {
        const { tCreateDate, sMakePerson: sMakePersonTemp, sResult, sContentMemo: sContentMemoTemp, sAssignedBy } = item;
        temp[`reply${index}`] = (
          <span>
            {index + 1}.{tCreateDate} <span>由</span> <strong>{sMakePersonTemp}</strong> {sResult.replace("已", "")}
            {[""].map(() => {
              if (!sAssignedBy) {
                return "";
              } else if (sAssignedBy && sResult.includes("解决") && sMakePersonTemp === sAssignedBy) {
                return "";
              } else if (sAssignedBy && sResult.includes("解决")) {
                return (
                  <>
                    <span>并指派给 </span>
                    <strong>{sAssignedBy}</strong>
                  </>
                );
              } else {
                return (
                  <>
                    <span>给 </span>
                    <strong>{sAssignedBy}</strong>
                  </>
                );
              }
            })}
          </span>
        );
        if (sContentMemoTemp) {
          temp[`replyContentMemo${index}`] = BraftEditor.createEditorState(sContentMemoTemp);
        }
      });

      const addState = {};
      if (sCustomerId) {
        if (customerOption.find(item => item.value === sCustomerId)) {
          addState.sCustomerId = sCustomerId;
        } else {
          setCustomerOption(prevState => [
            ...prevState,
            {
              value: sCustomerId,
              label: sCustomerName,
              item: {
                sCustomerId,
                sCustomerName,
              },
            },
          ]);
        }
      }

      if (sModuleId) {
        if (moduleOption.find(item => item.value === sModuleId)) {
          addState.sModuleId = sModuleId;
        } else {
          setModuleOption(prevState => [
            ...prevState,
            {
              value: sModuleId,
              label: sModuleName,
              item: {
                sModuleId,
                sModuleName,
              },
            },
          ]);
        }
      }

      form.setFieldsValue({
        sTitle,
        sContentMemo: BraftEditor.createEditorState(sContentMemo),
        ...addState,
        sHanldeId,
        sCopyHanldeId: sCopyHanldeId ? sCopyHanldeId.split(",") : [],
        sRDUserId,
        bVsersion,
        sBug,
        sType: sType !== undefined ? parseInt(sType) : "",
        tDevHandleDate: tDevHandleDate ? moment(tDevHandleDate) : "",
        tHandleDate: tHandleDate ? moment(tHandleDate) : "",
        ...temp,
      });
      forceUpdate();
    }
  }, [detailData, customerOption, moduleOption]);

  const [fileList, setFileList] = useState([]); // 附件列表
  const [fileAdd, setFileAdd] = useState([]); // 新增附件

  // fileData变化时，给附件列表赋值
  useEffect(() => {
    setFileList(
      [...fileData].map(item => {
        const { sId: uid, sPictureName: name, sPicturePath } = item;
        return {
          uid,
          name,
          url: `${commonConfig.feedback_host}file/download?savePathStr=${sPicturePath}&sModelsId=100`,
          status: "done",
          item,
        };
      })
    );
  }, [fileData]);

  // fileAdd变化时，调用新增附件接口
  useEffect(() => {
    if (!fileAdd.length) return;

    const handleFileAdd = async () => {
      setFileAdd([]);
      const _fileData = await WorkOrderSystemService.uploadAdd(fileAdd, {
        sId,
        sMakePerson,
      });
      setFileList([
        ...fileList,
        ..._fileData.map(item => {
          const { sId: uid, sPictureName: name, sPicturePath } = item;
          return {
            uid,
            name,
            url: `${commonConfig.feedback_host}file/download?savePathStr=${sPicturePath}&sModelsId=100`,
            status: "done",
            item,
          };
        }),
      ]);
    };

    handleFileAdd();
  }, [fileAdd]);

  // 附件props
  const uploadProps = {
    accept: "*/*",
    multiple: true,
    fileList,
    disabled: !btnShowData.includes("BtnEdit"),
    beforeUpload: file => {
      setFileAdd(prevState => [...prevState, file]);
      return false;
    },
    onRemove: file => {
      Modal.confirm({
        title: "确认删除",
        onOk() {
          WorkOrderSystemService.deleteFile(file.item, sId, () => {
            setFileList(fileList.filter(item => item.uid !== file.uid));
            message.success("附件删除成功");
          });
        },
      });
    },
  };

  // 回复props
  const replyProps = {
    ...props,
    replyModalVisible,
    detailData,
    detailModalId,
    setReplyModalVisible,
    refresh,
    bMin,
    setBMin,
  };

  // 指派props
  const assignmentProps = {
    ...props,
    bMin,
    setBMin,
    userOption,
    visible: assignmentModalVisible,
    setVisible: setAssignmentModalVisible,
    detailData,
    onFinish: values => {
      setLoading(true);
      setAssignmentModalVisible(false);
      const { value, label } = userOption.find(item => item.value === values.sHanldeId);

      const copyDataAdd = {};
      const copyData = userOption.filter(item => values.sCopyHanldeId.includes(item.value));

      if (commonUtils.isNotEmptyArr(copyData)) {
        copyDataAdd.sCopyFor = copyData.map(item => item.label).toString();
        copyDataAdd.sCopyForId = copyData.map(item => item.value).toString();
      }

      addReplyHanle({
        sAssignedBy: label,
        sAssignedById: value,
        ...copyDataAdd,
        sContentMemo: values.sContentMemo ? values.sContentMemo.toHTML() : "<p></p>",
        sResult: "已指派",
      });
    },
  };

  // 解决props
  const resolutionModalProps = {
    ...props,
    bResolution: true,
    userOption,
    visible: resolutionModalVisible,
    setVisible: setResolutionModalVisible,
    detailData,
    bMin,
    setBMin,
    onFinish: values => {
      setLoading(true);
      setResolutionModalVisible(false);
      const { value, label } = userOption.find(item => item.value === values.sHanldeId);

      const copyDataAdd = {};
      const copyData = userOption.filter(item => values.sCopyHanldeId.includes(item.value));

      if (commonUtils.isNotEmptyArr(copyData)) {
        copyDataAdd.sCopyFor = copyData.map(item => item.label).toString();
        copyDataAdd.sCopyForId = copyData.map(item => item.value).toString();
      }

      addReplyHanle({
        sAssignedBy: label,
        sAssignedById: value,
        dSolveHourSj: values.dSolveHourSj,
        ...copyDataAdd,
        sContentMemo: values.sContentMemo ? values.sContentMemo.toHTML() : "<p></p>",
        sResult: "已解决",
      });
    },
  };

  // 图片弹窗props
  const imageModalProps = {
    imageSrc,
    imageVisible,
    setImageVisible,
  };

  // 修改后保存
  const onFinish = async values => {
    setLoading(true);
    const {
      sContentMemo,
      sCustomerId,
      sModuleId,
      sHanldeId,
      sCopyHanldeId,
      sRDUserId,
      bVsersion,
      sBug,
      sType,
      tDevHandleDate,
      tHandleDate,
      dSolveHour,
    } = values;

    const response = await WorkOrderSystemService.detailUpdate({
      sId,
      sMakePerson,
      sTitle,
      sContentMemo: sContentMemo.toHTML(),
      ...customerOption.find(item => item.value === sCustomerId).item,
      ...moduleOption.find(item => item.value === sModuleId).item,
      ...userOption.find(item => item.value === sHanldeId).item,
      sCopyHanldeId: sCopyHanldeId.toString(),
      sCopyHanldeName: userOption
        .filter(item => sCopyHanldeId.includes(item.value))
        .map(item => item.label)
        .toString(),
      sRDUserId,
      sRDUserName: userOption.find(item => sRDUserId === item.value)?.label,
      bVsersion,
      sBug,
      sType,
      tDevHandleDate: tDevHandleDate ? moment(tDevHandleDate).format("YYYY-MM-DD") : undefined,
      tHandleDate: tDevHandleDate ? moment(tHandleDate).format("YYYY-MM-DD") : undefined,
      dSolveHour,
      sStatus: "已修改",
    });

    setLoading(false);
    if (commonUtils.isNotEmptyObject(response)) {
      setFormEnabled(false);
      refresh();
      refreshSlaveTable();
    }
  };

  return (
    <Spin spinning={loading}>
      <Form
        form={form}
        onFinish={onFinish}
        labelCol={{
          span: 3,
        }}
        wrapperCol={{
          span: 21,
        }}
        className={`${styles.workOrderSystemDetail} ${detailModalId}`}
      >
        <Form.Item
          name="sTitle"
          labelCol={{
            span: 0,
          }}
          wrapperCol={{
            span: 24,
          }}
        >
          <Input.TextArea
            disabled
            bordered={false}
            autoSize={{ minRows: 1, maxRows: 10 }}
            style={{
              fontSize: 16,
              fontWeight: "bold",
              resize: "none",
              color: "#000",
            }}
          />
        </Form.Item>
        <Form.Item
          name="sContentMemo"
          labelCol={{
            span: 0,
          }}
          wrapperCol={{
            span: 24,
          }}
        >
          <BraftEditor className={styles.braftEditorReadOnly} readOnly={true} controls={[]} />
        </Form.Item>

        <Form.Item className={styles.formItemHalf} name="sCustomerId" label="所属客户" rules={[{ required: formEnabled }]}>
          <Select
            allowClear
            showSearch={true}
            options={customerOption}
            optionFilterProp="label"
            placeholder="请选择所属客户"
            disabled={!formEnabled}
          />
        </Form.Item>
        <Form.Item className={styles.formItemHalf} name="sModuleId" label="所属模块" rules={[{ required: formEnabled }]}>
          <Select
            mode={formEnabled ? "tags" : ""}
            showSearch={true}
            options={moduleOption}
            optionFilterProp="label"
            placeholder="请选择所属模块"
            disabled={!formEnabled}
            onChange={value => {
              if (value.length) {
                form.setFieldValue("sModuleId", value[value.length - 1]);
              }
            }}
          />
        </Form.Item>
        <Form.Item className={styles.formItemHalf} name="sHanldeId" label="处理人" rules={[{ required: formEnabled }]}>
          <Select allowClear showSearch={true} options={userOption} optionFilterProp="label" placeholder="请选择处理人" disabled={!formEnabled} />
        </Form.Item>
        <Form.Item className={styles.formItemHalf} name="sCopyHanldeId" label="抄送人">
          <Select
            allowClear
            showSearch={true}
            options={userOption}
            optionFilterProp="label"
            mode="multiple"
            placeholder={formEnabled ? "请选择抄送人" : ""}
            disabled={!formEnabled}
          />
        </Form.Item>
        <Form.Item
          // className={styles.formItemHalf}
          name="sRDUserId"
          label="研发人员"
        >
          <Select allowClear showSearch={true} options={userOption} optionFilterProp="label" placeholder="请选择研发人员" disabled={!formEnabled} />
        </Form.Item>
        <Form.Item className={styles.formItemAQuarter} name="bVsersion" label="标版同样问题" valuePropName="checked">
          <Switch checkedChildren="是" unCheckedChildren="否" disabled={!formEnabled} />
        </Form.Item>
        <Form.Item className={styles.formItemBug} name="sBug" label="是否bug">
          <Select options={sBugOption} optionFilterProp="label" disabled={!formEnabled} />
        </Form.Item>
        <Form.Item className={styles.formItemAQuarter} name="sType" label="优先级">
          <Select
            className={styles.sTypeSelect}
            popupClassName={styles.sTypedDropdown}
            options={priorityOption}
            optionFilterProp="label"
            disabled={!formEnabled}
          />
        </Form.Item>
        <Form.Item
          className={styles.formItemAQuarter1}
          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={formEnabled ? "请选择开发截止日期" : ""} disabled={!formEnabled} />
        </Form.Item>
        <Form.Item
          className={styles.formItemAQuarter1}
          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={formEnabled ? "请选择截止日期" : ""} disabled={!formEnabled} />
        </Form.Item>
        <div className={styles.replyDiv}>
          <div className={styles.replyTitle}>历史记录</div>
          {replyData.map((item, index) => {
            const { sContentMemo: sContentMemoTemp } = item;
            const itemName = `reply${index}`;
            const itemName1 = `replyContentMemo${index}`;
            const itemDom = form.getFieldValue()[itemName];
            return (
              itemDom && (
                <>
                  <Form.Item name={itemName} key={index}>
                    <div style={{ fontSize: 14 }}>{itemDom}</div>
                  </Form.Item>
                  {sContentMemoTemp ? (
                    <Form.Item name={itemName1}>
                      <BraftEditor className={styles.detailBraftEditorReply} readOnly={true} controls={[]} />
                    </Form.Item>
                  ) : (
                    ""
                  )}
                </>
              )
            );
          })}
        </div>
        <Form.Item name="fileData" label="附件" className={styles.annex}>
          <Upload {...uploadProps}>{btnShowData.includes("BtnEdit") && <a>添加附件</a>}</Upload>
        </Form.Item>
        <Form.Item />

        <Form.Item className={styles.fixedBtns}>
          <Space>
            {!formEnabled && (
              <Button
                type="primary"
                icon={<img src={BackIcon} />}
                className={styles.iconBtn}
                style={{ background: "#838A9D", borderColor: "#838A9D" }}
                onClick={() => {
                  props.onSaveState({
                    workOrderSystemDetailModalVisible: false,
                  });
                }}
              >
                返回
              </Button>
            )}
            {!formEnabled && btnShowData.includes("BtnReplyd") && (
              <Button
                type="primary"
                icon={<img src={CopyAllIcon} />}
                className={styles.iconBtn}
                style={{ background: "#ff822d", borderColor: "#ff822d" }}
                onClick={() => {
                  setReplyModalVisible(true);
                }}
              >
                回复
              </Button>
            )}
            {!formEnabled && btnShowData.includes("BtnEdit") && (
              <Button
                type="primary"
                icon={<EditOutlined />}
                className={styles.iconBtn}
                onClick={() => {
                  setFormEnabled(true);
                  document.querySelector(`.${detailModalId}`).scrollTop = 0;
                }}
              >
                修改
              </Button>
            )}
            {formEnabled && (
              <Button
                type="primary"
                htmlType="submit"
                icon={<SaveOutlined />}
                style={{ background: "#ff822d", borderColor: "#ff822d" }}
                className={styles.iconBtn}
              >
                保存
              </Button>
            )}
            {formEnabled && (
              <Button
                type="primary"
                icon={<CloseCircleOutlined />}
                className={styles.iconBtn}
                onClick={() => {
                  setFormEnabled(false);
                  refresh();
                }}
              >
                取消
              </Button>
            )}
            {!formEnabled && btnShowData.includes("BtnAssign") && (
              <Button
                type="primary"
                icon={<SendOutlined />}
                className={styles.iconBtn}
                onClick={() => {
                  setAssignmentModalVisible(true);
                }}
              >
                指派
              </Button>
            )}
            {!formEnabled && btnShowData.includes("BtnSolve") && (
              <Button
                type="primary"
                icon={<CheckOutlined />}
                className={styles.iconBtn}
                onClick={() => {
                  setResolutionModalVisible(true);
                }}
              >
                解决
              </Button>
            )}
            {!formEnabled && btnShowData.includes("BtnActive") && (
              <Button
                type="primary"
                icon={<ThunderboltOutlined />}
                className={styles.iconBtn}
                onClick={() => {
                  addReplyHanle({
                    sResult: "已激活",
                  });
                }}
              >
                激活
              </Button>
            )}
            {!formEnabled && btnShowData.includes("BtnClose") && (
              <Button
                type="primary"
                icon={<CloseCircleOutlined />}
                className={styles.iconBtn}
                onClick={() => {
                  Modal.confirm({
                    title: "确认关闭工单",
                    onOk() {
                      const evaluate = async () => {
                        const result = await WorkOrderSystemService.evaluate({
                          dEvaluate: 5,
                          sId,
                          sMakePerson,
                        });

                        if (result) {
                          refreshSlaveTable();
                          props.onSaveState({
                            workOrderSystemDetailModalVisible: false,
                          });
                        }
                      };
                      evaluate();
                    },
                  });
                }}
              >
                关闭工单
              </Button>
            )}
          </Space>
        </Form.Item>
      </Form>
      {replyModalVisible && <ReplyModal {...replyProps} />}
      {assignmentModalVisible && <AssignmentModal {...assignmentProps} />}
      {resolutionModalVisible && <AssignmentModal {...resolutionModalProps} />}
      {imageVisible && <ImageModal {...imageModalProps} />}
    </Spin>
  );
};

// 回复弹窗
const ReplyModal = props => {
  const { replyModalVisible, detailData, detailModalId, setReplyModalVisible, refresh, bMin, setBMin } = props;
  const { sId, sTitle } = detailData;
  const [loading, setLoading] = useState(false);

  const closeModal = () => {
    setReplyModalVisible(false);
  };

  const onFinish = async values => {
    setLoading(true);
    const { app } = props;
    const { userinfo } = app;
    const { sUserName: sMakePerson, sId: sLoginId } = userinfo;

    const returnData = await WorkOrderSystemService.addReply({
      sContentMemo: values.sContentMemo.toHTML(),
      sMakePerson,
      sLoginId,
      sId,
      status: "回复",
    });
    setLoading(false);
    if (commonUtils.isNotEmptyArr(returnData)) {
      message.success("成功");
      refresh();
      setTimeout(() => {
        document.querySelector(`.${detailModalId}`).scrollTop = 9999;
      }, 500);
      closeModal();
    }
  };

  return (
    replyModalVisible && (
      <AntdDraggableModal
        title={
          <>
            <span>
              {sTitle}
              -回复内容
            </span>
            <Button
              type="link"
              style={{
                position: "absolute",
                right: 30,
                top: 6,
                color: "#4a495f",
              }}
              onClick={() => {
                props.onSaveState({ bMin: true }, () => {
                  setBMin(true);
                });
              }}
            >
              <MinusOutlined />
            </Button>
          </>
        }
        open={replyModalVisible && !bMin}
        className={`${gStyles.workOrderSystemModal} ${styles.replyModal}`}
        style={{ top: "10vh" }}
        width="80vw"
        footer={null}
        onCancel={closeModal}
      >
        <Spin spinning={loading}>
          <Form onFinish={onFinish}>
            <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.replyBraftEditor}
                readOnly={false}
                media={{
                  uploadFn: WorkOrderSystemService.uploadFn,
                }}
              />
            </Form.Item>
            <Form.Item className={styles.flexCener}>
              <Space>
                <Button onClick={closeModal}>取消</Button>
                <Button htmlType="submit" type="primary">
                  确认
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Spin>
      </AntdDraggableModal>
    )
  );
};

// 指派弹窗
const AssignmentModal = props => {
  const { visible, userOption, detailData, onFinish, setVisible, bResolution, setBMin, bMin } = props;
  const { sTitle, sCopyHanldeId } = detailData;
  const initialValues = {
    sCopyHanldeId: sCopyHanldeId ? sCopyHanldeId.split(",") : [],
  };

  const closeModal = () => {
    setVisible(false);
  };

  return (
    visible && (
      <AntdDraggableModal
        title={
          <>
            <span>{bResolution ? "已解决确认" : `${sTitle}-指派人选择`}</span>
            <Button
              type="link"
              style={{
                position: "absolute",
                right: 30,
                top: 6,
                color: "#4a495f",
              }}
              onClick={() => {
                props.onSaveState({ bMin: true }, () => {
                  setBMin(true);
                });
              }}
            >
              <MinusOutlined />
            </Button>
          </>
        }
        open={visible && !bMin}
        className={`${gStyles.workOrderSystemModal} ${styles.assignmentModal}`}
        style={{ top: "10vh" }}
        width="80vw"
        footer={null}
        onCancel={closeModal}
      >
        <Form
          initialValues={initialValues}
          onFinish={onFinish}
          labelCol={{
            span: 2,
          }}
          wrapperCol={{
            span: 22,
          }}
        >
          <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 mode="multiple" showSearch={true} options={userOption} optionFilterProp="label" placeholder="请选择抄送人" />
          </Form.Item>
          {bResolution ? (
            <Form.Item name="dSolveHour" label="研发时间" rules={[{ required: true }]}>
              <InputNumber addonAfter="小时" style={{ width: 200 }} />
            </Form.Item>
          ) : (
            ""
          )}
          <Form.Item name="sContentMemo" label="备注">
            <BraftEditor
              className={styles.replyBraftEditor}
              readOnly={false}
              media={{
                uploadFn: WorkOrderSystemService.uploadFn,
              }}
            />
          </Form.Item>

          <Form.Item className={styles.flexCener}>
            <Space>
              <Button onClick={closeModal}>取消</Button>
              <Button htmlType="submit" type="primary">
                确认
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </AntdDraggableModal>
    )
  );
};

// 图片弹窗
const ImageModal = ({ imageSrc, imageVisible, setImageVisible }) => {
  return (
    <Image
      style={{ display: "none" }}
      preview={{
        visible: imageVisible,
        scaleStep: 0.2,
        src: imageSrc,
        onVisibleChange: () => {
          setImageVisible(false);
        },
      }}
    />
  );
};

export default WorkOrderSystemDetail;
