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, { ProFormSelect } from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import serviceClient from '@/services/report/settings/index';

export type EditFormProps = {
  values: Partial<Report.Settings.ProductionProgressKanbanSettingDto>;
  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<Report.Settings.ProgressStepDto[]>(() => []);

  const editColumns: ProColumns<Report.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,
            sgNoSourceType: props.values.sgNoSourceTypeId,
          });
          props.values.progressStepList?.forEach((s) => {
            s.type = s.typeId;
            s.rowKey = s.id;
          });
          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: Report.Settings.ProductionProgressKanbanSettingUpdate = {
            id: props.values.id || '',
            progressUpdate: {
              id: props.values.progressId || '',
              steps: dataSource,
            },
            ...formData,
          };
          await serviceClient.productionProgressSettingService.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: '请输入生产管理员。' }]}
        />
        <ProFormSelect
          name="sgNoSourceType"
          label="施工号来源"
          width="md"
          rules={[{ required: true }]}
          options={[
            { label: '产品编号', value: 1 },
            { label: '施工号', value: 2 },
          ]}
        />
      </ProFormGroup>
      <ProFormGroup>
        <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<Report.Settings.ProgressStepDto>
          rowKey="rowKey"
          toolBarRender={false}
          columns={editColumns}
          value={dataSource}
          //onChange={setDataSource}
          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) => {
              console.log(record);
              console.log(recordList);
              setDataSource(recordList);
            },
            onChange: setEditableRowKeys,
          }}
        />
      </ProForm.Item>
    </DrawerForm>
  );
};

export default EditForm;
