import React, { useState, useEffect } from 'react';
import {
  Drawer,
  Form,
  Input,
  notification,
  Row,
  Col,
  Select,
  Button,
  Dropdown,
  Menu,
  Space,
} from 'antd';
import styles from './maintenance.less';
import ModalDrag from './ModalDrag';
import {
  CM_XWBPlan_AccountTable,
  CM_XWBPlan_feedbackTable,
  CM_XWBPlan_DataEditORAdd,
  CM_XWBPlan_DataList,
} from '@/services/maintenance/api';
import { CM_Event_LoadDepartmentAndRoles } from '@/services/standingBook/api';
import { PlusOutlined, DownOutlined, StepForwardFilled } from '@ant-design/icons';
import ChangeAdd from './ChangeAdd';

const { Option } = Select;
const AddModal = props => {
  const [inputValue, setInputValue] = useState({
    feedbackName: '',
    doRole: '',
  });
  const { callBackSubmit = () => {}, visible, type, formObj } = props;

  const [Type1, setType1] = useState('');
  const [Type2, setType2] = useState('');
  const [selectValue, setSelectValue] = useState('');
  const [selectValue1, setSelectValue1] = useState('');
  const [treeData, setTreeData] = useState([]);
  const [isVisible, setIsVisible] = useState(false);
  const [filed, setFiled] = useState({}); // 传给子组件列表数据
  const [filed1, setFiled1] = useState({}); // 传给子组件列表数据
  const [types, setTypes] = useState(''); // 弹窗类型
  const [pickItem, setPickItem] = useState(''); // 复选框数据填入项
  const [checkedList1, setCheckedList1] = useState([]); // 最新选择数据
  const [characterValue, setCharacterValue] = useState(''); // 打开弹框之前数据
  const [ff, setFf] = useState([]);

  const [form] = Form.useForm();
  const { Item } = Form;
  const { TextArea } = Input;

  useEffect(() => {
    getRole();
    if (type === 'add') {
      setType1('');
      setType2('');
      setInputValue({ feedbackName: '', doRole: '' });
      setFiled1({});
      form.resetFields();
    } else if (type === 'edit') {
      CM_XWBPlan_DataList({ id: formObj.id }).then(res => {
        let data = res.data[0];
        data && form.setFieldsValue({ ...data });
        setInputValue({ ...data });
        console.log(data.businessTypee);
        setType1(data.businessType);
        setType2(data.accountName);
      });
    }
  }, [visible]);

  useEffect(() => {
    getRole();
    getList();
    getFeedbackTable();
  }, []);
  const getList = () => {
    CM_XWBPlan_AccountTable().then(res => {
      if (res.msg == 'Ok') {
        let arr = [];
        res.data.map((item, index) => {
          arr.push(item.accountName);
        });
        setTreeData(arr);
      }
    });
  };

  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        let obj = form.getFieldsValue();
        obj.feedbackName = inputValue.feedbackName;
        obj.doRole = inputValue.doRole;
        console.log(obj.doRole);
        console.log(obj);
        if (type == 'add') {
          CM_XWBPlan_DataEditORAdd(obj).then(res => {
            if (res.msg == '') {
              form.resetFields();
              callBackSubmit();
              notification.success({
                message: '提示',
                duration: 3,
                description: '添加成功',
              });
            } else {
              notification.error({
                message: '提示',
                duration: 3,
                description: res.msg,
              });
            }
          });
        }
        if (type == 'edit') {
          CM_XWBPlan_DataEditORAdd({
            ...obj,
            id: formObj.id,
          }).then(res => {
            if (res.msg == '') {
              form.resetFields();
              callBackSubmit();
              notification.success({
                message: '提示',
                duration: 3,
                description: '添加成功',
              });
            } else {
              notification.error({
                message: '提示',
                duration: 3,
                description: res.msg,
              });
            }
          });
        }
      }
    });
  };
  const inputType1 = e => {
    setType1(e.target.value);
    form.setFieldsValue({ businessType: e.target.value });
  };
  const inputType2 = e => {
    setType2(e.target.value);
    form.setFieldsValue({ accountName: e.target.value });
  };
  const changeText = (e, type) => {
    let inputText = { ...inputValue };
    inputText[type] = e.target.value;
    setInputValue(inputText);
  };
  const pickFiled = fileds => {
    setTypes('add');
    setCharacterValue(inputValue[fileds]);
    setCheckedList1(inputValue[fileds].split(','));
    setPickItem(fileds);
    setIsVisible(true);
  };
  const pickFiled1 = fileds => {
    setTypes('app');
    setCharacterValue(inputValue[fileds]);
    setCheckedList1(inputValue[fileds].split(','));
    console.log(inputValue[fileds]);
    console.log(inputValue[fileds].split(','));
    setPickItem(fileds);
    setIsVisible(true);
  };
  const getRole = () => {
    CM_Event_LoadDepartmentAndRoles().then(res => {
      if (res.msg === 'Ok') {
        setFiled1(formateArrDataA1(res.data, 'groupType'));
        console.log(filed1);
        console.log(filed1['角色']);
        setFf(filed1['角色']);
        console.log(ff);
        console.log(res.data);
      }
    });
  };
  const getFeedbackTable = () => {
    CM_XWBPlan_feedbackTable().then(res => {
      if (res.msg === 'Ok') {
        let arr = [];
        res.data.map((item, index) => {
          arr.push(item.accountName);
        });
        setFiled(arr);
      }
    });
  };
  const formateArrDataA1 = (initialArr, name) => {
    let aa = [];
    let a1 = [];
    let a2;
    let a3 = [];
    initialArr.data.map(i => {
      // console.log(i.groupType)
      a2 = i.groupType;
      // console.log(a2)
      // console.log(i.root)
      a1 = i.root;
      a1.map(j => {
        j.group = a2;
        // console.log(j)
      });
      aa.push(i.root);
    });
    // console.log(aa)
    aa.map(p => {
      // console.log(p)
      p.map(o => {
        // console.log(o)
        a3.push(o);
      });
    });
    console.log(a3);

    // 判定传参是否符合规则
    if (!(a3 instanceof Array)) {
      return '请传入正确格式的数组';
    }
    if (!name) {
      return '请传入对象属性';
    }
    //先获取一下这个数组中有多少个"name"
    let nameArr = [];
    a3.map(i => {
      if (nameArr.indexOf(i.group) === -1) {
        nameArr.push(i.group);
      }
    });
    console.log(nameArr);
    //新建一个包含多个list的结果对象
    let tempObj = {};
    // 根据不同的"name"生成多个数组
    for (let k in nameArr) {
      for (let j in a3) {
        if (a3[j].group == nameArr[k]) {
          // 每次外循环时新建一个对应"name"的数组, 内循环时当前数组不变
          tempObj[nameArr[k]] = tempObj[nameArr[k]] || [];
          tempObj[nameArr[k]].push(a3[j]);
        }
      }
    }
    console.log(tempObj);
    for (let key in tempObj) {
      let arr = [];
      tempObj[key].map(item => {
        tempObj[key] = arr;
        arr.push(item.Name);
      });
    }
    return tempObj;
  };
  const changTable = value => {
    setSelectValue(value);
  };
  const changTable1 = value => {
    setSelectValue1(value);
  };
  const onOK = prop => {
    console.log(prop.isType);
    setIsVisible(false);
    let inputText = { ...inputValue };
    inputText[prop.pickItem] = prop.str;
    setCheckedList1(prop.checkedList);
    setInputValue(inputText);
  };
  // const title = <ModalDrag title="巡维保计划配置" />
  return (
    <Drawer
      title="巡维保计划配置"
      visible={visible}
      destroyOnClose
      width="600px"
      {...props}
      footer={
        <Space>
          <Button onClick={onSubmit} type="primary">
            确定
          </Button>
        </Space>
      }
    >
      <Form form={form} labelCol={{ span: 7 }} style={{ overflowY: 'scroll' }}>
        <Row>
          <Col span={23}>
            <Item
              label="业务名称"
              name="businessName"
              labelCol={{ span: 4 }}
              rules={[
                {
                  required: true,
                  message: '请输入业务名称',
                },
              ]}
            >
              <Input placeholder="业务名称不可重复" />
            </Item>
          </Col>
          <Col span={23}>
            <span
              style={{
                position: 'absolute',
                left: '1%',
                top: '9%',
                color: 'red',
                fontSize: '16px',
              }}
            >
              *
            </span>
            <Item
              label="业务类型"
              name="businessType"
              labelCol={{ span: 4 }}
              rules={[
                {
                  validator: (rule, value) => {
                    if (form.getFieldsValue().businessType == '') {
                      return Promise.reject('业务类型必填');
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <div>
                <Input
                  className="ue-editable-select-input"
                  onChange={inputType1}
                  value={Type1}
                  placeholder="选择或手动输入业务类型"
                />
                <Dropdown
                  placement="bottomRight"
                  style={{ width: '430px' }}
                  overlay={
                    <Menu>
                      <Menu.Item
                        key="巡检"
                        onClick={() => {
                          setType1('巡检');
                          form.setFieldsValue({ businessType: '巡检' });
                        }}
                        style={{ width: '430px', marginLeft: '-8px' }}
                      >
                        巡检
                      </Menu.Item>
                      <Menu.Item
                        key="保养"
                        onClick={() => {
                          setType1('保养');
                          form.setFieldsValue({ businessType: '保养' });
                        }}
                        style={{ width: '430px', marginLeft: '-8px' }}
                      >
                        保养
                      </Menu.Item>
                    </Menu>
                  }
                >
                  <div className={styles.linkDrowp} onClick={e => e.preventDefault()}>
                    <DownOutlined
                      style={{
                        fontSize: '12px',
                        color: 'rgba(0, 0, 0, 0.25)',
                        marginLeft: '5px',
                      }}
                    />
                  </div>
                </Dropdown>
              </div>
            </Item>
          </Col>
          <Col span={23}>
            <Item
              label="执行周期"
              name="docycle"
              labelCol={{ span: 4 }}
              rules={[
                {
                  required: true,
                  message: '请选择执行周期',
                },
              ]}
            >
              <Select placeholder="选择计划执行周期" onChange={changTable} value={selectValue}>
                <Option value="一周一次">一周一次</Option>
                <Option value="半月一次">半月一次</Option>
                <Option value="一月一次">一月一次</Option>
                <Option value="季度一次">季度一次</Option>
                <Option value="半年一次">半年一次</Option>
                <Option value="一年一次">一年一次</Option>
              </Select>
            </Item>
          </Col>
          <Col span={23}>
            <span
              style={{
                position: 'absolute',
                left: '1%',
                top: '9%',
                color: 'red',
                fontSize: '16px',
              }}
            >
              *
            </span>
            <Item
              label="台账名称"
              name="accountName"
              labelCol={{ span: 4 }}
              rules={[
                {
                  validator: (rule, value) => {
                    if (form.getFieldsValue().accountName == '') {
                      return Promise.reject('台账名称必选');
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <div>
                <Input
                  className="ue-editable-select-input"
                  onChange={inputType2}
                  value={Type2}
                  placeholder="选择此计划关联的设备台账名称"
                />
                <Dropdown
                  placement="bottomRight"
                  style={{ width: '430px' }}
                  overlay={
                    <Menu>
                      {treeData.length ? (
                        treeData.map((item, index) => {
                          return (
                            <Menu.Item
                              onClick={() => {
                                setType2(item);
                                form.setFieldsValue({ accountName: item });
                              }}
                              style={{ width: '430px', marginLeft: '-8px' }}
                              key={index}
                            >
                              {item}
                            </Menu.Item>
                          );
                        })
                      ) : (
                        <Menu.Item style={{ width: '430px', marginLeft: '-8px' }}>
                          <span style={{ color: 'red' }}>
                            暂无数据，请先配置台账管理台账名称为设备
                          </span>
                        </Menu.Item>
                      )}
                    </Menu>
                  }
                >
                  <div className={styles.linkDrowp} onClick={e => e.preventDefault()}>
                    <DownOutlined
                      style={{
                        fontSize: '12px',
                        color: 'rgba(0, 0, 0, 0.25)',
                        marginLeft: '5px',
                      }}
                    />
                  </div>
                </Dropdown>
              </div>
            </Item>
          </Col>
          <Col span={23}>
            <span
              style={{
                position: 'absolute',
                left: '1%',
                top: '9%',
                color: 'red',
                fontSize: '16px',
              }}
            >
              *
            </span>
            <Item
              label="反馈名称"
              name="feedbackName"
              labelCol={{ span: 4 }}
              rules={[
                {
                  validator: (rule, value) => {
                    if (inputValue.feedbackName == '') {
                      return Promise.reject('反馈名称必填');
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <div className={styles.filed_listItem}>
                <Input
                  style={{ width: '83%' }}
                  placeholder="请选择反馈名称"
                  onChange={e => changeText(e, 'feedbackName')}
                  value={inputValue.feedbackName}
                  allowClear
                />
                <Button
                  type="dashed"
                  onClick={() => pickFiled('feedbackName')}
                  icon={<PlusOutlined style={{ marginTop: '5px' }} />}
                  style={{ marginLeft: '0.5rem', width: '4rem' }}
                />
              </div>
            </Item>
          </Col>
          <Col span={23}>
            <span
              style={{
                position: 'absolute',
                left: '1%',
                top: '9%',
                color: 'red',
                fontSize: '16px',
              }}
            >
              *
            </span>
            <Item
              label="执行角色"
              name="doRole"
              labelCol={{ span: 4 }}
              rules={[
                {
                  validator: (rule, value) => {
                    if (inputValue.doRole == '') {
                      return Promise.reject('执行角色必填');
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <div className={styles.filed_listItem}>
                <Input
                  style={{ width: '83%' }}
                  placeholder="请选择执行角色"
                  onChange={e => changeText(e, 'doRole')}
                  value={inputValue.doRole}
                  allowClear
                />
                <Button
                  type="dashed"
                  onClick={() => pickFiled1('doRole')}
                  icon={<PlusOutlined style={{ marginTop: '5px' }} />}
                  style={{ marginLeft: '0.5rem', width: '4rem' }}
                />
              </div>
            </Item>
          </Col>
          <Col span={13}>
            <Item
              label="预生成天数"
              name="produceDays"
              rules={[
                {
                  required: true,
                  message: '请输入预生成天数',
                },
              ]}
            >
              <Input placeholder="请输入预生成天数" />
            </Item>
          </Col>
          <Col span={10}>
            <Item
              label="在线任务量"
              name="onLines"
              labelCol={{ span: 10 }}
              rules={[
                {
                  required: true,
                  message: '请输入在线任务量',
                },
              ]}
            >
              <Input placeholder="请输入在线任务量" />
            </Item>
          </Col>
          <Col span={23}>
            <Item
              label="是否送审"
              name="isSubmit"
              labelCol={{ span: 4 }}
              rules={[
                {
                  required: true,
                  message: '请选择是否送审',
                },
              ]}
            >
              <Select placeholder="是否送审" onChange={changTable1} value={selectValue1}>
                <Option value="否">否</Option>
                <Option value="是">是</Option>
              </Select>
            </Item>
          </Col>
          <Col span={23}>
            <Item label="台账过滤条件" name="filterCondition" labelCol={{ span: 4 }}>
              <TextArea placeholder="设备对应的Scada台账名称,可多选" />
            </Item>
          </Col>
        </Row>
      </Form>
      <ChangeAdd
        visible={isVisible}
        onCancel={() => setIsVisible(false)}
        callBackSubmit={onOK}
        newCheckedList={checkedList1}
        isType={types}
        filed={filed}
        type={type}
        filed1={filed1}
        ff={ff}
        pickItem={pickItem}
        characterValue={characterValue}
      />
    </Drawer>
  );
};
export default AddModal;
