import { Button, Form, Radio, Table, Tag } from "antd";
import { FC, useEffect, useMemo, useRef, useState } from "react";
import classNames from "classnames";
import {
  DageFileResponseType,
  DageTableActions,
  DageUpload,
  DageUploadConsumer,
  DageUploadProvider,
  DageUploadType,
} from "@dage/pc-components";
import { SubEvaluationModal } from "../SubEvaluationModal";
import style from "./index.module.scss";
import {
  DEPT_STATUS_ENUM,
  IManageFormDetail,
  IManageIndexDetail,
  MaterialType,
  REVIEW_MATERIAL_TYPE,
  YES_OR_NO,
} from "@/types";
import { downloadFile, beforeUpload } from "@/utils";
import { getBaseURL } from "@dage/service";
import {
  additionalEvaOpinionApi,
  assessmentEvaOpinionApi,
  changeMaterialConditionApi,
  deleteFileApi,
  getFileListApi,
  materialEvaOpinionApi,
  saveManageFileApi,
} from "@/api";
import { EvaluationFormModal } from "../EvaluationFormModal";
import { ColumnsType } from "antd/es/table";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { REVIEW_MATERIAL_STATUS_MAP } from "@/constants";

export interface OverallAssessmentProps {
  detail: IManageIndexDetail | IManageFormDetail | null;
  isReportDetail?: boolean;
  isEvalutionDetail?: boolean;
  isIndexDetail?: boolean;
  refreshDetail(): void;
}

export const OverallAssessment: FC<OverallAssessmentProps> = ({
  detail,
  isIndexDetail,
  isReportDetail,
  isEvalutionDetail,
  refreshDetail,
}) => {
  const { userInfo } = useSelector<RootState, RootState["base"]>(
    (state) => state.base
  );
  const baseUrl = getBaseURL();
  // 是否能够上传附件
  const canUpload = [
    DEPT_STATUS_ENUM.PENDING_SUBMIT,
    DEPT_STATUS_ENUM.RETURN,
  ].includes((detail as IManageFormDetail)?.deptStatus);
  // 是否退回状态
  const isRefund =
    (detail as IManageFormDetail)?.deptStatus === DEPT_STATUS_ENUM.RETURN;
  // 当前评定的类型
  const curEvaluationData = useRef<{
    type: "material" | "assessment";
    id: number;
  } | null>(null);
  const [initEvaluationContent, setInitEvaluationContent] = useState("");
  const [subEvaluationVisible, setSubEvaluationVisible] = useState(false);
  const [evaluationVisible, setEvaluationVisible] = useState(false);
  // 选中的附加项
  const checkedAddItem = useRef<any>(null);
  const checkedAddIndex = useRef(0);
  // 加分项
  const addList = useMemo(() => {
    if (!detail || !detail.jsonAdd) return [];
    return JSON.parse(detail.jsonAdd);
  }, [detail]);
  // 减分项
  const subList = useMemo(() => {
    if (!detail || !detail.jsonSub) return [];
    return JSON.parse(detail.jsonSub);
  }, [detail]);
  const [loading, setLoading] = useState(false);
  // 已上传附件映射
  const [uploadedFileMap, setUploadedFileMap] = useState<
    Record<number, MaterialType[]>
  >({});
  const fileColumns = useMemo(() => {
    const stack: ColumnsType<MaterialType> = [
      {
        title: "附件名称",
        dataIndex: "fileName",
        align: "center",
      },
      {
        title: "责任部门",
        dataIndex: "deptName",
        align: "center",
      },
      {
        title: "上传用户",
        dataIndex: "creatorName",
        align: "center",
      },
      {
        title: "操作",
        align: "center",
        render: (val) => (
          <DageTableActions
            renderBefore={
              <Button
                size="small"
                type="link"
                onClick={() => {
                  downloadFile(
                    baseUrl + process.env.REACT_APP_IMG_PUBLIC + val.filePath,
                    val.fileName
                  );
                }}
              >
                下载
              </Button>
            }
            showDelete={isReportDetail && canUpload}
            showEdit={false}
            onDelete={handleDeleteFile.bind(undefined, val.id)}
          />
        ),
      },
    ];

    if (isEvalutionDetail || (isReportDetail && isRefund)) {
      stack.splice(
        2,
        0,
        {
          title: "评定结果",
          align: "center",
          render: (item: MaterialType) => {
            if (
              item.status === REVIEW_MATERIAL_TYPE.PENDING &&
              !isEvalutionDetail
            )
              return "";

            return isRefund ? (
              <Tag
                color={
                  item.status === REVIEW_MATERIAL_TYPE.PASS
                    ? "success"
                    : "error"
                }
              >
                {REVIEW_MATERIAL_STATUS_MAP[item.status]}
              </Tag>
            ) : (
              <Radio.Group
                defaultValue={item.status}
                options={[
                  {
                    label: "合格",
                    value: REVIEW_MATERIAL_TYPE.PASS,
                  },
                  {
                    label: "不合格",
                    value: REVIEW_MATERIAL_TYPE.FAIL,
                  },
                ]}
                onChange={(v) => {
                  changeMaterialConditionApi({
                    condition: v.target.value,
                    deptId: detail!.id,
                    materialId: item.id,
                  });
                }}
              />
            );
          },
        },
        {
          title: "评定意见",
          align: "center",
          render: (val) =>
            isRefund ? (
              val.opinion
            ) : (
              <Button
                type="link"
                onClick={() => {
                  curEvaluationData.current = {
                    type: "material",
                    id: val.id,
                  };
                  setInitEvaluationContent(val.opinion);
                  setEvaluationVisible(true);
                }}
              >
                填写
              </Button>
            ),
        }
      );
    } else {
      stack.splice(2, 0, {
        title: "编辑时间",
        dataIndex: "updateTime",
        align: "center",
      });
    }

    return stack;
  }, [detail]);
  const additionalColumns: ColumnsType<any> = [
    {
      title: "评定得分",
      dataIndex: "score",
      align: "center",
    },
    {
      title: "评定人",
      dataIndex: "assessor",
      align: "center",
    },
    {
      title: "评定意见",
      dataIndex: "comment",
      align: "center",
    },
    {
      title: "操作",
      align: "center",
      hidden: !isEvalutionDetail,
      render: (item, record, index) => (
        <Button
          type="link"
          onClick={openSubEvaluationModal.bind(undefined, index, item)}
        >
          评定
        </Button>
      ),
    },
  ];

  const getList = async () => {
    try {
      setLoading(true);
      const data = await getFileListApi(
        isIndexDetail ? detail!.id : (detail as IManageFormDetail).accessId,
        "assess",
        detail!.id
      );
      const temp: typeof uploadedFileMap = {};
      data.forEach((item) => {
        if (!item.parentId) return;
        if (Array.isArray(temp[item.parentId])) temp[item.parentId].push(item);
        else temp[item.parentId] = [item];
      });
      setUploadedFileMap(temp);
    } finally {
      setLoading(false);
    }
  };

  const saveManageFile = async (
    item: MaterialType,
    list: DageFileResponseType[]
  ) => {
    // @ts-ignore
    const li = list.filter((i) => i.status === "done" && !i.uploaded);

    for (let i = 0; i < li.length; i++) {
      const file = li[i];

      if (!file.response) return;

      await saveManageFileApi({
        name: file.name,
        fileName: file.response.fileName,
        filePath: file.response.filePath,
        level: 2,
        suffix: item.suffix,
        parentId: item.id,
        module: "fill-assess",
        moduleId: (detail as IManageFormDetail).accessId,
        deptId: detail?.id,
        assessId: (detail as IManageFormDetail).accessId,
      });
      // @ts-ignore
      file.uploaded = true;
    }

    getList();
  };

  const handleDeleteFile = async (id: number) => {
    await deleteFileApi(id);
    getList();
  };

  const handleSubmitEvaluation = async (val: any) => {
    if (!curEvaluationData.current) return;

    if (curEvaluationData.current.type === "assessment") {
      await assessmentEvaOpinionApi({
        deptId: curEvaluationData.current.id,
        ...val,
      });
    } else {
      await materialEvaOpinionApi({
        deptId: detail!.id,
        materialId: curEvaluationData.current.id,
        ...val,
      });
    }
    refreshDetail();
  };

  const openSubEvaluationModal = (index: number, item: any) => {
    checkedAddIndex.current = index;
    checkedAddItem.current = item;
    setSubEvaluationVisible(true);
  };

  const handleAdditionalEvalution = async (vals: any) => {
    const temp = [...addList];
    temp.splice(checkedAddIndex.current, 1, {
      ...checkedAddItem.current,
      ...vals,
      assessor: userInfo?.user.realName,
    });
    await additionalEvaOpinionApi({
      assessId: (detail as IManageFormDetail).accessId,
      deptId: detail!.id,
      opinionJson: JSON.stringify(temp),
      type: checkedAddItem.current.id.indexOf("bonus") > -1 ? "add" : "sub",
    });
    refreshDetail();
  };

  useEffect(() => {
    if (!detail) return;
    getList();
  }, [detail]);

  return (
    <Form
      labelCol={{ offset: 1, span: 3 }}
      wrapperCol={{
        offset: 1,
      }}
      colon={false}
      className={classNames(style.form, "mw1125")}
    >
      <Form.Item label="考核说明">
        <p>{detail?.remark || "--"}</p>
      </Form.Item>

      {!isReportDetail && (
        <>
          <Form.Item label="考核进度">
            <Table
              pagination={false}
              className="cus-table"
              dataSource={detail?.plan}
              rowKey="deptId"
              columns={[
                {
                  title: "部门名称",
                  dataIndex: "name",
                  align: "center",
                },
                {
                  title: "分配指标数量",
                  dataIndex: "pcsNorm",
                  align: "center",
                },
                {
                  title: "完成填报数量",
                  dataIndex: "pcsFill",
                  align: "center",
                },
                {
                  title: "部门考核状态",
                  align: "center",
                  // @ts-ignore
                  render: (val) => REVIEW_MATERIAL_STATUS_MAP[val.status],
                },
              ]}
            />
          </Form.Item>

          <Form.Item label="评定意见">
            {isEvalutionDetail ? (
              <Button
                type="primary"
                onClick={() => {
                  curEvaluationData.current = {
                    type: "assessment",
                    id: detail!.id,
                  };
                  setInitEvaluationContent(detail!.opinion);
                  setEvaluationVisible(true);
                }}
              >
                填写
              </Button>
            ) : (
              <p>
                1、
                工作中具有独立思考、不断创新的能力。对工作有高度的事业心和责任感，积极主动工作，认真履行自己的职责。
                2、
                该同志工作态度端正，对工作有高度的事业心和责任感，政治立场坚定，方向明确，忠诚并献身于党和人民的教育事业，治学严谨，热爱学生，以身作则，为人师表。
                3、
                该同志遵纪守法，具有良好的社会公德和家庭美德，有高尚的职业道德，关爱学生，面向全体学生，注重学生的全面发展，认真履行教师职务职责，有强烈的服务意识。
                4、
                该同志政治立场坚定，教育思想端正，专业知识及基本功扎实过硬，具有很强的表达能力，善于做思想政治工作。严格遵守学校的作息时间和工作纪律，全身心地投入工作。
              </p>
            )}
          </Form.Item>
        </>
      )}

      <Form.Item label="资料上传">
        {(detail?.materials?.filter((i) => i.module === "assess") || []).map(
          (item) => {
            const isUpload = item.isUpload === YES_OR_NO.YES;

            return (
              <div key={item.id} className={style.fileUpload}>
                <div className={style.fileUploadHeader}>
                  <div>
                    <Tag color={isUpload ? "red" : ""}>
                      {isUpload ? "必填" : "选填"}
                    </Tag>
                    <h3>
                      {item.name} | {item.suffix || "*"}
                    </h3>
                  </div>
                  <Button
                    type="primary"
                    ghost
                    onClick={() =>
                      downloadFile(
                        baseUrl +
                          process.env.REACT_APP_IMG_PUBLIC +
                          item.filePath,
                        item.fileName
                      )
                    }
                  >
                    下载模板
                  </Button>
                  {canUpload && !isEvalutionDetail && (
                    <DageUploadProvider>
                      <DageUploadConsumer>
                        {(res) => (
                          <DageUpload
                            className={classNames(style.uploadBtn, "no-list")}
                            dType={DageUploadType.DOC}
                            action="/api/cms/fill/file/upload"
                            // @ts-ignore
                            accept={item.suffix}
                            // @ts-ignore
                            beforeUpload={beforeUpload.bind(
                              undefined,
                              item.suffix
                            )}
                            onChange={saveManageFile.bind(undefined, item)}
                          >
                            <Button
                              type="primary"
                              ghost
                              loading={res?.uploading}
                            >
                              上传附件
                            </Button>
                          </DageUpload>
                        )}
                      </DageUploadConsumer>
                    </DageUploadProvider>
                  )}
                </div>

                <Table
                  rowKey="id"
                  loading={loading}
                  className="cus-table"
                  pagination={false}
                  dataSource={uploadedFileMap[item.id]}
                  columns={fileColumns}
                />
              </div>
            );
          }
        )}
      </Form.Item>

      {!isReportDetail && (
        <Form.Item label="附加项">
          <Table
            rowKey="id"
            className="cus-table"
            pagination={false}
            dataSource={addList}
            columns={[
              {
                title: "加分项名称",
                dataIndex: "name",
                align: "center",
              },
              {
                title: "指标分值",
                dataIndex: "num",
                align: "center",
              },
              ...additionalColumns,
            ]}
          />

          <Table
            rowKey="id"
            style={{ marginTop: 20 }}
            className="cus-table"
            pagination={false}
            dataSource={subList}
            columns={[
              {
                title: "减分项名称",
                dataIndex: "name",
                align: "center",
              },
              {
                title: "可扣分值",
                dataIndex: "num",
                align: "center",
              },
              ...additionalColumns,
            ]}
          />
        </Form.Item>
      )}

      <SubEvaluationModal
        open={subEvaluationVisible}
        onOk={handleAdditionalEvalution}
        onCancel={() => setSubEvaluationVisible(false)}
      />

      <EvaluationFormModal
        initContent={initEvaluationContent}
        open={evaluationVisible}
        onOk={handleSubmitEvaluation}
        onCancel={() => setEvaluationVisible(false)}
      />
    </Form>
  );
};
