import React, { useRef, useState } from 'react';
import { DrawerForm, ProFormCheckbox, ProFormDigit, ProFormSelect } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { queryCKKanbanSetting } from '../../services/api';
import type { SettingDto } from '../../services/api';

export type Setting = {
  autoResize: boolean;
  intervalTime: number;
  rowMovingTime: number;
  cKProgressKanbanSetting?: SettingDto;
  kanbanId: string;
};

export type SettingFormProps = {
  values: Partial<Setting>;
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  onSubmitting: (setting: Setting) => Promise<any>;
};

const SettingForm: React.FC<SettingFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const [kanbanSettingList, setKanbanSettingList] = useState<SettingDto[]>([]);

  return (
    <DrawerForm
      formRef={formRef}
      title="设置"
      width={600}
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          formRef?.current?.setFieldsValue({
            ...props.values,
            productionProgressKanbanSettingId: props.values.cKProgressKanbanSetting?.id,
          });
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async (values: Setting) => {
        const cKProgressKanbanSetting = kanbanSettingList.find((a) => a.id === values.kanbanId);
        props.onSubmitting({ ...values, cKProgressKanbanSetting });
        props.onVisibleChange(false);
      }}
    >
      <ProFormCheckbox name="autoResize" label="适配窗口" width="xl" />
      <ProFormDigit
        name="intervalTime"
        label="刷新时间间隔（秒）"
        required
        width="xl"
        min={10}
        fieldProps={{ precision: 0 }}
      />
      <ProFormDigit
        name="rowMovingTime"
        label="内容滚动（秒）"
        required
        width="xl"
        min={1}
        fieldProps={{ precision: 0 }}
      />
      <ProFormSelect
        name="kanbanId"
        label="看板设置"
        required
        width="xl"
        request={async () => {
          const { data } = await queryCKKanbanSetting();
          setKanbanSettingList(data);
          return data.map((a) => ({ label: a.werks + '-' + a.kanbTitle, value: a.id }));
        }}
      />
    </DrawerForm>
  );
};

export default SettingForm;
