import React, { useRef, useState, useEffect } from 'react';
import { useIntl } from 'umi';
import { Radio, Drawer, Form, Checkbox, InputNumber, Select } from 'antd';
import { queryProductionComprehensKanbanData } from '../../services/api';
type KanbanSetting = KANBAN.ProductionComprehens.ProductionComprehensKanbanDataDto;

type FormSettingDto = {
  autoResize: boolean;
  intervalTime: number;
  rowMovingTime: number;
  dataRange: number;
  planSource: number;
  productionComprehensKanbanSettingId: string;
};

export type Setting = {
  autoResize: boolean;
  intervalTime: number;
  rowMovingTime: number;
  dataRange: number;
  planSource: number;
  lineName?: 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 [form] = Form.useForm();
  const btn = useRef<HTMLButtonElement>(null);
  const btn1 = useRef<HTMLButtonElement>(null);
  const RadioList = useRef<any>([]);

  const CheckboxRef = useRef<HTMLInputElement>(null);
  const line = useRef<HTMLBaseElement>(null);
  const intervalTimeRef = useRef<HTMLInputElement>(null);
  const rowMovingTimeRef = useRef<HTMLInputElement>(null);
  const intl = useIntl();
  const [lineNameList, setLineNameList] = useState<
    KanbanSetting[]
  >([]);

  useEffect(async () => {
    if (props.visible) {
      console.log('props.values', props.values)
      const { data } = await queryProductionComprehensKanbanData();
      if (Array.isArray(data)) {
        data.unshift(intl.formatMessage({
          id: '全厂'
        }))
      }
      setLineNameList(data);
      form.setFieldsValue({...props.values});
      CheckboxRef.current?.focus()
    }
    props.onVisibleChange(props.visible);
  }, [props.visible]);
  const onPressEnter = (e) => {
    console.log('回车了')
    line.current?.focus()
  };
  const CheckboxKeyDown = (e) => {
    if (e.code === "ArrowDown") {
      intervalTimeRef.current?.focus()
    }
  }
  const cancelBtn = (e) => {
    if (e.code === "ArrowRight") {
      btn1.current?.focus()
    } else if (e.code === "ArrowUp") {
      line.current?.focus()
    }
  }
  const lineNameKeyDown = (e) => {
    // if (e.code === "ArrowRight") {
    //   const index1 = index + 1 >= lineNameList.length ? 0 : index + 1
    //   RadioList.current[index1]?.focus()
    // } else if (e.code === "ArrowLeft") {
    //   const index1 = index - 1 >= 0 ? lineNameList.length - 1 : index - 1
    //   RadioList.current[index1]?.focus()
    const a = document.getElementsByClassName('ant-select-open')
    if (e.code === "ArrowUp" && a.length === 0) {
      rowMovingTimeRef.current?.focus()
    } else if (e.code === "ArrowDown" && a.length === 0) {
      btn.current?.focus()
    }
  }
  return (
    <Drawer title={intl.formatMessage({id: '设置'})} width={600} onClose={() => {props.onVisibleChange(false)}} visible={props.visible}>
      <Form
      form={form}
      name="control-hooks"
      onFinish={async (values: FormSettingDto) => {
        console.log('values', values)
        props.onSubmitting({ ...values });
        props.onVisibleChange(false);
      }}
    >
      <Form.Item name="autoResize" label={intl.formatMessage({id: '适配窗口'})} valuePropName="checked">
        <Checkbox ref={CheckboxRef} onKeyDown={CheckboxKeyDown}></Checkbox>
      </Form.Item>
      <Form.Item name="intervalTime" label={intl.formatMessage({id: '刷新时间间隔（秒）'})} rules={[{ required: true }]}>
        <InputNumber precision={0} ref={intervalTimeRef}></InputNumber>
      </Form.Item>
      <Form.Item name="rowMovingTime" label={intl.formatMessage({id: '内容滚动（秒）'})} rules={[{ required: true }]}>
        <InputNumber precision={0} ref={rowMovingTimeRef} onPressEnter={onPressEnter}></InputNumber>
      </Form.Item>
      {/* <Form.Item name="lineName" label={intl.formatMessage({id: '产线选择'})} rules={[{ required: true }]}>
        <Radio.Group>
          {lineNameList.map((lineName, index) => (
            <Radio ref={el => (RadioList.current[index] = el)} onKeyDown={(e)=>{lineNameKeyDown(e, index)}} value={lineName}>{lineName}</Radio>
          ))}
        </Radio.Group>
      </Form.Item> */}
      <Form.Item name="lineName" label={intl.formatMessage({id: '产线选择'})} rules={[{ required: true }]}>
        <Select
          style={{ width: 120 }}
          ref={line}
          onInputKeyDown={lineNameKeyDown}
          options={lineNameList.map(v => ({value: v, label: v}))}
        />
      </Form.Item>
      
      <Form.Item>
        <button
          type='button'
          key="submit"
          ref={btn}
          onKeyDown={cancelBtn}
          onClick={() => form?.submit?.()}
        >
          {intl.formatMessage({id: '确认'})}
        </button>
      </Form.Item>
    </Form>
    </Drawer>
  );
};

export default SettingForm;
