import { createReportApi, getReportApi, saveReportApi } from "@/api";
import { FormPageFooter, PageContainer } from "@/components";
import { DageEditor, DageLoading } from "@dage/pc-components";
import { Form, Input } from "antd";
import { FC, useEffect, useRef, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";

const PerformanceFormEditPage: FC = () => {
  const location = useLocation();
  const params = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const detail = useRef<any>(null);
  const [form] = Form.useForm();
  const isEdit = location.pathname.indexOf("edit") > -1;

  const getAssDetail = async () => {
    try {
      setLoading(true);
      const data = await createReportApi(params.id as string);
      const jsonAdd = data.reAssess.jsonAdd
        ? JSON.parse(data.reAssess.jsonAdd)
        : null;
      const jsonSub = data.reAssess.jsonSub
        ? JSON.parse(data.reAssess.jsonSub)
        : null;
      form.setFieldsValue({
        name: `${data.reAssess.name}考核报告（${data.reAssess.dateStart}~${data.reAssess.dateEnd}）`,
        rtf: `<h1><strong>${data.reAssess.name}考核报告</strong></h1>
        <h3 style="text-align: left;">基本信息</h3>
        <ul>
            <li style="text-align: left;"><strong>考核名称</strong>：${
              data.reAssess.name
            }</li>
            <li style="text-align: left;"><strong>考核周期</strong>：${
              data.reAssess.dateStart
            } - ${data.reAssess.dateEnd}</li>
            <li style="text-align: left;"><strong>考核说明</strong>：${
              data.reAssess.remark
            }</li>
            <li style="text-align: left;"><strong>发布状态</strong>：${
              data.reAssess.publishStatus
            }</li>
            <li style="text-align: left;"><strong>编辑时间</strong>：${
              data.createTime
            }</li>
            <li style="text-align: left;"><strong>编辑人</strong>：${
              data.creatorName
            }</li>
            <li style="text-align: left;"><strong>总分值</strong>：${
              data.reAssess.score
            }</li>
            <li style="text-align: left;"><strong>评定得分</strong>：${
              data.reAssess.opinionScore
            }</li>
            <li style="text-align: left;"><strong>评定意见</strong>：${
              data.reAssess.opinion
            }</li>
        </ul>
        <hr />
        <h3 style="text-align: left;">考核角色</h3>
        <ul>
            ${data.reDept.map(
              (dept, index) => `
            <li style="text-align: left;"><strong>责任部门${
              index + 1
            }</strong>：</li>
            <ul>
                <li style="text-align: left;"><strong>部门名称</strong>：${
                  dept.name
                }</li>
                <li style="text-align: left;"><strong>博物馆级别</strong>：${
                  dept.levelMuseum
                }</li>
                <li style="text-align: left;"><strong>主管</strong>：${
                  dept.leaderName
                }</li>
                <li style="text-align: left;"><strong>成员</strong>：${
                  dept.crewName
                }</li>
            </ul>
            `
            )}
            <li style="text-align: left;"><strong>评定组成员</strong>：</li>
            <ul>
                <li style="text-align: left;"><strong>评定组</strong>：${
                  data.groupName
                }</li>
                <li style="text-align: left;"><strong>评定人</strong>：${
                  data.groupUser
                }</li>
            </ul>
        </ul>
        <h3 style="text-align: left;">指标清单</h3>
        <table style="width: 100%;">
            <tbody>
                <tr>
                    <td colSpan="1" rowSpan="1" width="100">序号</td>
                    <td colSpan="1" rowSpan="1" width="100">标题</td>
                    <td colSpan="1" rowSpan="1" width="100">说明</td>
                    <td colSpan="1" rowSpan="1" width="100">分值</td>
                    <td colSpan="1" rowSpan="1" width="100">打分点</td>
                    <td colSpan="1" rowSpan="1" width="100">责任部门</td>
                    <td colSpan="1" rowSpan="1" width="100">评定得分</td>
                    <td colSpan="1" rowSpan="1" width="100">评定意见</td>
                </tr>
                ${data.reNorm.map(
                  (norm, index) => `
                <tr>
                    <td colSpan="1" rowSpan="1" width="100">${index + 1}</td>
                    <td colSpan="1" rowSpan="1" width="100">${norm.name}</td>
                    <td colSpan="1" rowSpan="1" width="100">${norm.remark}</td>
                    <td colSpan="1" rowSpan="1" width="100">${norm.num}</td>
                    <td colSpan="1" rowSpan="1" width="100">${
                      norm.isPoint === "1" ? "是" : "否"
                    }</td>
                    <td colSpan="1" rowSpan="1" width="100">${
                      norm.deptName
                    }</td>
                    <td colSpan="1" rowSpan="1" width="100">${
                      norm.opinionScore
                    }</td>
                    <td colSpan="1" rowSpan="1" width="100">${norm.opinion}</td>
                </tr>  
                `
                )}
            </tbody>
        </table>
        <h3 style="text-align: left;">预警指标</h3>
        <ul>
            <li style="text-align: left;"><strong>安全管理</strong>：该指标得分低于设定的预警阈值，需立即采取改进措施。</li>
            <li style="text-align: left;"><strong>说明</strong>：该指标反映了博物馆在安全管理方面存在的潜在风险，建议加强培训与演练。</li>
        </ul>
        ${
          jsonAdd
            ? `
        <h3 style="text-align: left;"><strong>加分项</strong></h3>
        <table style="width: 100%;">
            <tbody>
                <tr>
                    <td colSpan="1" rowSpan="1" width="179">名称</td>
                    <td colSpan="1" rowSpan="1" width="100">指标分值</td>
                    <td colSpan="1" rowSpan="1" width="239">评定得分</td>
                </tr>
                ${jsonAdd.map(
                  (add: any) => `
                <tr>
                    <td colSpan="1" rowSpan="1" width="179">${add.name}</td>
                    <td colSpan="1" rowSpan="1" width="100">${add.num}</td>
                    <td colSpan="1" rowSpan="1" width="239">${add.score}</td>
                </tr>
                `
                )}
            </tbody>
        </table>  
        `
            : ``
        }
        ${
          jsonSub
            ? `
        <h3 style="text-align: left;"><strong>减分项</strong></h3>
        <table style="width: 100%;">
            <tbody>
                <tr>
                    <td colSpan="1" rowSpan="1" width="179">名称</td>
                    <td colSpan="1" rowSpan="1" width="100">可扣分值</td>
                    <td colSpan="1" rowSpan="1" width="239">评定得分</td>
                </tr>
                ${jsonSub.map(
                  (add: any) => `
                <tr>
                    <td colSpan="1" rowSpan="1" width="179">${add.name}</td>
                    <td colSpan="1" rowSpan="1" width="100">${add.num}</td>
                    <td colSpan="1" rowSpan="1" width="239">${add.score}</td>
                </tr>
                `
                )}
            </tbody>
        </table>
        `
            : ""
        }
        `,
      });
    } finally {
      setLoading(false);
    }
  };

  const getDetail = async () => {
    try {
      setLoading(true);
      const data = await getReportApi(params.id as string);
      form.setFieldsValue({
        name: data.name,
        rtf: data.rtf,
      });
      detail.current = data;
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async () => {
    await saveReportApi({
      ...form.getFieldsValue(),
      id: isEdit ? detail.current?.id : undefined,
    });
    navigate(-1);
  };

  useEffect(() => {
    isEdit ? getDetail() : getAssDetail();
  }, []);

  return (
    <PageContainer title={isEdit ? "编辑报告" : "新增报告"}>
      {loading && <DageLoading />}

      <Form form={form} labelCol={{ span: 3 }}>
        <Form.Item
          label="报告标题"
          required
          name="name"
          rules={[{ required: true, message: "请输入报告标题" }]}
        >
          <Input className="w450" placeholder="请输入" allowClear />
        </Form.Item>
        <Form.Item required label="报告正文" name="rtf">
          <DageEditor
            action="/api/cms/assess/file/upload"
            excludeKeys={["group-image", "group-video", "emotion"]}
          />
        </Form.Item>
      </Form>

      <FormPageFooter onSubmit={handleSubmit} onCancel={() => navigate(-1)} />
    </PageContainer>
  );
};

export default PerformanceFormEditPage;
