import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, notification, Spin, Button, Card, Row, Col } from 'antd';
import styles from '../policiesIssued.less'
import {
  getEquipmentInfo, getQutaList, addPredictOptions, getSceneNameInfo, editPredictOptions
} from '@/services/intelligence/api';
import { DeleteOutlined } from '@ant-design/icons';

const { TextArea } = Input;
const AddModal = props => {
  const { callBackSubmit = () => { }, type, formObj, visible, deviceType } = props;
  const [loading, setLoading] = useState(false);
  const [isloading, setIsLoading] = useState(false);
  const [deviceCodes, setDeviceCode] = useState([]); //设备编码列表
  const [deviceList, setDeviceList] = useState([]); //设备列表
  const [card, setCard] = useState([]); //卡片列表值
  const [timeType, setTimeType] = useState(['分钟', '小时', '天']);
  const [PredictType, setPredictType] = useState(['日', '周', '月']);
  const [showTime, setShowTime] = useState(true);
  const [commonType, setCommonType] = useState(['自定义', '同周日', '同月日']);
  const [intervalType, setIntervalType] = useState('分钟')
  const [CycleValue, setCycleValue] = useState('')
  const [sceneList, setSceneList] = useState([])
  const [form] = Form.useForm();
  const { Item } = Form;
  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        let obj = form.getFieldsValue();

        let api = addPredictOptions
        let query = {
          SceneName: obj.SceneName,
          Cycle: intervalType,
          CycleValue: CycleValue,
          DeviceType: obj.DeviceType,
          PredictName: obj.PredictName,
          Remarks: obj.Remarks,
          DeviceDetails: card,
          PredictCycle: obj.PredictCycle ? obj.PredictCycle : '',
          PredictCycleValue: obj.PredictCycleValue,
          StatisticCycle: obj.StatisticCycle,
          PredictType: obj.PredictType,
          StatisticCycleValue: obj.StatisticCycleValue
        }
        // card.length ? query.DeviceDetails = card : delete query.DeviceDetails
        type === 'edit' ? (query.ID = formObj.ID) && (api = editPredictOptions) : delete query.ID && (api = addPredictOptions)
        setLoading(true);
        api(query).then(res => {
          setLoading(false);
          if (res.errMsg === '') {
            form.resetFields();
            callBackSubmit();
            prompt('success', `${type === 'add' ? "增加成功" : "编辑成功"}`)
          } else {
            prompt('fail', res.errMsg)
          }
        })
      }
    });
  };
  const prompt = (type, content) => {
    if (type == 'success') {
      notification.success({
        message: '提示',
        duration: 3,
        description: content,
      });
    }
    else {
      notification.error({
        message: '提示',
        duration: 3,
        description: content,
      });
    }
  }
  const onFinish = value => { };
  useEffect(() => {
    switch (type) {
      case 'add':
        initData()
        break;
      case 'edit':
        initData()
        break;
      default:
        break;
    }
  }, [visible]);

  //页面初始化
  const initData = () => {
    if (type === 'add') {
      form.resetFields();
      setCycleValue('');
      setIntervalType('小时');
      setCard([])
      setDeviceList([])
    }
    else {
      setDeviceList([])
      formObj.PredictType === '日' ? setShowTime(true) : setShowTime(false)
      form.setFieldsValue({ ...formObj });
      setCycleValue(formObj.CycleValue);
      setIntervalType(formObj.Cycle);
      if (formObj.DeviceDetails.length) {
        getEquipmentInfo(formObj.DeviceType).then(respone => {
          respone.getMe.length && respone.getMe[0].DeviceList.length && setDeviceCode(respone.getMe[0].DeviceList)
          let arr = [...deviceList]
          formObj.DeviceDetails.map((item, index) => {
            arr[index] = {}
            arr[index].code = respone.getMe.length ? respone.getMe[0].DeviceList : []
            form.setFieldsValue({
              [`deviceCode${index}`]: item.DeviceCode,
              [`indextr${index}`]: item.PointAddress,
              [`max${index}`]: item.MaxValue,
              [`min${index}`]: item.MinValue
            })
          })
          setCard(formObj.DeviceDetails)
          setDeviceList(arr)
          setLoading(false)
        })
      }

    }

    getSceneNameInfo().then(res => {
      res.getMe.length && setSceneList(res.getMe)
    })
  }
  //获取设备编码
  const getDeviceCode = () => {
    setLoading(false)
    let obj = form.getFieldsValue();
    getEquipmentInfo(obj.DeviceType).then(respone => {
      respone.getMe.length && respone.getMe[0].DeviceList.length && setDeviceCode(respone.getMe[0].DeviceList)
      if (deviceList.length) {
        let arr = [...deviceList]
        arr.map((item, index) => {
          arr[index].code = respone.getMe.length ? respone.getMe[0].DeviceList : []
          arr[index].indexStr = ''
          clearInput(index)
        })

        setDeviceList(arr)
      }
      setLoading(false)
    })
  }

  //选择设备类型
  const handleDeviceType = (value) => {
    getDeviceCode()
  }
  const handleIntervalType = (value) => {
    setIntervalType(value)
  }
  //选择设备编码
  const handleChange = (value, option) => {
    let cardList = [...card]
    cardList[+option.index].DeviceCode = value
    setCard(cardList)
    let obj = form.getFieldsValue();
    getQutaList({ accountName: obj.DeviceType, AddrSchemeID: option.pointid }).then(res => {
      if (res.getMe && res.getMe.length) {
        let arr = [...deviceList]
        arr[+option.index].indexStr = res.getMe
        setDeviceList(arr)
      }
    })

  }
  //选择设备指标
  const handleChangeIndex = (value, option) => {
    let cardList = [...card]
    cardList[+option.index].PointAddress = value
    setCard(cardList)
  }
  //最大值
  const inputMax = (e, option) => {
    e.persist();
    let cardList = [...card]
    cardList[option].MaxValue = e.target.value
    setCard(cardList)
  }
  //最小值
  const inputMin = (e, option) => {
    e.persist();
    let cardList = [...card]
    cardList[option].MinValue = e.target.value
    setCard(cardList)
  }
  const add = () => {
    let obj = form.getFieldsValue();
    if (!obj.DeviceType) {
      notification.error({
        message: '提示',
        duration: 3,
        description: '请选择设备类型',
      });
    } else {
      let cardList = [...card]
      let arr = [...deviceList]
      cardList.push({})
      setCard(cardList)
      arr.push({ code: deviceCodes })
      setDeviceList(arr)
    }
  }
  //删除卡片
  const deleteDevice = (index) => {
    let cardList = [...card]
    let arr = [...deviceList]
    cardList.splice(index, 1);
    arr.splice(index, 1);
    clearInput(index)
    setCard(cardList)
    setDeviceList(arr)
  }
  const clearInput = (index) => {
    form.setFieldsValue({
      [`deviceCode${index}`]: undefined,
      [`indextr${index}`]: undefined,
      [`max${index}`]: undefined,
      [`min${index}`]: undefined
    })
  }
  const selectPredictType = (value) => {
    value === '日' ? setShowTime(true) : setShowTime(false)
  }
  //选择小时,分,天
  const selectCycleValue = (e) => {
    setCycleValue(e.target.value)
  }
  return (
    <Modal
      title={`${type === 'add' ? '预测方案新增' : '编辑'}`}
      bodyStyle={{ width: '100%', minHeight: '100px' }}
      style={{ top: '150px' }}
      width="800px"
      destroyOnClose
      maskClosable={false}
      cancelText="取消"
      okText="确认"
      {...props}
      onOk={() => onSubmit()}
      confirmLoading={loading}
      forceRender={true}
      getContainer={false}
    >
      <Spin spinning={isloading} delay={300}>
        {visible && (
          <Form form={form} onFinish={onFinish}>
            <Item
              label="方案名称"
              name="PredictName"
              rules={[{ required: true, message: '请输入方案名称' }]}
            >
              <Input placeholder="请输入方案名称" allowClear />
            </Item>
            <Item
              label="场景名称"
              name="SceneName"
              rules={[{ required: true, message: '请输入算法名称' }]}
            >
              <Select >
                {sceneList.length ? sceneList.map((item, index) => { return <Select.Option key={index} value={item.scenename}>{item.scenename}</Select.Option> }) : ''}
              </Select>
            </Item>
            <Item
              label="设备类型"
              name="DeviceType"
              rules={[{ required: true, message: '请输入设备类型' }]}
            >
              <Select onChange={handleDeviceType} >
                {deviceType.length ? deviceType.map((item, index) => { return <Select.Option key={index} value={item.DeviceType}>{item.DeviceType}</Select.Option> }) : ''}
              </Select>
            </Item>
            <Item
              label="预测间隔"
              name="Cycle"
              rules={[{ required: true, message: '请输入预测间隔' }]}
            >
              <div>
                <div className={styles.predict}></div>
                <Input style={{ width: '67.2%' }} placeholder="请输入预测间隔" value={CycleValue} onChange={(value) => selectCycleValue(value)} allowClear />
                <Select style={{marginLeft:'1.5rem', width: '29%' }} onChange={handleIntervalType} value={intervalType}>
                  {timeType.length ? timeType.map((item, index) => { return <Select.Option key={index} value={item}>{item}</Select.Option> }) : ''}
                </Select>
              </div>
            </Item>
            <Row gutter='24' >
              <Item
                label="预测维度"
                name="PredictType"
                style={{ marginLeft: '0.8rem' }}
                rules={[{ required: true, message: '请选择预测维度' }]}
              >
                <Select onChange={selectPredictType} style={{ width: '8.4rem' }}>
                  {PredictType.length ? PredictType.map((item, index) => { return <Select.Option key={index} value={item}>{item}</Select.Option> }) : ''}
                </Select>
              </Item>
              {showTime ? <Item
                label="维度类别"
                name="PredictCycle"
                style={{ marginLeft: '0.8rem' }}
                rules={[{ required: true, message: '请选择维度类别' }]}
              >
                <Select style={{ width: '9rem' }}>
                  {commonType.length ? commonType.map((item, index) => { return <Select.Option key={index} value={item}>{item}</Select.Option> }) : ''}
                </Select>
              </Item> : ''}
              <Item
                label="预测维度值"
                style={{ marginLeft: '0.8rem' }}
                name="PredictCycleValue"
                rules={[{ required: true, message: '请输入预测维度值' }]}
              >
                <Input placeholder="请输入预测维度值" style={{ width: '12rem' }} allowClear />
              </Item>
            </Row>
            <Row gutter='24' >
              <Item
                label="统计维度"
                style={{ marginLeft: '0.8rem' }}
                name="StatisticCycle"
                rules={[{ required: true, message: '请选择预测维度' }]}
              >
                <Select style={{ width: '18rem' }}>
                  {PredictType.length ? PredictType.map((item, index) => { return <Select.Option key={index} value={item}>{item}</Select.Option> }) : ''}
                </Select>
              </Item>
              <Item
                label="统计维度值"
                style={{ marginLeft: '0.8rem' }}
                name="StatisticCycleValue"
                rules={[{ required: true, message: '请输入统计维度值' }]}
              >
                <Input  style={{ width: '17.2rem' }} placeholder="请输入统计维度值" allowClear />
              </Item>
            </Row>
            <Item
              label="描述"
              name="Remarks"
              style={{ marginLeft: '2.4rem' }}
            >
              <TextArea placeholder="可输入描述信息" rows={4} allowClear />
            </Item>
            <Button size="small" onClick={() => { add() }}>
              新增
            </Button>
            <div className={styles.deviceList}>
              {deviceList.length ? deviceList.map((item, index) => {
                return <Card key={index} style={{ marginTop: '0.5rem' }}>
                  <Row gutter='36' >
                    <Col span={12}>
                      <Item
                        label="设备编码"
                        name={'deviceCode' + index}
                        rules={[{ required: true, message: '请选择设备编码' }]}
                      >
                        <Select
                          placeholder="请选择设备编码"
                          onChange={(value, option) => handleChange(value, option)}
                        >
                          {item.code.length ? item.code.map((item, codeIndex) => { return <Select.Option index={index} key={codeIndex} value={item.Code} pointid={item.PointAddressID}>{item.Code}</Select.Option> }) : ''}
                        </Select>
                      </Item>
                    </Col>
                    <Col span={12}>
                      <Item
                        label="指标名称"
                        name={'indextr' + index}
                        rules={[{ required: true, message: '请选择指标名称' }]}
                      >
                        <Select
                          placeholder="请选择指标"
                          onChange={(value, option) => handleChangeIndex(value, option)}
                        >
                          {item.indexStr && item.indexStr.length ? item.indexStr.map((item, zindex) => { return <Select.Option key={zindex} index={index} value={item.Name}>{item.Name}</Select.Option> }) : ''}
                        </Select>
                      </Item>
                    </Col>
                  </Row>
                  <Row gutter='24' >
                    <Col span={12}>
                      <Item
                        label="最小值"
                        style={{ marginLeft: '1.5rem' }}
                        name={'min' + index}
                      >
                        <Input placeholder="请输入最小值" style={{ width: '98%' }} onChange={(value) => inputMin(value, index)} index={index} allowClear />
                      </Item>
                    </Col>
                    <Col span={12}>
                      <Item
                        label="最大值"
                        style={{ marginLeft: '1.6rem' }}
                        name={'max' + index}
                      >
                        <Input style={{ width: '98%', marginLeft: '0.4rem' }} placeholder="请输入最大值" onChange={(value) => inputMax(value, index)} index={index} allowClear />
                      </Item>
                    </Col>
                  </Row>
                  <DeleteOutlined
                    className={styles.deleteItem}
                    onClick={() => deleteDevice(index)}
                    style={{ fontSize: '16px', color: '#e86060' }}
                  />
                </Card>
              }) : ''}
            </div>
          </Form>
        )}
      </Spin>

    </Modal>
  );
};
export default AddModal;
