import {
  MyBetaModalFormProps,
  MyButtons,
  MyFormItems,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import {
  ApprovalTemplateNodesNodeTypeEnum,
  ApprovalTemplatesTypeEnum,
} from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Button, Form, message } from 'antd';
let showInfo: any = [];
export default function Update(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();
  return (
    <BetaSchemaForm<ApiTypes.Approval.ApprovalTemplates.Update>
      {...MyModalFormProps.props}
      title={`编辑${props.title}`}
      trigger={<MyButtons.Edit />}
      key={new Date().getTime()}
      wrapperCol={{ span: 24 }}
      width="700px"
      form={form}
      onOpenChange={(open: any) => {
        if (open && props.item) {
          Apis.Approval.ApprovalTemplates.Show({
            id: props.item?.id ?? 0,
          }).then((res: any) => {
            showInfo = res?.data?.approval_template_nodes;
            form.setFieldsValue({
              ...res?.data,
              nodes: res?.data?.approval_template_nodes?.map((item: any) => ({
                ...item,
                members: item?.approval_template_node_members?.map(
                  (member: any) => member?.company_employees_id,
                ),
              })),
            });
          });
        }
      }}
      onFinish={async (values) => {
        const { nodes } = values;

        // 校验：只能提交一行 node_type 为 "cc" 的数据
        const ccNodes = nodes?.filter(
          (node: any) =>
            node?.node_type === ApprovalTemplateNodesNodeTypeEnum.CC.value,
        );
        if (ccNodes?.length > 1) {
          message.error('只能提交一行抄送节点');
          return false;
        }

        // 过滤掉 node_type 为 "cc" 且 members 为空的行
        const filteredNodes = nodes?.filter((node: any) => {
          if (node?.node_type === ApprovalTemplateNodesNodeTypeEnum.CC.value) {
            return node?.members?.length > 0;
          }
          return true;
        });

        const nodeNames = filteredNodes?.map((node: any) => node?.name);
        const hasDuplicate = nodeNames?.length !== new Set(nodeNames).size;
        if (hasDuplicate) {
          message.error('节点名称不能重复');
          return false;
        }

        return Apis.Approval.ApprovalTemplates.Update({
          ...values,
          nodes: filteredNodes,
          id: props.item?.id ?? 0,
        })
          .then(() => {
            props.reload?.();
            message.success(props.title + '编辑成功');
            return true;
          })
          .catch(() => false);
      }}
      columns={[
        MyFormItems.EnumSelect({
          key: 'type',
          title: '业务类型',
          // valueEnum: ApprovalTemplatesTypeEnum,
          valueEnum: () => {
            const obj: Record<string, any> = JSON.parse(
              JSON.stringify(ApprovalTemplatesTypeEnum),
            );
            delete obj.Finance;
            delete obj.BillModification;
            return obj;
          },
          required: true,
          colProps: { span: 8 },
        }),
        {
          key: 'name',
          title: '名称',
          formItemProps: { ...rulesHelper.text },
          colProps: { span: 8 },
        },
        {
          key: 'code',
          title: '模板编码',
          formItemProps: { ...rulesHelper.text },
          colProps: { span: 8 },
        },

        {
          valueType: 'formList',
          dataIndex: 'nodes',
          title: '审批节点',
          fieldProps: {
            copyIconProps: false,
            creatorButtonProps: {
              creatorButtonText: '添加节点',
            },
            actionRender: (field: any, action: any) => [
              <Button
                key="add"
                type="link"
                size="small"
                onClick={() => {
                  const currentNodeType = form.getFieldValue([
                    'nodes',
                    field.name,
                    'node_type',
                  ]);
                  if (
                    currentNodeType ===
                    ApprovalTemplateNodesNodeTypeEnum.CC.value
                  ) {
                    message.warning('抄送节点不允许添加');
                    return;
                  }
                  action.add(
                    {
                      node_type:
                        ApprovalTemplateNodesNodeTypeEnum.Approver.value,
                      name: '',
                      members: [],
                    },
                    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,
                  },
                }),
                {
                  title: '节点名称',
                  key: 'name',
                  colProps: { span: 6 },
                  formItemProps: {
                    ...rulesHelper.text,
                  },
                },
                {
                  valueType: 'dependency',
                  name: ['node_type', 'name'],
                  columns: ({ node_type, name }) => {
                    return [
                      Selects.Employees({
                        key: 'members',
                        title: `审批人员`,
                        colProps: { span: 13 },
                        fieldProps: {
                          mode: 'multiple',
                          maxCount:
                            node_type ===
                            ApprovalTemplateNodesNodeTypeEnum.Approver.value
                              ? 1
                              : 9,
                          maxTagTextLength: 3,
                          labelRender: (res: any) => {
                            console.log(res, showInfo, name, '222');
                            if (res?.label) {
                              return res?.label;
                            } else {
                              return showInfo?.map((i: any) => {
                                if (i?.name === name) {
                                  return i?.approval_template_node_members?.map(
                                    (k: any) => {
                                      if (
                                        k?.company_employees_id === res?.value
                                      ) {
                                        return k?.company_employee?.name || '-';
                                      }
                                    },
                                  );
                                }
                              });
                            }
                          },
                        },
                      }),
                    ];
                  },
                },
              ],
            },
          ],
        },
        {
          title: '备注',
          key: 'description',
          colProps: { span: 24 },
          // valueType: 'textarea',
        },
      ]}
    />
  );
}
