import {
  MyButtons,
  MyFormItems,
  MyModalFormProps,
  MyPageContainer,
  rulesHelper,
} from '@/common';

import { SelectContract } from '@/components/SelectContract';
import { Apis } from '@/gen/Apis';
import { BetaSchemaForm, ProCard } from '@ant-design/pro-components';
import { useNavigate, useSearchParams } from '@umijs/max';
import { Form, message, Space } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import MySubmitApproval from '../modals/SubmitApproval';
// import SubmitReview from '../modals/SubmitReview';
import {
  CompanySuppliersCounterpartyEnum,
  ContractPeoplesSignPartyEnum,
} from '@/gen/Enums';
import ContractsInfoAdd from '../show/components/ContractsInfoAdd';
import { IsDepositEnum } from './reducer';
export default function Index({ title = '新增补充协议' }) {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [contractId, setContractId] = useState<number>(0);

  const id = searchParams.get('id') ?? 0;
  const [data, setShow] = useState<any>({});
  const [selectedRow, setSelectedRow] = useState<any>({});
  const [submitModalVisible, setSubmitModalVisible] = useState<boolean>(false);

  const loadShow = () => {
    Apis.Contract.Contracts.Show({ id: Number(id) }).then((res) => {
      setShow(res?.data);
      setSelectedRow(res?.data?.resource);
      form.setFieldsValue({
        // ...res?.data,
        name: `${res?.data?.name}-补充协议` || '',
        total_amount: res?.data?.total_amount || 0,
        is_deposit: res?.data?.is_deposit ? 'yes' : 'no',
        peoples: res?.data?.contract_peoples,
        contract_time: [res?.data?.start_time, res?.data?.end_time],
        asset_projects_id: res?.data?.asset_projects_id,
      }); // 编辑赋值
    });
  };

  useEffect(() => {
    loadShow();
  }, [id]);

  // const onSave = (formData: any, subType: number) => {
  //   formData?.peoples?.forEach((res: any) => {
  //     res.company_suppliers_id = res?.counterparty?.split('：')?.[0];
  //   });
  //   console.log(formData, 'formData');
  //   Apis.Contract.Contracts.Store({
  //     ...formData,
  //     parent_id: data?.id ?? 0,
  //     is_deposit:
  //       IsDepositEnum[formData.is_deposit as keyof typeof IsDepositEnum].value,
  //     start_time: dayjs(formData?.contract_time?.[0]).format('YYYY-MM-DD'),
  //     end_time: dayjs(formData?.contract_time?.[1]).format('YYYY-MM-DD'),
  //     asset_projects_id: data?.asset_projects_id || 0,
  //     income_expense_type: data?.income_expense_type || 0,
  //     contract_nature: data?.contract_nature || 0,
  //     sign_subject: data?.sign_subject || '',
  //   })
  //     .then(() => {
  //       if (subType) {
  //         message.success('保存成功');
  //       } else {
  //         message.success('暂存成功');
  //       }
  //     })
  //     .catch(() => false);
  // };

  return (
    <MyPageContainer
      title={
        <Space
          style={{ cursor: 'pointer' }}
          onClick={() => {
            navigate(-1);
          }}
        >
          {/* <LeftCircleOutlined size={34} /> */}
          {title}
        </Space>
      }
      enableTabs={false}
      tabKey="charge-standards-create"
      tabLabel={title}
      footer={[
        <MyButtons.Default
          key="DirectSubmit"
          size="middle"
          type="primary"
          onClick={() => {
            // 先保存合同，然后显示提审弹窗
            const values = form.getFieldsValue();
            values?.peoples?.forEach((res: any) => {
              res.company_suppliers_id = res?.counterparty?.split('：')?.[0];
            });
            form?.validateFields().then(() => {
              Apis.Contract.Contracts.Store({
                ...values,
                parent_id: data?.id ?? 0,
                is_deposit: values.is_deposit
                  ? IsDepositEnum[
                      values.is_deposit as keyof typeof IsDepositEnum
                    ].value
                  : 'no',
                start_time: dayjs(values.contract_time?.[0]).format(
                  'YYYY-MM-DD',
                ),
                end_time: dayjs(values.contract_time?.[1]).format('YYYY-MM-DD'),
                asset_projects_id: data?.asset_projects_id || 0,
                income_expense_type: data?.income_expense_type || 0,
                contract_nature: data?.contract_nature || 0,
                sign_subject: data?.sign_subject || '',
                contract_liaison: data?.contract_liaison || '',
                seal_info: data?.seal_info || '',
                contract_types_id: data?.contract_types_id || 0,
              })
                .then((res) => {
                  const newContractId = res?.data?.id;
                  setContractId(newContractId);
                  setSubmitModalVisible(true);
                })
                .catch((error) => {
                  if (error !== '未获取到合同ID') {
                    message.error('操作失败，请重试');
                  }
                });
            });
          }}
          title="保存并提审"
        />,
      ]}
    >
      <ProCard>
        <div style={{ width: 900, margin: '0 auto' }}>
          <BetaSchemaForm<ApiTypes.Contract.Contracts.Update>
            {...MyModalFormProps.props}
            title={title}
            // 基础表单
            layoutType="Form"
            width="800px"
            layout="horizontal"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            labelAlign="left"
            form={form}
            submitter={{
              render: () => {
                return [];
              },
            }}
            columns={[
              {
                valueType: 'divider',
                fieldProps: {
                  orientation: 'left',
                  children: '新增补充协议',
                },
              },
              {
                key: 'name',
                title: '协议名称',
                colProps: { span: 24 },
                formItemProps: { ...rulesHelper.text },
              },
              {
                title: '补充协议份数',
                key: 'number_contract_copies',
                valueType: 'digit',
                colProps: { span: 24 },
                formItemProps: { ...rulesHelper.number },
                fieldProps: {
                  style: { width: '100%' },
                },
              },
              {
                valueType: 'divider',
                fieldProps: {
                  orientation: 'left',
                  children: (
                    <>
                      <span style={{ color: '#ff4d4f', marginLeft: 4 }}>*</span>
                      交易方信息
                    </>
                  ),
                },
              },
              {
                valueType: 'formList',
                dataIndex: 'peoples',
                title: '',
                fieldProps: {
                  copyIconProps: false,
                },
                formItemProps: {
                  ...rulesHelper.array,
                  wrapperCol: { span: 24 },
                },
                initialValue: [
                  {
                    sign_party: null,
                    counterparty_type: null,
                    counterparty: null,
                  },
                  {
                    sign_party: null,
                    counterparty_type: null,
                    counterparty: null,
                  },
                ],
                columns: [
                  {
                    valueType: 'group',
                    colProps: { span: 24 },
                    columns: [
                      MyFormItems.EnumSelect({
                        key: 'sign_party',
                        valueEnum: ContractPeoplesSignPartyEnum,
                        colProps: { span: 6 },
                        formItemProps: {
                          ...rulesHelper.text,
                          wrapperCol: { span: 24 },
                        },
                        fieldProps: {
                          placeholder: '请选择签约方',
                        },
                      }),
                      MyFormItems.EnumSelect({
                        key: 'counterparty_type',
                        title: '',
                        valueEnum: CompanySuppliersCounterpartyEnum,
                        colProps: { span: 6 },
                        formItemProps: {
                          ...rulesHelper.text,
                          wrapperCol: { span: 24 },
                        },
                      }),
                      {
                        valueType: 'dependency',
                        name: ['counterparty_type'],
                        columns: ({ counterparty_type }) => {
                          return counterparty_type === 'Supplier'
                            ? [
                                SelectContract.SupplierName({
                                  key: 'counterparty',
                                  title: '',
                                  params: {
                                    counterparty: 'Supplier',
                                  },
                                  colProps: { span: 12 },
                                  formItemProps: {
                                    ...rulesHelper.text,
                                    wrapperCol: { span: 24 },
                                  },
                                  required: true,
                                  fieldProps: {
                                    placeholder: '请选择签约主体',
                                  },
                                }),
                              ]
                            : counterparty_type === 'InternalCompany'
                            ? [
                                SelectContract.SupplierName({
                                  key: 'counterparty',
                                  title: '',
                                  params: {
                                    counterparty: 'InternalCompany',
                                  },
                                  colProps: { span: 12 },
                                  formItemProps: {
                                    ...rulesHelper.text,
                                    wrapperCol: { span: 24 },
                                  },
                                  required: true,
                                  fieldProps: {
                                    placeholder: '请选择签约主体',
                                  },
                                }),
                              ]
                            : [
                                SelectContract.SupplierName({
                                  key: 'counterparty',
                                  title: '',
                                  params: {
                                    counterparty: 'InternalCompany',
                                  },
                                  colProps: { span: 12 },
                                  formItemProps: {
                                    ...rulesHelper.text,
                                    wrapperCol: { span: 24 },
                                  },
                                  required: true,
                                  fieldProps: {
                                    placeholder: '请选择签约主体',
                                    disabled: true,
                                  },
                                }),
                              ];
                        },
                      },
                    ],
                  },
                ],
              },
              MyFormItems.UploadImages({
                key: 'attachments',
                title: '上传附件',
                tooltip: '支持上传任意格式的文件',
                uploadType: 'file',
                colProps: { span: 24 },
                // accept: '.docx,.doc,.pdf',
                max: 100,
                required: true,
              }),

              SelectContract.ContractSeals({
                key: 'seal_info',
                required: true,
                title: '选择印章',
                colProps: { span: 24 },
                fieldProps: {
                  showSearch: true,
                  mode: 'multiple',
                },
              }),
              {
                valueType: 'divider',
                fieldProps: {
                  orientation: 'left',
                  children: '是否变更原合同信息',
                },
              },
              {
                key: 'contract_time',
                title: '原合同合同有效期',
                valueType: 'dateRange',
                colProps: { span: 24 },
                fieldProps: {
                  style: { width: '50%' },
                  format: 'YYYY-MM-DD',
                },
                formItemProps: { ...rulesHelper.text },
                transform: (value: any) => {
                  return {
                    start_time: value?.[0],
                    end_time: value?.[1],
                  };
                },
              },
              {
                title: '原合同总金额',
                key: 'total_amount',
                valueType: 'digit',
                colProps: { span: 24 },
                formItemProps: {
                  ...rulesHelper.number,
                  labelCol: { span: 4 },
                  wrapperCol: { span: 20 },
                },
                fieldProps: {
                  style: { width: '100%' },
                  addonAfter: '元',
                },
              },
              MyFormItems.EnumRadio({
                key: 'is_deposit',
                title: '是否有保证金',
                valueEnum: IsDepositEnum,
                colProps: { span: 12 },
                formItemProps: {
                  ...rulesHelper.text,
                  labelCol: { span: 8 },
                  wrapperCol: { span: 16 },
                },
              }),
              {
                valueType: 'dependency',
                name: ['is_deposit'],
                columns: ({ is_deposit }) => {
                  return is_deposit === 'yes'
                    ? [
                        {
                          title: '请输入保证金',
                          key: 'deposit_amount',
                          valueType: 'digit',
                          colProps: { span: 12 },
                          formItemProps: {
                            ...rulesHelper.number,
                            labelCol: { span: 12 },
                            wrapperCol: { span: 12 },
                          },
                          fieldProps: {
                            style: { width: '100%' },
                            suffix: '元',
                          },
                        },
                      ]
                    : [];
                },
              },
            ]}
          />
        </div>
        <div style={{ width: 900, margin: '0 auto' }}>
          <ContractsInfoAdd item={data} />
        </div>
        <MySubmitApproval
          open={submitModalVisible}
          item={{ type: 'Contract', contracts_id: contractId }}
          onCancel={() => {
            setSubmitModalVisible(false);
          }}
          reload={() => {
            setSubmitModalVisible(false);
            navigate('/contract/contracts');
          }}
        />
      </ProCard>
    </MyPageContainer>
  );
}
