import React, { useRef, useState } from 'react';
import type { ProFormInstance } from '@ant-design/pro-form';
import { DrawerForm, ProFormCheckbox, ProFormRadio, ProFormDigit } from '@ant-design/pro-form';
import { getAllWorkSite, getAllWorkUnit } from '@/services/mgr/resource/api';

export type Setting = {
  autoResize: boolean;
  intervalTime: number;
  machineProgramExceptionPageTurning: number;
  days: number;
  currentWorkSite?: API.WorkSite;
  selectedWorkUnits: API.WorkUnit[];
};

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 [allWorkSiteList, setAllWorkSiteList] = useState<API.WorkSite[]>([]);
  const [allWorkUnitList, setAllWorkUnitList] = useState<API.WorkUnit[]>([]);

  return (
    <DrawerForm
      formRef={formRef}
      title="设置"
      width={600}
      visible={props.visible}
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          formRef?.current?.setFieldsValue({
            ...props.values,
            selectedWorkSiteItem: props.values.currentWorkSite
              ? props.values.currentWorkSite.id
              : '',
            selectedWorkUnitItems: props.values.selectedWorkUnits
              ? props.values.selectedWorkUnits.map((w) => w.id)
              : [],
          });
        }
        props.onVisibleChange(visible);
      }}
      onFinish={async (values: {
        autoResize: boolean;
        intervalTime: number;
        machineProgramExceptionPageTurning: number;
        days: number;
        selectedWorkSiteItem: string;
        selectedWorkUnitItems: string[];
      }) => {
        const currentWorkSite = allWorkSiteList.find((w) => w.id === values.selectedWorkSiteItem);
        const selectedWorkUnits = allWorkUnitList.filter(
          (w) => values.selectedWorkUnitItems.findIndex((x) => w.id === x) >= 0,
        );
        props.onSubmitting({ ...values, currentWorkSite, selectedWorkUnits });
        props.onVisibleChange(false);
      }}
    >
      <ProFormCheckbox name="autoResize" label="适配窗口" width="xl" />
      <ProFormDigit
        name="intervalTime"
        label="刷新时间间隔（秒）"
        required
        width="xl"
        min={10}
        fieldProps={{ precision: 0 }}
      />
      <ProFormDigit
        name="machineProgramExceptionPageTurning"
        label="异常运行程序翻页（秒）"
        required
        width="xl"
        min={1}
        fieldProps={{ precision: 0 }}
      />
      <ProFormDigit
        name="days"
        label="筛选时间范围（天）"
        required
        width="xl"
        min={1}
        max={30}
        fieldProps={{ precision: 0 }}
      />
      <ProFormRadio.Group
        name="selectedWorkSiteItem"
        label="车间"
        width="xl"
        fieldProps={{
          onChange: (ev) => {
            if (ev.target.value && ev.target.value !== 'all') {
              formRef?.current?.setFieldsValue({
                ...formRef.current.getFieldsValue(),
                selectedWorkUnitItems: allWorkUnitList
                  .filter((w) => w.workCenter.workSite.id === ev.target.value)
                  .map((w) => w.id),
              });
            } else {
              formRef?.current?.setFieldsValue({
                ...formRef.current.getFieldsValue(),
                selectedWorkUnitItems: allWorkUnitList.map((w) => w.id),
              });
            }
          },
        }}
        request={async ({ visible }) => {
          if (visible) {
            try {
              const sr = await getAllWorkSite();
              setAllWorkSiteList(sr);
              return [{ value: 'all', label: '全部' }].concat(
                sr.map((i) => ({
                  label: i.name,
                  value: i.id,
                })),
              );
            } catch {
              return [];
            }
          }
          return [];
        }}
        params={{ visible: props.visible }}
      />
      <ProFormCheckbox.Group
        name="selectedWorkUnitItems"
        label="作业单元"
        width="xl"
        dependencies={['selectedWorkSiteItem']}
        request={async ({ visible, selectedWorkSiteItem }) => {
          if (visible) {
            try {
              let allwu = allWorkUnitList;
              if (allwu.length === 0) {
                allwu = await getAllWorkUnit();
                setAllWorkUnitList(allwu);
              }
              if (selectedWorkSiteItem && selectedWorkSiteItem !== 'all') {
                return allwu
                  .filter((w) => w.workCenter.workSite.id === selectedWorkSiteItem)
                  .map((i) => ({
                    label: i.name,
                    value: i.id,
                  }));
              }
              return allwu.map((i) => ({
                label: i.name,
                value: i.id,
              }));
            } catch {
              return [];
            }
          }
          return [];
        }}
        params={{ visible: props.visible }}
      />
    </DrawerForm>
  );
};

export default SettingForm;
