import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, notification, DatePicker, Spin, Button, Card, Row, Col } from 'antd';
import styles from '../policiesIssued.less'
// import moment from 'moment';
// import locale from 'antd/es/date-picker/locale/zh_CN';
// import 'moment/locale/zh-cn';

import moment from 'moment'
import locale from 'antd/lib/date-picker/locale/zh_CN'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
import {
  getEquipmentInfo, getQutaList, addStrategyOptions, editStrategyOptions, getPredictDevice, getPredictDevicePoint, getPredictInfo
} 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 [predictCode, setPredictCode] = useState([]); //预测编码列表
  const [deviceList, setDeviceList] = useState([]); //设备列表
  const [card, setCard] = useState([]); //卡片列表值
  const [dateArr, setDateArr] = useState({ DeviationType: '秒', DeviationValue: 0, DurationType: '秒', DurationValue: 0}); //偏移量,时段时长
  const [source, setSource] = useState([])
  const [showTime, setShowTime] = useState(true)
  const [PredictID, setPredictID] = useState()
  const [form] = Form.useForm();
  const { Item } = Form;
  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        let obj = form.getFieldsValue();
        let api = addStrategyOptions
        let query = {
          DeviceType: obj.DeviceType,
          StrategyDes: obj.StrategyDes,
          StrategyName: obj.StrategyName,
          StrategyType: obj.StrategyType,
          DeviationType: dateArr.DeviationType,
          DeviationValue: dateArr.DeviationValue,
          DurationType: dateArr.DurationType,
          DurationValue: dateArr.DurationValue,
          DetailInfos: card,
          CreateTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          PredictID
        }
        type === 'edit' ? (query.ID = formObj.ID) && (api = editStrategyOptions) : delete query.ID && (api = addStrategyOptions)
        setLoading(true);
        api(query).then(res => {
          setLoading(false);
          if (res.errMsg === '') {
            form.resetFields();
            callBackSubmit();
            prompt('success', `${type === 'add' ? "增加成功" : res.errMsg}`)
          } else {
            prompt('fail',  res.errMsg)
          }
        }).catch(e => {
          setLoading(false);
        })
      }
    });
  };
  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 = () => {
    getPredictInfo().then(res => {
      res.getMe && res.getMe.length && setSource(res.getMe)
    })
    if (type === 'add') {
      form.resetFields();
      setCard([])
      setDeviceList([])
      setShowTime(true)
      setDateArr({ DeviationType: '秒', DeviationValue: 0, DurationType: '秒', DurationValue: 0})
    }
    else {
      let { DeviationType, DeviationValue, DurationType, DurationValue } = formObj
      formObj.StrategyType === '时段控制' ? setShowTime(true) : setShowTime(false)
      setDateArr({ DeviationType, DeviationValue, DurationType, DurationValue })
      form.setFieldsValue({ time: moment(formObj.CreateTime, "YYYYMMDDHHmmss"), ...formObj });
      if (formObj.DetailInfos.length) {
        let req1 = getEquipmentInfo(formObj.DeviceType)
        let req2 = getPredictDevice(formObj.DeviceType)
        Promise.all([req1, req2]).then(respone => {
          console.log('respone', respone);
          respone[0].getMe.length && respone[0].getMe[0].DeviceList.length && setDeviceCode(respone[0].getMe[0].DeviceList)
          respone[1].getMe.length && setPredictCode(respone[1].getMe)
          let arr = []
          formObj.DetailInfos.map((item, index) => {
            arr[index] = {}
            arr[index].code = respone[0].getMe.length ? respone[0].getMe[0].DeviceList : []
            arr[index].predictCode = respone[1].getMe.length ? respone[1].getMe : []
            form.setFieldsValue({
              [`deviceCode${index}`]: item.ControlCode,
              [`indextr${index}`]: item.ControlPoint,
              [`max${index}`]: item.PredictCode,
              [`min${index}`]: item.PredictPoint
            })
          })
          setCard(formObj.DetailInfos)
          setDeviceList(arr)
          setLoading(false)
        })
      }

    }

  }
  //获取设备编码
  const getDeviceCode = () => {
    setLoading(false)
    let obj = form.getFieldsValue();
    let req1 = getEquipmentInfo(obj.DeviceType)
    let req2 = getPredictDevice(obj.DeviceType)
    Promise.all([req1, req2]).then(respone => {
      respone[0].getMe.length && respone[0].getMe[0].DeviceList.length && setDeviceCode(respone[0].getMe[0].DeviceList)
      respone[1].getMe.length && setPredictCode(respone[1].getMe)
      if (deviceList.length) {
        let arr = [...deviceList]
        arr.map((item, index) => {
          arr[index].code = respone[0].getMe.length ? respone[0].getMe[0].DeviceList : []
          arr[index].predictCode = respone[1].getMe.length ? respone[1].getMe : []
          arr[index].indexStr = ''
          arr[index].predictStr = ''
          clearInput(index)
        })
        setDeviceList(arr)
      }
      setLoading(false)
    })

  }
  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 16,
    },
  };
  //选择设备类型
  const handleDeviceType = (value) => {
    getDeviceCode()
  }

  //选择设备编码
  const handleChange = (value, option) => {
    let cardList = [...card]
    cardList[+option.index].ControlCode = 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 handleChange1 = (value, option) => {
    let cardList = [...card]
    cardList[+option.index].PredictCode = value
    setCard(cardList)
    let obj = form.getFieldsValue();
    getPredictDevicePoint({ deviceType: obj.DeviceType, DeviceCode: value }).then(res => {
      console.log('res', res);
      if (res.getMe && res.getMe.length) {
        let arr = [...deviceList]
        arr[+option.index].predictStr = res.getMe
        setDeviceList(arr)
      }
    })
  }
  //选择设备指标
  const handleChangeIndex = (value, option) => {
    let cardList = [...card]
    cardList[+option.index].ControlPoint = value
    setCard(cardList)
  }
  //选择预测指标
  const handleChangeIndex1 = (value, option) => {
    let cardList = [...card]
    cardList[+option.index].PredictPoint = 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, predictCode })
      setDeviceList(arr)
    }
  }
  //清除卡片删除一项的值
  const clearInput = (index) => {
    form.setFieldsValue({
      [`deviceCode${index}`]: undefined,
      [`indextr${index}`]: undefined,
      [`max${index}`]: undefined,
      [`min${index}`]: undefined
    })
  }
  //删除卡片
  const deleteDevice = (index) => {
    let cardList = [...card]
    let arr = [...deviceList]
    cardList.splice(index, 1)
    arr.splice(index, 1)
    clearInput(index)
    setCard(cardList)
    setDeviceList(arr)
  }
  const handleOrgin = (value, option) => {
    setPredictID(option.id)
  }
  const changeDeviationValue = (e) => {
    const newArr = { ...dateArr }
    newArr.DeviationValue = e.target.value
    setDateArr(newArr)
  }
  const changeDeviationType = (value) => {
    const newArr = { ...dateArr }
    newArr.DeviationType = value
    setDateArr(newArr)
  }
  const changeDurationValue = (e) => {
    const newArr = { ...dateArr }
    newArr.DurationValue = e.target.value
    setDateArr(newArr)
  }
  const changeDurationType = (value) => {
    const newArr = { ...dateArr }
    newArr.DurationType = value
    setDateArr(newArr)
  }
  const hangleTime = (value) => {
    value === '时段控制' ? setShowTime(true) : setShowTime(false)
    const newArr = { ...dateArr }
    newArr.DurationValue = 0
    newArr.DurationType = '秒'
    setDateArr(newArr)
  }
  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} {...layout} onFinish={onFinish}>
            <Item
              label="策略名称"
              name="StrategyName"
              rules={[{ required: true, message: '请输入策略名称' }]}
            >
              <Input placeholder="请输入任务名称" allowClear />
            </Item>
            <Item
              label="策略类型"
              name="StrategyType"
              rules={[{ required: true, message: '请选择策略类型' }]}
            >
              <Select onChange={hangleTime} >
                <Select.Option value='实时控制'>实时控制</Select.Option>
                <Select.Option value='时段控制'>时段控制</Select.Option>
              </Select>
            </Item>
            <Item
              label="数据来源"
              name="PredictName"
              rules={[{ required: true, message: '请选择数据来源' }]}
            >
              <Select onChange={(value, option) => handleOrgin(value, option)}>
                {source.length ? source.map((item, index) => { return <Select.Option key={index} id={item.ID} value={item.PredictName}>{item.PredictName}</Select.Option> }) : ''}
              </Select>
            </Item>
            <Item
              label="设备类型"
              name="DeviceType"
            >
              <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: '64%' }} placeholder="请输入偏移量" value={dateArr.DeviationValue} onChange={changeDeviationValue} allowClear />
                <Select style={{ marginLeft: '2rem', width: '28%' }} onChange={changeDeviationType} value={dateArr.DeviationType}>
                  <Select.Option value='秒'>秒</Select.Option>
                  <Select.Option value='分'>分</Select.Option>
                  <Select.Option value='时'>时</Select.Option>
                  <Select.Option value='日'>日</Select.Option>
                </Select>
              </div>
            </Item>
            {showTime ? <Item
              label="时段时长"
              name="Cycle"
              rules={[{ required: true, message: '请输入时段时长' }]}
            >
              <div>
                <div className={styles.predict}></div>
                <Input style={{ width: '64%' }} placeholder="请输入时段时长" value={dateArr.DurationValue} onChange={changeDurationValue} allowClear />
                <Select style={{ marginLeft: '2rem', width: '28%' }} onChange={changeDurationType} value={dateArr.DurationType}>
                  <Select.Option value='秒'>秒</Select.Option>
                  <Select.Option value='分'>分</Select.Option>
                  <Select.Option value='时'>时</Select.Option>
                  <Select.Option value='日'>日</Select.Option>
                </Select>
              </div>
            </Item> : ''}
            <Item
              label="描述"
              name="StrategyDes"
            >
              <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' justify='space-between'>
                    <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' justify='space-between'>
                    <Col span={12}>
                      <Item
                        label="预测编码"
                        name={'max' + index}
                        rules={[{ required: true, message: '请输入预测编码' }]}
                      >
                        <Select
                          placeholder="请选择预测编码"
                          onChange={(value, option) => handleChange1(value, option)}
                        >
                          {item.predictCode.length ? item.predictCode.map((item, codeIndex) => { return <Select.Option index={index} key={codeIndex} value={item} >{item}</Select.Option> }) : ''}
                        </Select>
                        {/* <Input placeholder="请输入最大值" onChange={(value) => inputMax(value, index)} index={index} allowClear /> */}
                      </Item>
                    </Col>
                    <Col span={12}>
                      <Item
                        label="预测指标"
                        name={'min' + index}
                        rules={[{ required: true, message: '请输入预测指标' }]}
                      >
                        <Select
                          placeholder="请选择预测指标"
                          style={{ width: '98%', marginLeft: '0.4rem' }}
                          onChange={(value, option) => handleChangeIndex1(value, option)}
                        >
                          {item.predictStr && item.predictStr.length ? item.predictStr.map((item, zindex) => { return <Select.Option key={zindex} index={index} value={item}>{item}</Select.Option> }) : ''}
                        </Select>
                      </Item>
                    </Col>
                  </Row>
                  <DeleteOutlined
                    className={styles.deleteItem}
                    onClick={() => deleteDevice(index)}
                    style={{ fontSize: '16px', color: '#e86060' }}
                  />
                </Card>
              }) : ''}
            </div>
          </Form>
        )}
      </Spin>

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