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

import { Apis } from '@/gen/Apis';
import { HouseRegistersStatusEnum } from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import { Form, message, Space } from 'antd';
import ApprovalRecord from '../../common_info/ApprovalRecord';
import ArchiveBorrowInfo from '../../common_info/ArchiveBorrowInfo';
import BillUpdateInfo from '../../common_info/BillUpdateInfo';
import ChargeStandardInfo from '../../common_info/ChargeStandardInfo';
import ContractInfo from '../../common_info/ContractInfo';
import ContractPaymentInfo from '../../common_info/ContractPaymentInfo';
import ContractTerminationInfo from '../../common_info/ContractTerminationInfo';
import RefundInfo from '../../common_info/RefundInfo';
import SealInfo from '../../common_info/SealInfo';
import TemporaryBillUpdateInfo from '../../common_info/TemporaryBillUpdateInfo';

export default function Update(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();
  const navigate = useNavigate();

  // 监听status字段变化，动态设置默认审批意见
  const handleStatusChange = (changedValues: any) => {
    if (changedValues.status) {
      if (changedValues.status === HouseRegistersStatusEnum.Approved.value) {
        form.setFieldsValue({ opinion: '同意' });
      } else if (
        changedValues.status === HouseRegistersStatusEnum.Rejected.value
      ) {
        form.setFieldsValue({ opinion: '不同意' });
      }
    }
  };

  return (
    <BetaSchemaForm<ApiTypes.Archive.HouseRegisters.Update>
      {...MyModalFormProps.props}
      title={props.title}
      trigger={<MyButtons.Default title="审核" type="primary" />}
      wrapperCol={{ span: 24 }}
      width="600px"
      key={new Date().getTime()}
      form={form}
      onOpenChange={() => {
        if (props?.item?.id) {
          Apis.Approval.ApprovalInstances.Show({
            id: props.item?.approval_instances_id,
          }).then((res) => {
            form.setFieldsValue({
              info_display: res?.data,
            });
          });
        }
      }}
      initialValues={{
        // 默认选择通过，审批意见为同意
        status: HouseRegistersStatusEnum.Approved.value,
        opinion: '同意',
      }}
      onValuesChange={handleStatusChange}
      onFinish={async (values: any) =>
        Apis.Approval.ApprovalInstances.Approve({
          record_id: props.item?.id ?? 0,
          ...values,
        })
          .then(() => {
            props.reload?.();
            message.success('审核成功！');
            return true;
          })
          .catch(() => false)
      }
      columns={[
        {
          // title: '登记信息',
          dataIndex: 'info_display',
          valueType: 'text',
          renderFormItem: (_, config) => (
            <Space direction="vertical" style={{ width: '100%' }}>
              {config?.value?.type === 'Contract' && (
                <ContractInfo item={config?.value} />
              )}
              {config?.value?.type === 'ContractTermination' && (
                <ContractTerminationInfo item={config?.value} />
              )}
              {config?.value?.type === 'ContractPayment' && (
                <ContractPaymentInfo item={config?.value} />
              )}
              {config?.value?.type === 'Refund' && (
                <RefundInfo item={config?.value} />
              )}
              {config?.value?.type === 'ContractBorrow' && (
                <ArchiveBorrowInfo item={config?.value} />
              )}
              {config?.value?.type === 'OtherContractSeal' && (
                <SealInfo item={config?.value} />
              )}
              {config?.value?.type === 'HouseBillUpdate' && (
                <BillUpdateInfo item={config?.value} />
              )}
              {config?.value?.type === 'ChargeStandardModification' && (
                <ChargeStandardInfo item={config?.value} />
              )}
              {config?.value?.type === 'BillUpdate' && (
                <TemporaryBillUpdateInfo item={config?.value} />
              )}
              <ApprovalRecord item={config?.value} />
            </Space>
          ),
          colProps: { span: 24 },
        },
        {
          valueType: 'group',
          // title: '审核操作',
          columns: [
            MyFormItems.EnumRadio({
              key: 'status',
              title: '审核操作',
              colProps: { span: 24 },
              valueEnum: () => {
                let obj: any = JSON.parse(
                  JSON.stringify(HouseRegistersStatusEnum),
                );
                delete obj.Pending;
                return obj;
              },
              required: true,
            }),
            {
              valueType: 'dependency',
              name: ['status'],
              columns: ({ status }) => {
                return status === 'Rejected'
                  ? [
                      {
                        title: '审批意见',
                        dataIndex: 'opinion',
                        valueType: 'textarea',
                        formItemProps: { ...rulesHelper.text },
                        colProps: { span: 24 },
                      },
                    ]
                  : [
                      {
                        title: '审批意见',
                        dataIndex: 'opinion',
                        valueType: 'textarea',
                        formItemProps: { ...rulesHelper.text },
                        colProps: { span: 24 },
                      },
                    ];
              },
            },
          ],
        },
      ]}
    />
  );
}
