import {
  MyBetaModalFormProps,
  MyButtons,
  MyFormItems,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import { HouseWorkOrdersTypeEnum } from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Form, message } from 'antd';

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

  return (
    <BetaSchemaForm
      {...MyModalFormProps.props}
      title={`添加${props.title}`}
      wrapperCol={{ span: 24 }}
      width="600px"
      trigger={<MyButtons.Create title={`添加${props.title}`} />}
      key={new Date().getTime()}
      form={form}
      onOpenChange={(open: any) => {
        if (open) {
          form.resetFields(); // 清空表单数据
        }
      }}
      onFinish={async (values: any) => {
        const { type, ...restValues } = values;
        const promises = (type || []).map((t: any) =>
          Apis.Asset.AssetProjectAdmins.Store({
            ...restValues,
            type: t,
            asset_projects_id: props?.item?.id,
          }),
        );

        return Promise.all(promises)
          .then(() => {
            props.reload?.();
            message.success(props.title + '成功');
            return true;
          })
          .catch(() => false);
      }}
      columns={[
        Selects?.Employees({
          title: '选择员工',
          dataIndex: 'company_employees_id',
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.text },
          fieldProps: {
            showSearch: true,
          },
          required: true,
        }),
        MyFormItems.EnumCheckbox({
          key: 'type',
          title: '工单类型',
          colProps: { span: 24 },
          valueEnum: HouseWorkOrdersTypeEnum,
          formItemProps: { ...rulesHelper.array },
          fieldProps: {
            // 每行显示3个选项
            options: Object.entries(HouseWorkOrdersTypeEnum).map(
              ([key, value]) => ({
                label: value.text,
                value: value.value,
              }),
            ),
            optionType: 'default',
            style: {
              display: 'grid',
              gridTemplateColumns: 'repeat(3, 1fr)',
              gap: '8px',
            },
          },
        }),
      ]}
    />
  );
}
