import React, { useRef, useState } from 'react';
import type { ProFormInstance } from '@ant-design/pro-form';
import {
  DrawerForm,
  ProFormCheckbox,
  ProFormDigit,
  ProFormGroup,
  ProFormSwitch,
  ProFormText,
} from '@ant-design/pro-form';
import ProForm from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import serviceClient from '@/services/kanban/settings/index';

export type EditFormProps = {
  values: Partial<KANBAN.Settings.ProductProgressKanbanSettingDto>;
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  onSubmitting: () => Promise<any>;
  onSuccess: (params: any) => Promise<void>;
  onError: (params: any, error: unknown) => Promise<void>;
};

const EditForm: React.FC<EditFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() => []);
  const [dataSource, setDataSource] = useState<KANBAN.Settings.ProgressStepDto[]>(() => []);

  const editColumns: ProColumns<KANBAN.Settings.ProgressStepDto>[] = [
    {
      title: '编码',
      dataIndex: 'code',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '序号',
      dataIndex: 'ordinal',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueType: 'select',
      hideInSearch: true,
      request: async () => {
        const result = [
          { label: 'MES工序', value: 1 },
          { label: 'MES入库', value: 2 },
          { label: '手工导入', value: 3 },
        ];
        return result;
      },
    },
    {
      title: 'MES工序',
      dataIndex: 'extraTypeDes',
      valueType: 'text',
      formItemProps: () => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
    },
  ];
  return (
    <DrawerForm
      formRef={formRef}
      title="修改产品进度看板配置"
      width="900px"
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          formRef?.current?.resetFields();
          formRef?.current?.setFieldsValue({ ...props.values });
          props.values.progressStepList?.forEach((s) => {
            s.type = s.typeId;
            s.rowKey = s.id;
          });
          //setDataSource([]);
          setDataSource(props.values.progressStepList || []);
          setEditableRowKeys(() => props.values.progressStepList?.map((item) => item.rowKey) || []);
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async () => {
        const formData = formRef?.current?.getFieldsValue();
        const params = await props.onSubmitting();
        try {
          dataSource.forEach((s) => {
            s.progress = props.values.progressId;
          });
          const updateDto: KANBAN.Settings.ProductProgressKanbanSettingUpdate = {
            id: props.values.id || '',
            subTitle1: formData.subTitle1,
            subTitle2: formData.subTitle2,
            sgNoSourceType: formData.sgNoSourceType,
            progressUpdate: {
              id: props.values.progressId || '',
              steps: dataSource,
            },
            ...formData,
          };
          await serviceClient.productProgressSettingService.update(updateDto);
          await props.onSuccess(params);
        } catch (error) {
          await props.onError(params, error);
        }
      }}
    >
      <ProFormGroup>
        <ProFormText name="subTitle1" label={'车间名称'} width="md" rules={[{ required: true }]} />
        <ProFormText name="subTitle2" label={'产品名称'} width="md" rules={[{ required: true }]} />
        <ProFormText
          name="werks"
          label={'工厂'}
          width="md"
          rules={[{ required: true, message: '请输入生产管理员。' }]}
        />
        <ProFormText
          name="fevor"
          label={'生产管理员'}
          width="md"
          rules={[{ required: true, message: '请输入生产管理员。' }]}
        />
        <ProFormDigit
          name="overdueNone"
          label={'按期（<{0}）'}
          width="md"
          rules={[{ required: true, message: '请输入超期警告天数。' }]}
        />
        <ProFormDigit
          name="overdueWarn"
          label={'超期警告（>={0} and <=严重超期）'}
          width="md"
          rules={[{ required: true, message: '请输入超期警告天数。' }]}
        />
        <ProFormDigit
          name="overdueSeverity"
          label={'严重超期>（{0}）'}
          width="md"
          rules={[{ required: true, message: '请输入严重超期天数。' }]}
        />
        <ProFormSwitch name="isSyncOverdue" label="是否关联修改" />
      </ProFormGroup>
      <ProForm.Item label="添加数据列" name="dataSource" trigger="onValuesChange">
        <EditableProTable<KANBAN.Settings.ProgressStepDto>
          rowKey="rowKey"
          toolBarRender={false}
          columns={editColumns}
          value={dataSource}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            position: 'top',
            record: () => ({
              rowKey: Date.now().toString(),
              id: '',
              code: '',
              name: '',
              type: 1,
              fevor: '',
              ordinal: 0,
              extraTypeDes: '',
            }),
          }}
          editable={{
            type: 'multiple',
            editableKeys,
            actionRender: (row, _, dom) => {
              return [dom.delete];
            },
            onValuesChange: (record, recordList) => {
              setDataSource(recordList);
            },
            onChange: setEditableRowKeys,
          }}
        />
      </ProForm.Item>
    </DrawerForm>
  );
};

export default EditForm;
