/*
 * @Author: wangqiang@feewee.cn
 * @Date: 2023-02-10 17:52:44
 * @LastEditors: wangqiang@feewee.cn
 * @LastEditTime: 2023-03-01 14:04:28
 */
import {
  Button,
  DatePicker,
  Divider,
  Form,
  Input,
  message,
  Modal,
  Spin,
} from "antd";
import React, { useEffect, useState } from "react";
import { useStore } from "../index";
import ProDescriptions from "@ant-design/pro-descriptions";
import {
  getIdentifyItemExpandInfoListApi,
  submitIdentifyAuditApi,
} from "@/pages/identify/IdentifyAudit/api";
import moment from "moment";
import FeeweeUploadAttachment from "@/components/FeeweeUploadAttachment";
import DetailItem from "@/pages/ehr/Authentication/Settings/components/DetailItem";

const REMARK_KEY = "fw_other_remark";

export default function IdentifyAuditModal() {
  const { open, setOpen, current, setCurrent, Types, pagination, Type } =
    useStore();
  const [editData, setEditData] = useState<IdentifyAudit.ExpandItem[]>([]);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (open) {
      if (current?.identifyCode && current?.extraData) {
        setLoading(true);
        getIdentifyItemExpandInfoListApi(current.identifyCode)
          .then((res) => {
            const expandListData = res.data || [];
            const _editData: IdentifyAudit.ExpandItem[] = [];
            const extraData: { [key: string]: string } = JSON.parse(
              current.extraData!
            );
            const keys = Object.keys(extraData);
            const fields = {};
            for (let key of keys) {
              const item = expandListData.find((i) => i.name === key);
              _editData.push({
                name: key,
                data: extraData[key],
                ...(item || {}),
              });
              const value =
                item?.type && Types[item.type] === "Date"
                  ? moment(extraData[key])
                  : extraData[key];
              fields[key] = value;
            }

            form.setFieldsValue(fields);
            setEditData(_editData);
            setLoading(false);
          })
          .catch((error) => {
            console.error(error.message);
            message.error("初始化认证审核表单失败");
            setEditData([]);
            setLoading(false);
          });
      }
    }
  }, [open, current]);

  const cancel = () => {
    setCurrent(undefined);
    setOpen(false);
  };

  const submit = (pass: boolean) => {
    form.validateFields().then((val) => {
      const remark = val[REMARK_KEY];
      delete val[REMARK_KEY];
      for (let key of Object.keys(val)) {
        if (typeof val[key] === "object") {
          val[key] = moment(val[key]).format("YYYY-MM-DD HH:mm:ss");
        }
      }
      const auditData = JSON.stringify(val);
      setLoading(true);
      submitIdentifyAuditApi({ id: current?.id, pass, auditData, remark })
        .then((res) => {
          message.success(res.result);
          setLoading(false);
          cancel();
          pagination.setLoading(true);
        })
        .catch((error) => {
          setLoading(false);
          message.error(error.message || "保存认证审核失败");
        });
    });
  };

  return (
    <Modal
      title="认证审核"
      open={open}
      onCancel={cancel}
      footer={[
        <Button loading={loading} onClick={cancel}>
          取消
        </Button>,
        <Button
          loading={loading}
          type="primary"
          danger
          onClick={() => submit(false)}
        >
          拒绝
        </Button>,
        <Button loading={loading} type="primary" onClick={() => submit(true)}>
          通过
        </Button>,
      ]}
      width="50%"
      maskClosable={false}
      afterClose={() => {
        form.resetFields();
      }}
    >
      <ProDescriptions column={2}>
        <ProDescriptions.Item label="资料编码">
          {current?.identifyCode || "-"}
        </ProDescriptions.Item>
        <ProDescriptions.Item label="资料名称">
          {current?.identifyName || "-"}
        </ProDescriptions.Item>
        {pagination.innerParams?.type !== Type.员工认证 ? (
          <ProDescriptions.Item label="会员ID">
            {current?.memberId || "-"}
          </ProDescriptions.Item>
        ) : null}
        {pagination.innerParams?.type !== Type.会员认证 ? (
          <ProDescriptions.Item label="员工ID">
            {current?.staffId || "-"}
          </ProDescriptions.Item>
        ) : null}
        {pagination.innerParams?.type === Type.车辆认证 ? (
          <ProDescriptions.Item label="VIN">
            {current?.vin || "-"}
          </ProDescriptions.Item>
        ) : null}
        <ProDescriptions.Item label="审核原因">
          <span style={{ color: "red" }}>{current?.verify || "-"}</span>
        </ProDescriptions.Item>
      </ProDescriptions>

      <DetailItem
        title="附件"
        desp={
          <div style={{ flex: 1, width: "85%" }}>
            <FeeweeUploadAttachment
              fidList={current?.fids?.split(",")}
              disabled
              style={{ flex: 1 }}
            />
          </div>
        }
      />
      <Divider orientation="left">可编辑审核数据如下</Divider>
      <Spin spinning={loading}>
        <Form form={form}>
          {editData.map((data) => (
            <Form.Item
              name={data.name}
              label={data.label || data.name}
              rules={[
                { required: !!data.label, message: `${data.label}不能为空` },
              ]}
            >
              {data.type && Types[data.type] === "Date" ? (
                // @ts-ignore
                <DatePicker
                  style={{ width: "100%" }}
                  allowClear
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder={`请选择${data.label || data.name}`}
                />
              ) : (
                <Input
                  allowClear
                  placeholder={`请输入${data.label || data.name}`}
                />
              )}
            </Form.Item>
          ))}
          <Divider />
          <Form.Item name={REMARK_KEY} label="备注信息">
            <Input.TextArea
              allowClear
              autoSize={{ minRows: 2 }}
              placeholder="请输入备注信息"
            />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
}
