import {
  MyBetaModalFormProps,
  MyButtons,
  MyFormItems,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import {
  ApprovalTemplateNodesNodeTypeEnum,
  ApprovalTemplatesTypeEnum,
  HouseBillsBillStatusEnum,
  HouseBillsTypeEnum,
} from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Button, Form, message } from 'antd';
import { useState } from 'react';

export default function Update(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();
  const [ApprovalTemplates, setApprovalTemplates] = useState<any>([]);

  return (
    <BetaSchemaForm<ApiTypes.Bill.HouseBills.Update>
      {...MyModalFormProps.props}
      title={`${props.title}编辑`}
      trigger={
        <MyButtons.Default
          title="编辑"
          type="primary"
          size="small"
          disabled={
            props?.item?.bill_status === HouseBillsBillStatusEnum.Paid.value ||
            props?.item?.bill_status ===
              HouseBillsBillStatusEnum.Cancelled.value
          }
        />
      }
      wrapperCol={{ span: 24 }}
      width="800px"
      key={props.item?.id}
      form={form}
      onOpenChange={(open: any) => {
        if (open && props.item) {
          const formValues = {
            ...props.item,
            month:
              props.item.year && props.item.month
                ? `${props.item.year}-${String(props.item.month).padStart(
                    2,
                    '0',
                  )}`
                : props.item.month,
          };
          form.setFieldsValue(formValues);
        }
      }}
      onFinish={async (values: any) => {
        const { node_approvers } = values;

        if (ApprovalTemplates?.length > 0 && node_approvers?.length > 0) {
          // 遍历模板节点，通过名称找到对应的提交节点进行校验
          for (const templateNode of ApprovalTemplates) {
            // 通过名称找到对应的提交节点
            const submittedNode = node_approvers.find(
              (node: any) => node?.name === templateNode?.name,
            );

            // 如果模板节点在提交数据中不存在，说明被删除了，报错
            if (!submittedNode) {
              message.error(`节点"${templateNode?.name}"不能删除`);
              return false;
            }

            // 校验审批人
            if (
              templateNode?.node_type ===
              ApprovalTemplateNodesNodeTypeEnum.Approver.value
            ) {
              const originalMembers =
                templateNode?.approval_template_node_members?.map(
                  (member: any) => member?.company_employees_id,
                );

              if (originalMembers?.length > 0) {
                const submittedMembers = submittedNode?.members || [];

                const isMatch =
                  originalMembers.length === submittedMembers.length &&
                  originalMembers.every((memberId: number) =>
                    submittedMembers.includes(memberId),
                  );

                if (!isMatch) {
                  message.error(
                    `节点"${templateNode?.name}"的审批人必须与审批模板设置保持一致`,
                  );
                  return false;
                }
              }
            }
          }
        }

        return Apis.Bill.HouseBills.Update({
          ...values,
          id: props.item?.id ?? 0,
        })
          .then(() => {
            props.reload?.();
            message.success(props.title + '成功');
            return true;
          })
          .catch(() => false);
      }}
      columns={[
        MyFormItems.EnumRadio({
          key: 'type',
          title: '类型',
          colProps: { span: 24 },
          valueEnum: HouseBillsTypeEnum,
          required: true,
        }),
        {
          key: 'amount',
          title: '金额',
          valueType: 'digit',
          colProps: { span: 8 },
          fieldProps: {
            style: {
              width: '100%',
            },
          },
          formItemProps: { ...rulesHelper.number },
        },
        {
          key: 'discount_amount',
          title: '优惠金额',
          valueType: 'digit',
          fieldProps: {
            style: {
              width: '100%',
            },
          },
          colProps: { span: 8 },
        },

        {
          key: 'late_fee',
          title: '滞纳金',
          valueType: 'digit',
          fieldProps: {
            style: {
              width: '100%',
            },
          },
          colProps: { span: 8 },
        },
        {
          key: 'month',
          title: '账单月份',
          valueType: 'date',
          colProps: { span: 8 },
          fieldProps: {
            picker: 'month',
            format: 'YYYY-MM',
            valueFormat: 'YYYY-MM',
            style: {
              width: '100%',
            },
            onChange: (e: any, dateString: string) => {
              form.setFieldsValue({
                start_date: rulesHelper.getMonthStartDate(dateString),
                end_date: rulesHelper.getMonthEndDate(dateString),
              });
            },
          },
          formItemProps: { ...rulesHelper.text },
        },
        {
          key: 'start_date',
          title: '计费开始日期',
          valueType: 'date',
          colProps: { span: 8 },
          fieldProps: {
            style: {
              width: '100%',
            },
          },
          formItemProps: { ...rulesHelper.text },
        },
        {
          key: 'end_date',
          title: '计费结束日期',
          valueType: 'date',
          colProps: { span: 8 },
          fieldProps: {
            style: {
              width: '100%',
            },
          },
          formItemProps: { ...rulesHelper.text },
        },

        {
          valueType: 'dependency',
          name: ['asset_projects_id'],
          columns: ({ asset_projects_id }) => {
            return [
              {
                valueType: 'group',
                columns: [
                  Selects?.ProjectAccounts({
                    key: 'company_receipt_accounts_id',
                    title: '选择收款账户',
                    params: {
                      projects_id: asset_projects_id,
                    },
                    colProps: { span: 24 },
                    formItemProps: { ...rulesHelper.number },
                    fieldProps: {
                      showSearch: true,
                    },
                  }),
                ],
              },
            ];
          },
        },
        {
          title: '备注',
          key: 'remark',
          valueType: 'textarea',
          colProps: { span: 24 },
        },
        Selects?.ApprovalTemplates({
          key: 'approval_templates_id',
          title: '审批模版',
          params: {
            type: ApprovalTemplatesTypeEnum.HouseBillUpdate.value,
            is_enabled: '1',
          },
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.number },
          fieldProps: {
            onChange: (e: any) => {
              if (e) {
                const templateId = typeof e === 'object' ? e.value : e;
                Apis.Approval.ApprovalTemplates.Show({
                  id: templateId,
                }).then((res) => {
                  setApprovalTemplates(res?.data?.approval_template_nodes);
                  form.setFieldsValue({
                    approval_templates_id: templateId,
                    node_approvers: res?.data?.approval_template_nodes?.map(
                      (item: any) => ({
                        ...item,
                        members: item?.approval_template_node_members?.map(
                          (member: any) => member?.company_employees_id,
                        ),
                      }),
                    ),
                  });
                });
              }
            },
          },
        }),
        {
          valueType: 'dependency',
          name: ['approval_templates_id'],
          columns: ({ approval_templates_id }) => {
            return approval_templates_id
              ? [
                  {
                    valueType: 'formList',
                    dataIndex: 'node_approvers',
                    fieldProps: {
                      creatorButtonProps: false,
                      actionRender: (field: any, action: any) => [
                        <Button
                          key="add"
                          type="link"
                          size="small"
                          onClick={() => {
                            const currentNodeType = form.getFieldValue([
                              'node_approvers',
                              field.name,
                              'node_type',
                            ]);
                            if (
                              currentNodeType ===
                              ApprovalTemplateNodesNodeTypeEnum.CC.value
                            ) {
                              message.warning('抄送节点不允许添加');
                              return;
                            }
                            action.add(
                              {
                                node_type:
                                  ApprovalTemplateNodesNodeTypeEnum.Approver
                                    .value,
                              },
                              field.name + 1,
                            );
                          }}
                        >
                          添加
                        </Button>,
                        <Button
                          key="delete"
                          type="link"
                          size="small"
                          danger
                          onClick={() => {
                            action.remove(field.name);
                          }}
                        >
                          删除
                        </Button>,
                      ],
                    },
                    formItemProps: {
                      ...rulesHelper.array,
                      wrapperCol: { span: 24 },
                    },
                    columns: [
                      {
                        valueType: 'group',
                        colProps: { span: 24 },
                        columns: [
                          MyFormItems.EnumSelect({
                            key: 'node_type',
                            valueEnum: ApprovalTemplateNodesNodeTypeEnum,
                            colProps: { span: 5 },
                            formItemProps: {
                              ...rulesHelper.text,
                            },
                          }),
                          {
                            key: 'name',
                            colProps: { span: 6 },
                            formItemProps: {
                              ...rulesHelper.text,
                            },
                          },
                          {
                            valueType: 'dependency',
                            name: ['node_type'],
                            columns: ({ node_type }) => {
                              return [
                                Selects.Employees({
                                  key: 'members',
                                  title: ``,
                                  colProps: { span: 13 },
                                  formItemProps: {
                                    ...rulesHelper.array,
                                  },
                                  fieldProps: {
                                    mode: 'multiple',
                                    showSearch: true,
                                    maxCount:
                                      node_type ===
                                      ApprovalTemplateNodesNodeTypeEnum.Approver
                                        .value
                                        ? 1
                                        : 9,
                                    maxTagTextLength: 20,
                                    labelRender: (res: any) => {
                                      if (res?.label) {
                                        return res?.label;
                                      } else {
                                        return ApprovalTemplates?.map(
                                          (item: any) => {
                                            if (
                                              item?.node_type === node_type &&
                                              item
                                                ?.approval_template_node_members
                                                ?.length
                                            ) {
                                              return item?.approval_template_node_members?.map(
                                                (i: any) => {
                                                  if (
                                                    i?.company_employees_id ===
                                                    res?.value
                                                  ) {
                                                    return (
                                                      i?.company_employee
                                                        ?.name || ''
                                                    );
                                                  }
                                                },
                                              );
                                            }
                                          },
                                        );
                                      }
                                    },
                                  },
                                }),
                              ];
                            },
                          },
                        ],
                      },
                    ],
                  },
                ]
              : [];
          },
        },
      ]}
    />
  );
}
