import AlarmLevelBox from '@/components/DictionaryBox/alarmLevel';
import { alarmLevelStatusEnum } from '@/enums/status';
import { localStorageKeyEnums } from '@/enums/storage';
import { DeleteOutlined, ExclamationCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { Form } from 'antd';
import React, { useEffect, useState } from 'react';
import { proFormSmallModelWidth } from '../../../../../config/defaultForm';
// TODO 需要根据接口替换API.DeviceCategory
export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<API.DeviceCategory>;

export type CreateFormProps = {
  alarmStatusModalOpen: boolean;
  handleModal: () => void;
  values: Partial<API.DeviceCategory>;
  reload: any;
};

/**style */

const tipStyle: React.CSSProperties = {
  display: 'flex',
  width: '100%',
  cursor: 'pointer',
  paddingBottom: 20,
};
const AlarmStatusForm: React.FC<CreateFormProps> = (props) => {
  const intl = useIntl();
  const [form] = Form.useForm<API.DeviceCategory>();
  const [alarmDict, setAlarmDict] = useState<Record<string, any>[]>([
    alarmLevelStatusEnum[0],
    alarmLevelStatusEnum[1],
    alarmLevelStatusEnum[2],
  ]);

  // 新增一项
  function doAddItem() {
    if (alarmDict.length >= 6) {
      return;
    }
    setAlarmDict((data) => [...data, alarmLevelStatusEnum[alarmDict.length]]);
  }
  // 删除一项
  function doDeleteItem(delItem: Record<string, any>) {
    setAlarmDict((data) => data.filter((item) => item.id !== delItem.id));
  }

  useEffect(() => {
    const currData = localStorage.getItem(
      localStorageKeyEnums.alarmSetting_model_alarmStatusSetting,
    );
    if (currData) {
      const finalData = alarmLevelStatusEnum.filter((item) =>
        Object.keys(JSON.parse(currData)).includes(item.id),
      );
      setAlarmDict(finalData);
    }
  }, []);

  return (
    <ModalForm<API.DeviceCategory>
      layout={'horizontal'}
      width={proFormSmallModelWidth}
      title={intl.formatMessage({
        id: 'alarm.setting.table.model.alarmStatusSetting',
        defaultMessage: '$$$',
      })}
      open={props.alarmStatusModalOpen}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => props.handleModal(),
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        console.log(values, 'values');
        localStorage.setItem(
          localStorageKeyEnums.alarmSetting_model_alarmStatusSetting,
          JSON.stringify(values),
        );
        // postDeviceCategoryCreateDeviceCategory(values)
        //   .then(() => {
        //     message.success(intl.formatMessage({ id: 'common.success', defaultMessage: '$$$' }));
        //     props.reload();
        //   })
        //   .catch(() => {
        //     message.error(intl.formatMessage({ id: 'common.failure', defaultMessage: '$$$' }));
        //   });
        props.handleModal();
        return true;
      }}
    >
      {/* TODO 待讨论是否需要动态添加状态字段 */}

      <ul>
        {alarmDict.map((item, index) => {
          const currVal = index % 6;
          const currLevel = alarmLevelStatusEnum[currVal];
          return (
            <li key={item.id} style={{ display: 'flex', width: '100%' }}>
              <div style={{ paddingTop: 5, paddingRight: 12 }}>
                <AlarmLevelBox size={20} {...currLevel}></AlarmLevelBox>
              </div>
              <div style={{ width: '100%', flex: 1 }}>
                <ProFormText name={item.id} initialValue={item.defaultLabel}></ProFormText>
              </div>
              {index === alarmDict.length - 1 && index > 2 ? (
                <div
                  style={{ paddingTop: 5, paddingLeft: 12 }}
                  onClick={() => {
                    doDeleteItem(item);
                  }}
                >
                  <DeleteOutlined
                    style={{
                      color: 'rgba(232, 13, 13, 1)',
                    }}
                  />
                </div>
              ) : (
                <></>
              )}
            </li>
          );
        })}
        {alarmDict.length < 6 ? (
          <li
            style={{ color: '#154DDD', ...tipStyle }}
            onClick={() => {
              doAddItem();
            }}
          >
            <div style={{ paddingRight: 12, fontSize: 16 }}>
              <PlusCircleOutlined />
            </div>
            <span>
              添加
              {intl.formatMessage({
                id: 'alarm.setting.table.model.alarmStatusSetting',
                defaultMessage: '$$$',
              })}
            </span>
          </li>
        ) : (
          <li style={{ ...tipStyle }}>
            <div style={{ paddingRight: 12, color: '#FAAD14' }}>
              <ExclamationCircleOutlined />
            </div>
            <span>
              {intl.formatMessage({
                id: 'alarm.setting.table.model.alarmStatusSetting',
                defaultMessage: '$$$',
              })}
              设置数量已达到极限，不能再添加了
            </span>
          </li>
        )}
      </ul>
    </ModalForm>
  );
};
export default AlarmStatusForm;
