import {
  Form,
  Modal,
  Row,
  Col,
  Input,
  DatePicker,
  Icon,
  Button,
  Divider,
  Steps,
  Select,
  TreeSelect,
  InputNumber,
  Upload,
  Space,
} from 'antd';
import ModuleTitle from '../../../components/ModuleTitle/moduleTitle';
import { useEffect, useMemo, useState } from 'react';
import { queryDepList, querySupplierList } from '@/services/contract';
import { useModel, useRequest } from '@umijs/max';
import { CloudUploadOutlined } from '@ant-design/icons';
import styles from '../index.less';
import dayjs from 'dayjs';
export const Type = {
  add: 0, //新增
  detail: 1, //详情
  cancel: 2, //作废
  check: 3, //审核
};

export const StatusText = [
  '',
  '待审核',
  '审核拒绝',
  '已存档',
  '作废待审核',
  '作废拒绝',
  '已作废',
];
export const Status = {
  None: 0,
  Checking: 1,
  CheckReject: 2,
  CheckSuccess: 3,
  CalChecking: 4,
  CalCheckReject: 5,
  CalCheckSuccess: 6,
};

const ContractModal = (props) => {
  const [form] = Form.useForm();
  const { user } = useModel('userInfo');
  const { userList, run: userListRun } = useModel('userList');
  const { depList, run: depListRun } = useModel('depList');
  const FORMAT = 'YYYY-MM-DD';
  const {
    detail: data,
    type,
    visible,
    projectList = [],
    handleOk,
    handleCancel,
    parent_id,
  } = props;
  const title =
    type == Type.add ? '新增' : type == Type.detail ? '详情' : '作废';
  //所属公司为总部时才能选择部门，为子公司时，部门不能操作  所属部门为子公司的需要填经办人
  const company = Form.useWatch('company_id', form);
  const [depDisable, setDepDisable] = useState(false);
  const [dealDisable, setDealDisable] = useState(false);
  //项目名称选择后，自动填入对应的项目编号
  const project_name = Form.useWatch('project_name', form);

  const [isPass, setIsPass] = useState(1);

  const [fileList, setFileList] = useState([]);

  useEffect(() => {
    userListRun();
    depListRun();
  }, []);

  useEffect(() => {
    form.resetFields();
  }, [data]);

  //供应商列表
  const { data: supplierList = [], loading } = useRequest(querySupplierList, {
    defaultParams: [
      {
        project_id: 1,
        is_super: false,
      },
    ],
    formatResult: (data) => {
      return data?.list
        ? data.list.map((item) => {
            return { ...item, Name: item.name };
          })
        : [];
    },
  });

  console.log('======================', data);

  useEffect(() => {
    if (company == 135) {
      setDepDisable(false);
      setDealDisable(false);
    } else {
      setDepDisable(true);
      setDealDisable(true);
      form.setFieldsValue({ deal_by: user?.CName });
    }
  }, [company]);
  useEffect(() => {
    const project_code = projectList?.find(
      (item) => item.project_name == project_name,
    )?.project_full_code;
    if (project_code) form.setFieldsValue({ project_code });
  }, [project_name]);

  const supplyList = useMemo(() => {
    return depList ? [...depList, ...supplierList] : supplierList;
  }, [depList, supplierList]);

  const disableds = useMemo(() => {
    if (!visible) {
      setFileList([]);
      setIsPass(1);
      setDepDisable(false);
      setDealDisable(false);
    }
    if (type == Type.add) {
      return { contract: false, check: true };
    } else if (type == Type.detail) {
      return { contract: true, check: true };
    } else if (type == Type.cancel) {
      return { contract: true, check: true };
    }
    return { contract: true, check: false };
  }, [type, visible]);

  const UploadProps = {
    action: `/api/contract/v1/attach`,
    headers: {
      'JWT-TOKEN': localStorage.getItem('JWT-TOKEN'),
    },
    onChange({ file, fileList }) {
      if (file.status !== 'uploading') {
        console.log(file, fileList);
        setFileList(fileList.map((item) => item.response?.data?.attach));
      }
    },
  };

  const handleSubmit = () => {
    form.validateFields().then((values) => {
      if (type == Type.add) {
        values.effect_on = dayjs(values.effect_on).format(FORMAT);
        values.created_on = values.created_on || dayjs().format(FORMAT);
        if (parent_id) values.parent_id = parent_id;
        if (values.amount || values.amount == 0)
          values.amount = values.amount + '';
        if (fileList.length > 0) values.attach = JSON.stringify(fileList);
        if (values.party_c && values.party_c.length > 0)
          values.party_c = values.party_c.join(',');
        if (values.company_id == 135 && values.dep_id) {
          const item = getDepItemById(values.dep_id);
          if (item) {
            values.dep_name = item.Name;
            values.dep_code = item.Code;
          }
          const companyItem = getDepItemById(values.company_id);
          if (companyItem) values.company_name = companyItem.Name;
        } else if (values.company_id) {
          const item = getDepItemById(values.company_id);
          if (item) {
            values.company_name = item.Name;
            values.company_code = item.Code;
          }
        }
        values.created_by = user?.ID;
        handleOk(values);
      } else if (type == Type.cancel) {
        let result = {
          id: data?.id,
          cancel_desc: values.cancel_desc,
        };
        handleOk(result);
      } else if (type == Type.check && data?.status == Status.Checking) {
        let result = {
          id: data?.id,
          check_by: user.CName,
          check_result: values.check_result,
          is_pass: values.is_pass,
          check_desc: values?.check_desc,
        };
        handleOk(result);
      }
    });
  };

  const getDepItemById = (id) => {
    const fun = (list) => {
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        if (item.ID == id) {
          return item;
        } else if (item.children?.length > 0) {
          let res = fun(item.children);
          if (res) return res;
        }
      }
    };
    return fun(depList);
  };

  return (
    <Modal
      width={'85%'}
      title={title}
      open={visible}
      okText="提交"
      cancelText="返回"
      onOk={handleSubmit}
      onCancel={handleCancel}
      okButtonProps={type == Type.detail ? { disabled: true } : null}
      destroyOnClose
    >
      <Divider />
      <ModuleTitle title="合同信息" />
      <Form
        form={form}
        // initialValues={data}
        labelCol={{ span: 7 }}
        wrapperCol={{ span: 17 }}
      >
        <Row>
          <Col span={10} offset={1}>
            <Form.Item
              name="company_id"
              label="所属公司："
              tooltip="所属公司"
              initialValue={data?.company_id}
              rules={[
                {
                  required: true,
                  message: '请填写所属公司',
                },
              ]}
            >
              <TreeSelect
                style={{ width: '100%' }}
                placeholder="请选择"
                showSearch
                allowClear
                fieldNames={{
                  label: 'Name',
                  value: 'ID',
                  children: 'children',
                }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={depList}
                disabled={disableds.contract}
              />
            </Form.Item>
            <Form.Item
              name="name"
              label="合同名称："
              tooltip="合同名称"
              initialValue={data?.name}
              rules={[
                {
                  required: true,
                  message: '请填写合同名称',
                },
              ]}
            >
              <Input disabled={disableds.contract} />
            </Form.Item>
            <Form.Item
              name="effect_on"
              label="合同生效日期："
              initialValue={data?.effect_on}
              rules={[
                {
                  required: true,
                  message: '请填写合同名称',
                },
              ]}
            >
              {type == Type.add ? (
                <DatePicker
                  style={{ width: '100%' }}
                  disabled={disableds.contract}
                />
              ) : (
                <Input disabled={disableds.contract} />
              )}
            </Form.Item>
            <Form.Item
              name="project_name"
              label="项目名称："
              initialValue={data?.project_name}
              rules={[
                {
                  required: true,
                  message: '请填写项目名称',
                },
              ]}
            >
              <Select
                style={{ width: '100%' }}
                placeholder="请选择"
                options={projectList?.map((item) => {
                  return {
                    value: item.project_name,
                    label: item.project_name,
                  };
                })}
                disabled={disableds.contract}
              />
            </Form.Item>
            <Form.Item
              name="party_a"
              label="甲方："
              initialValue={data?.party_a}
              rules={[
                {
                  required: true,
                  message: '请选择甲方',
                },
              ]}
            >
              <TreeSelect
                style={{ width: '100%' }}
                placeholder="请选择"
                showSearch
                allowClear
                fieldNames={{
                  label: 'Name',
                  value: 'Name',
                  children: 'children',
                }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={supplyList}
                disabled={disableds.contract}
              />
            </Form.Item>
            <Form.Item
              name="party_c"
              label="丙方（及其他）："
              initialValue={data?.party_c ? JSON.parse(data?.party_c) : []}
              rules={[
                {
                  required: true,
                  message: '请选择（支持多选）',
                },
              ]}
            >
              <TreeSelect
                style={{ width: '100%' }}
                placeholder="请选择"
                showSearch
                multiple
                allowClear
                fieldNames={{
                  label: 'Name',
                  value: 'Name',
                  children: 'children',
                }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={supplyList}
                disabled={disableds.contract}
              />
            </Form.Item>
            <Form.Item
              name="created_dep"
              label="签约承办部门："
              initialValue={data?.created_dep}
              rules={[
                {
                  required: true,
                  message: '请选择签约承办部门',
                },
              ]}
            >
              <TreeSelect
                style={{ width: '100%' }}
                placeholder="请选择"
                showSearch
                allowClear
                disabled={disableds.contract}
                fieldNames={{
                  label: 'Name',
                  value: 'Name',
                  children: 'children',
                }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={depList?.find((item) => item.Code == 'GT')?.children}
              />
            </Form.Item>
          </Col>
          <Col span={10}>
            <Form.Item
              name="dep_id"
              label="所属部门："
              initialValue={data?.dep_id}
            >
              <TreeSelect
                style={{ width: '100%' }}
                placeholder="请选择"
                showSearch
                allowClear
                fieldNames={{
                  label: 'Name',
                  value: 'ID',
                  children: 'children',
                }}
                disabled={disableds.contract || depDisable}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={depList?.find((item) => item.Code == 'GT')?.children}
              />
            </Form.Item>
            {/* {type != Type.add && ( */}
            <Form.Item name="code" initialValue={data?.code} label="合同编号：">
              <Input placeholder="提交后自动生成" disabled />
            </Form.Item>
            {/* )} */}

            <Form.Item
              label="合同总价款："
              name="amount"
              initialValue={data?.amount}
              rules={[
                {
                  required: true,
                  message: '请输入合同总价款',
                },
              ]}
            >
              <InputNumber
                style={{ width: '100%' }}
                precision={2}
                addonAfter="万元"
                disabled={disableds.contract}
              />
            </Form.Item>

            <Form.Item
              name="project_code"
              initialValue={data?.project_code}
              label="项目编号："
            >
              <Input disabled />
            </Form.Item>
            <Form.Item
              name="party_b"
              label="乙方："
              initialValue={data?.party_b}
              rules={[
                {
                  required: true,
                  message: '请选择乙方',
                },
              ]}
            >
              <TreeSelect
                style={{ width: '100%' }}
                placeholder="请选择"
                showSearch
                allowClear
                disabled={disableds.contract}
                fieldNames={{
                  label: 'Name',
                  value: 'Name',
                  children: 'children',
                }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={supplyList}
              />
            </Form.Item>
            <Form.Item
              name="deal_by"
              label="经办人："
              initialValue={data?.deal_by}
              rules={[
                {
                  required: true,
                  message: '请选择经办人',
                },
              ]}
            >
              <Select
                style={{ width: '100%' }}
                placeholder="请选择"
                disabled={dealDisable || disableds.contract}
                options={userList?.map((item) => {
                  return {
                    value: item.CName,
                    label: item.CName,
                  };
                })}
              />
            </Form.Item>
          </Col>
        </Row>
        <Form.Item
          name="perform"
          initialValue={data?.perform}
          label="合同履行情况："
          labelCol={{ span: 4 }}
        >
          <Input.TextArea disabled={disableds.contract} />
        </Form.Item>
        <Form.Item label="合同上传：" labelCol={{ span: 4 }}>
          {type == Type.add ? (
            <Upload {...UploadProps}>
              <Button icon={<CloudUploadOutlined />}>Upload</Button>
            </Upload>
          ) : (
            <ul>
              {data?.attach &&
                JSON.parse(data?.attach)?.map((item, idx) => (
                  <li key={`${idx}_${item.name}`}>
                    <Space>
                      {item.name} <span>预览</span> <a href={item.url}>下载</a>
                    </Space>
                  </li>
                ))}
            </ul>
          )}
        </Form.Item>
        <Row>
          <Col span={10} offset={1}>
            <Form.Item
              name="created_name"
              initialValue={data?.created_name || user.CName}
              label="创建人："
            >
              <Input disabled />
            </Form.Item>
          </Col>
          <Col span={10}>
            <Form.Item
              name="created_on"
              initialValue={data?.created_on || dayjs().format(FORMAT)}
              label="创建时间："
            >
              <Input disabled />
            </Form.Item>
          </Col>
        </Row>
        {type == Type.check &&
          (data.status == Status.Checking ||
            data.status == Status.CalChecking) && (
            <>
              <ModuleTitle title="审核情况" />
              <Row>
                <Col span={10} offset={1}>
                  <Form.Item
                    name="check_by"
                    initialValue={user.CName}
                    label="审核人："
                  >
                    <Input disabled />
                  </Form.Item>
                  <Form.Item name="is_pass" initialValue={1} label="审核意见：">
                    <Select
                      onChange={(e) => {
                        setIsPass(e);
                      }}
                      style={{ width: '100%' }}
                      options={[
                        {
                          value: 1,
                          label: '同意',
                        },
                        {
                          value: 0,
                          label: '拒绝',
                        },
                      ]}
                    />
                  </Form.Item>
                </Col>
                <Col span={10}>
                  <Form.Item
                    name="check_date"
                    initialValue={dayjs().format(FORMAT)}
                    label="审核时间："
                  >
                    <Input disabled />
                  </Form.Item>
                </Col>
              </Row>
              {!isPass && (
                <Form.Item
                  name="check_desc"
                  label="拒绝原因："
                  labelCol={{ span: 4 }}
                >
                  <Input.TextArea />
                </Form.Item>
              )}
            </>
          )}
        {type != Type.add && (
          <>
            <ModuleTitle title="归档流程" />
            <div className={styles.modelItem}>
              <Steps
                current={data?.status == Status.Checking ? 1 : 2}
                status={
                  data?.status == Status.CheckReject ? 'error' : 'process'
                }
                items={[
                  {
                    title: '发起',
                    description: (
                      <>
                        <div className={styles.textNowarp}>
                          发起人：{data?.created_name}
                        </div>
                        <div className={styles.textNowarp}>
                          发起时间：{data?.created_on}
                        </div>
                      </>
                    ),
                  },
                  {
                    title: '审核',
                    description: (
                      <>
                        <div className={styles.textNowarp}>
                          审核人：{data?.check_by}
                        </div>
                        <div className={styles.textNowarp}>
                          审核时间：{data?.check_on}
                        </div>
                        {data?.check_desc && (
                          <div
                            className={styles.textNowarp}
                            style={{ color: 'red' }}
                          >
                            拒绝原因：{data?.check_desc}
                          </div>
                        )}
                      </>
                    ),
                  },
                  {
                    title:
                      data?.status >= Status.CheckSuccess
                        ? StatusText[Status.CheckSuccess]
                        : StatusText[data?.status],
                  },
                ]}
              />
            </div>
          </>
        )}
        {(type == Type.cancel || data?.status >= Status.CalChecking) && (
          <>
            <ModuleTitle title="作废信息" />
            <Form.Item
              name="cancel_desc"
              label="作废原因："
              initialValue={data?.cancel_desc}
              labelCol={{ span: 4 }}
            >
              <Input />
            </Form.Item>
          </>
        )}
        {type == Type.cancel && (
          <Form.Item
            name="cancel_on"
            label="创建时间："
            initialValue={dayjs().format(FORMAT)}
            labelCol={{ span: 4 }}
          >
            <Input
              style={{ width: '460px' }}
              defaultValue={dayjs().format('YYYY-MM-DD')}
              disabled
            />
            <span
              style={{ color: 'red', fontSize: '24px', marginLeft: '40px' }}
            >
              确认作废该合同，作废提交后无法撤回
            </span>
          </Form.Item>
        )}
        {type == Type.detail && data?.status >= Status.CalChecking && (
          <>
            <ModuleTitle title="作废流程" />
            <div className={styles.modelItem}>
              <Steps
                current={data?.status == Status.CalChecking ? 1 : 2}
                status={
                  data?.status == Status.CalCheckReject ? 'error' : 'process'
                }
                items={[
                  {
                    title: '发起',
                    description: (
                      <>
                        <div className={styles.textNowarp}>
                          发起人：{data?.created_name}
                        </div>
                        <div className={styles.textNowarp}>
                          发起时间：{data?.created_on}
                        </div>
                      </>
                    ),
                  },
                  {
                    title: '审核',
                    description: (
                      <>
                        <div className={styles.textNowarp}>
                          审核人：{data?.cancel_check_by}
                        </div>
                        <div className={styles.textNowarp}>
                          审核时间：{data?.cancel_check_on}
                        </div>
                      </>
                    ),
                  },
                  {
                    title: StatusText[data?.status],
                  },
                ]}
              />
            </div>
          </>
        )}
      </Form>
      <Divider />
    </Modal>
  );
};
export default ContractModal;
