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

export default function Create(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();
  // const [ApprovalTemplates, setApprovalTemplates] = useState<any>([]);
  let approval_templates_id_store = 0;
  let ApprovalTemplates: any = [];
  return (
    <BetaSchemaForm<ApiTypes.Contract.ContractArchiveBorrows.Store>
      {...MyModalFormProps.props}
      title={`添加${props.title}`}
      wrapperCol={{ span: 24 }}
      width="800px"
      key={new Date().getTime()}
      form={form}
      onOpenChange={(open: any) => {
        if (open) {
          form.resetFields(); // 清空表单数据
        }
      }}
      trigger={<MyButtons.Create title={`${props.title}`} />}
      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.Contract.ContractArchiveBorrows.Store({
          ...values,
          contract_archives_id: values?.contract_archives?.id ?? 0,
          is_need_return: values?.is_need_return || false,
          files: values?.files?.map((item: any) => ({
            contract_archive_files_id: item.id,
            borrow_number: item?.borrow_number,
          })),
        })
          .then(() => {
            props.reload?.();
            message.success('借用成功！');
            return true;
          })
          .catch(() => false);
      }}
      columns={[
        Selects?.Employees({
          title: '借用人',
          dataIndex: 'borrower_id',
          key: 'borrower_id',
          colProps: { span: 8 },
          formItemProps: { ...rulesHelper.text },
          fieldProps: {
            showSearch: true,
          },
          required: true,
        }),
        {
          key: 'borrow_date',
          title: '借用日期',
          dataIndex: 'borrow_date',
          valueType: 'date',
          formItemProps: { ...rulesHelper.text },
          fieldProps: {
            style: {
              width: '100%',
            },
          },
          colProps: { span: 8 },
        },

        {
          key: 'is_need_return',
          title: '是否需要归还',
          colProps: { span: 8 },
          valueType: 'switch',
          // initialValue: true,
          width: '100%',
          fieldProps: {
            onChange: () => {
              form.setFieldValue('expected_return_date', undefined);
            },
          },
        },
        {
          name: ['is_need_return'],
          valueType: 'dependency',
          columns: ({ is_need_return }: any) => {
            return is_need_return
              ? [
                  {
                    key: 'expected_return_date',
                    title: '设置归还日期',
                    dataIndex: 'expected_return_date',
                    formItemProps: { ...rulesHelper.text },
                    valueType: 'date',
                    fieldProps: {
                      style: {
                        width: '100%',
                      },
                    },
                    colProps: { span: 8 },
                  },
                ]
              : [];
          },
        },

        {
          key: 'borrow_reason',
          title: '借用原因',
          dataIndex: 'borrow_reason',
          // valueType: 'textarea',
          colProps: { span: 16 },
        },
        {
          valueType: 'divider',
          fieldProps: {
            orientation: 'left',
            children: '借用文件',
          },
        },
        {
          colProps: { span: 24 },
          title: '选择归档合同',
          key: 'contract_archives',
          formItemProps: { ...rulesHelper.text },
          renderFormItem: (_, row: any) => {
            return (
              <Space>
                <MyModalsContractsArchivedSelectList
                  onChange={(e: any) => {
                    if (e && e.length > 0) {
                      let res = e[0];
                      form.setFieldsValue({
                        files: res?.contract_archive_files,
                        contract_archives: {
                          id: res?.id,
                          code: res?.code,
                        },
                      });
                    }
                    console.log(e, 'e');
                  }}
                />
                {row?.value?.code && (
                  <span>已选择归档编号: {row?.value?.code}</span>
                )}
              </Space>
            );
          },
        },

        {
          valueType: 'formList',
          dataIndex: 'files',
          title: '',
          formItemProps: {
            ...rulesHelper.array,
            labelCol: { span: 0 },
            wrapperCol: { span: 24 },
          },
          colProps: { span: 24 },
          fieldProps: {
            copyIconProps: false,
            // deleteIconProps: false,
            creatorButtonProps: false,
            itemRender: ({ listDom, action }: any, { index }: any) => {
              return (
                <ProCard
                  bordered
                  extra={action}
                  title={`借用文件${index + 1}`}
                  style={{
                    marginBlockEnd: 8,
                  }}
                >
                  {listDom}
                </ProCard>
              );
            },
          },

          columns: [
            {
              valueType: 'group',
              colProps: { span: 24 },
              columns: [
                {
                  title: '文件ID',
                  key: 'id',
                  colProps: { span: 4 },
                  fieldProps: {
                    disabled: true,
                  },
                },
                {
                  title: '名称',
                  key: 'name',
                  colProps: { span: 8 },
                  fieldProps: {
                    disabled: true,
                  },
                },
                {
                  title: '文件份数',
                  key: 'number',
                  valueType: 'digit',
                  colProps: { span: 4 },
                  fieldProps: {
                    disabled: true,
                    style: {
                      width: '100%',
                    },
                  },
                },
                {
                  title: '已借份数',
                  key: 'borrowed_number',
                  valueType: 'digit',
                  colProps: { span: 4 },
                  fieldProps: {
                    disabled: true,
                    style: {
                      width: '100%',
                    },
                  },
                },
                {
                  name: ['number', 'borrowed_number'],
                  valueType: 'dependency',
                  columns: ({ number, borrowed_number }: any) => {
                    return [
                      {
                        title: '借用份数',
                        key: 'borrow_number',
                        valueType: 'digit',
                        colProps: { span: 4 },
                        fieldProps: {
                          max: number - borrowed_number,
                          min: 1,
                          style: {
                            width: '100%',
                          },
                        },
                        formItemProps: { ...rulesHelper.number },
                      },
                    ];
                  },
                },
              ],
            },
          ],
        },
        Selects?.ApprovalTemplates({
          key: 'approval_templates_id',
          title: '审批模版',
          // 选择审批模版
          params: {
            type: ApprovalTemplatesTypeEnum.ContractBorrow.value,
            is_enabled: '1',
          },
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.number },
        }),
        {
          valueType: 'dependency',
          name: ['approval_templates_id'],
          columns: ({ approval_templates_id }) => {
            if (approval_templates_id) {
              if (approval_templates_id_store !== approval_templates_id) {
                approval_templates_id_store = approval_templates_id;
                Apis.Approval.ApprovalTemplates.Show({
                  id: approval_templates_id,
                }).then((res) => {
                  // setApprovalTemplates(res?.data?.approval_template_nodes);
                  ApprovalTemplates = res?.data?.approval_template_nodes;
                  form.setFieldsValue({
                    node_approvers: res?.data?.approval_template_nodes?.map(
                      (item: any) => ({
                        ...item,
                        members: item?.approval_template_node_members?.map(
                          (member: any) => member?.company_employees_id,
                        ),
                      }),
                    ),
                  });
                });
              }
            }
            return [
              {
                valueType: 'formList',
                dataIndex: 'node_approvers',
                // title: '审批节点',
                fieldProps: {
                  copyIconProps: false,
                  deleteIconProps: false,
                  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,
                            name: '审批人',
                          },
                          field.name + 1,
                        );
                      }}
                    >
                      添加
                    </Button>,
                    <Button
                      key="delete"
                      type="link"
                      size="small"
                      danger
                      disabled={!field.name}
                      onClick={() => {
                        action.remove(field.name);
                      }}
                    >
                      删除
                    </Button>,
                  ],
                },
                formItemProps: {
                  ...rulesHelper.array,
                  wrapperCol: { span: 24 },
                },
                columns: [
                  {
                    valueType: 'group',
                    colProps: { span: 24 },
                    columns: [
                      MyFormItems.EnumSelect({
                        key: 'node_type',
                        // title: `类型`,
                        valueEnum: ApprovalTemplateNodesNodeTypeEnum,
                        colProps: { span: 5 },
                        formItemProps: {
                          ...rulesHelper.text,
                        },
                      }),
                      {
                        // title: '节点名称',
                        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: 3,
                                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 ||
                                                  ''
                                                );
                                              }
                                            },
                                          );
                                        }
                                      },
                                    );
                                  }
                                },
                              },
                            }),
                          ];
                        },
                      },
                    ],
                  },
                ],
              },
            ];
          },
        },

        // {
        //   valueType: 'dependency',
        //   name: ['approval_templates_id'],
        //   columns: ({ approval_templates_id }) => {
        //     return approval_templates_id
        //       ? [
        //           {
        //             valueType: 'formList',
        //             dataIndex: 'node_approvers',
        //             // title: '审批节点',
        //             fieldProps: {
        //               copyIconProps: false,
        //               deleteIconProps: false,
        //               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',
        //                     // title: `类型`,
        //                     valueEnum: ApprovalTemplateNodesNodeTypeEnum,
        //                     colProps: { span: 5 },
        //                     formItemProps: {
        //                       ...rulesHelper.text,
        //                     },
        //                     fieldProps: {
        //                       disabled: true,
        //                     },
        //                   }),
        //                   {
        //                     // title: '节点名称',
        //                     key: 'name',
        //                     colProps: { span: 6 },
        //                     formItemProps: {
        //                       ...rulesHelper.text,
        //                     },
        //                     fieldProps: {
        //                       disabled: true,
        //                     },
        //                   },
        //                   {
        //                     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: 3,
        //                             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 || ''
        //                                             );
        //                                           }
        //                                         },
        //                                       );
        //                                     }
        //                                   },
        //                                 );
        //                               }
        //                             },
        //                           },
        //                         }),
        //                       ];
        //                     },
        //                   },
        //                 ],
        //               },
        //             ],
        //           },
        //         ]
        //       : [];
        //   },
        // },
      ]}
    />
  );
}
