import { FC, Key, useEffect, useRef, useState } from "react";
import {
  Button,
  Empty,
  Input,
  InputNumber,
  Modal,
  ModalProps,
  Radio,
  Tag,
} from "antd";
import { MaterialType, REVIEW_MATERIAL_TYPE, YES_OR_NO } from "@/types";
import { getBaseURL } from "@dage/service";
import { getFileListApi, normEvaOpinionApi } from "@/api";
import { downloadFile } from "@/utils";
import { DageLoading, DageTableActions } from "@dage/pc-components";
import {
  EditableProTable,
  ProForm,
  ProFormInstance,
} from "@ant-design/pro-components";
import style from "./index.module.scss";
import { REVIEW_MATERIAL_STATUS_MAP } from "@/constants";

export interface IndexDetailFormModalProps extends Omit<ModalProps, "onOk"> {
  id: number;
  deptNormId: number;
  title: string;
  moduleId: number;
  /** 是否显示评定得分输入 */
  showScoreInput?: boolean;
  initScore?: number;
  onCancel?: () => void;
  onOk?: () => void;
}

const { TextArea } = Input;

export const IndexDetailFormModal: FC<IndexDetailFormModalProps> = ({
  open,
  id,
  deptNormId,
  title,
  moduleId,
  showScoreInput,
  initScore,
  onOk,
  onCancel,
  ...rest
}) => {
  const baseUrl = getBaseURL();
  const formRef = useRef<ProFormInstance<any>>();
  const [loading, setLoading] = useState(false);
  const [btnLoading, setBtnLoading] = useState(false);
  const [list, setList] = useState<MaterialType[]>([]);
  const [editableKeys, setEditableKeys] = useState<Key[]>([]);

  const handleCancel = () => {
    onCancel?.();
  };

  const getList = async () => {
    try {
      setLoading(true);
      const data = await getFileListApi(moduleId, "norm", id);
      setList(data.filter((i) => i.module === "norm"));

      const temp: Record<number, MaterialType[]> = {};
      data
        .filter((i) => i.module === "fill-norm")
        .forEach((item) => {
          if (!item.parentId) return;
          if (Array.isArray(temp[item.parentId]))
            temp[item.parentId].push(item);
          else temp[item.parentId] = [item];
        });

      const k: number[] = [];
      const keys = Object.keys(temp).map((key) => Number(key));
      keys.forEach((id) => {
        formRef.current?.setFieldValue(id, temp[id]);
        k.push(...temp[id].map((i) => i.id));
      });
      setEditableKeys(k);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async () => {
    if (!(await formRef.current?.validateFields())) return;

    const res = formRef.current?.getFieldsValue();
    const keys = Object.keys(res).filter((key) => !isNaN(Number(key)));
    const mats: any[] = [];

    try {
      setBtnLoading(true);
      keys.forEach((id) => {
        const list = res[id];
        list?.forEach((item: any) => {
          mats.push({
            materialId: item.id,
            condition: item.status,
            opinion: item.opinion,
          });
        });
      });
      await normEvaOpinionApi({
        opinionScore: res.score,
        mats,
        deptNormId,
        deptId: moduleId,
      });
      onOk?.();
    } finally {
      setBtnLoading(false);
    }
  };

  useEffect(() => {
    if (open) {
      getList();
      formRef.current?.setFieldValue("score", initScore);
    }
  }, [open]);

  return (
    <Modal
      className={style.modal}
      title={title}
      open={open}
      width={1000}
      footer={!list.length ? null : undefined}
      maskClosable={false}
      okText="提交"
      okButtonProps={{
        disabled: btnLoading,
      }}
      onOk={handleSubmit}
      onCancel={handleCancel}
      {...rest}
    >
      {loading && <DageLoading />}

      {!list.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}

      <ProForm
        formRef={formRef}
        layout="horizontal"
        submitter={false}
        style={{ marginTop: 30 }}
      >
        {showScoreInput && Boolean(list.length) && (
          <ProForm.Item
            name="score"
            label="评定得分"
            required
            rules={[{ required: true, message: "此项为必填项" }]}
          >
            <InputNumber
              min={0}
              max={50}
              precision={1}
              className="w450"
              placeholder="请输入0~50的数字，支持小数点后一位"
            />
          </ProForm.Item>
        )}

        {list.map((item) => {
          const isUpload = item.isUpload === YES_OR_NO.YES;

          return (
            <div key={item.id} className={style.fileUpload}>
              <div className={style.fileUploadHeader}>
                <div className={style.fileUploadHeaderInfo}>
                  <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>
              </div>

              <EditableProTable
                rowKey="id"
                name={item.id}
                className="cus-table"
                columns={[
                  {
                    title: "附件名称",
                    dataIndex: "fileName",
                    align: "center",
                    editable: false,
                  },
                  {
                    title: "责任部门",
                    dataIndex: "deptName",
                    align: "center",
                    editable: false,
                  },
                  {
                    title: "上传用户",
                    dataIndex: "creatorName",
                    align: "center",
                    editable: false,
                  },
                  {
                    title: "上传时间",
                    dataIndex: "updateTime",
                    align: "center",
                    editable: false,
                  },
                  {
                    title: "评定结果",
                    align: "center",
                    dataIndex: "status",
                    formItemProps: () => {
                      return {
                        rules: [
                          {
                            validator(rule, value) {
                              if (value === 0) {
                                return Promise.reject("此项为必选项");
                              } else {
                                return Promise.resolve();
                              }
                            },
                          },
                        ],
                      };
                    },
                    renderFormItem: () => (
                      <Radio.Group
                        options={[
                          {
                            value: REVIEW_MATERIAL_TYPE.PASS,
                            label:
                              REVIEW_MATERIAL_STATUS_MAP[
                                REVIEW_MATERIAL_TYPE.PASS
                              ],
                          },
                          {
                            value: REVIEW_MATERIAL_TYPE.FAIL,
                            label:
                              REVIEW_MATERIAL_STATUS_MAP[
                                REVIEW_MATERIAL_TYPE.FAIL
                              ],
                          },
                        ]}
                      />
                    ),
                  },
                  {
                    title: "评定意见",
                    width: 300,
                    dataIndex: "opinion",
                    align: "center",
                    formItemProps: () => {
                      return {
                        rules: [{ required: true, message: "此项为必填项" }],
                      };
                    },
                    renderFormItem: () => (
                      <TextArea
                        showCount
                        rows={6}
                        maxLength={500}
                        style={{ marginBottom: 20 }}
                        placeholder="请输入内容，最多500字"
                      />
                    ),
                  },
                  {
                    title: "操作",
                    align: "center",
                    editable: false,
                    render: (val) => (
                      <DageTableActions
                        renderBefore={
                          <Button
                            size="small"
                            type="link"
                            onClick={() =>
                              downloadFile(
                                baseUrl +
                                  process.env.REACT_APP_IMG_PUBLIC +
                                  item.filePath,
                                item.fileName
                              )
                            }
                          >
                            下载
                          </Button>
                        }
                        showEdit={false}
                        showDelete={false}
                      />
                    ),
                  },
                ]}
                recordCreatorProps={{
                  style: {
                    display: "none",
                  },
                  // @ts-ignore
                  record: () => ({}),
                }}
                editable={{
                  type: "multiple",
                  editableKeys,
                }}
              />
            </div>
          );
        })}
      </ProForm>
    </Modal>
  );
};
