/* eslint-disable indent */
/* eslint-disable camelcase */
/* eslint-disable no-unused-expressions */
import React, { useState, useEffect } from 'react';
import {
  Drawer,
  Form,
  Input,
  notification,
  Row,
  Col,
  Select,
  Button,
  Dropdown,
  Tooltip,
  Menu,
  Space,
  Radio,
} from 'antd';
import {
  PlusOutlined,
  DownOutlined,
  StepForwardFilled,
  InfoCircleOutlined,
} from '@ant-design/icons';
import styles from './maintenance.less';
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 RMSComponents from '@/components/RolePmSite/index';

import ChangeAdd from './ChangeAdd';

const { Option } = Select;
const AddModal = props => {
  const { callBackSubmit = () => {}, visible, type, formObj, keepTableData } = 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 [chee, setChee] = useState('');
  const [isVisibleRoles, setIsVisibleRoles] = useState(false);
  const [groupName, setGroupName] = useState('角色');
  const [chooseGroupName, setChooseGroupName] = useState(['角色']);
  const [keepFiled, setKeepFiled] = useState([]);

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

  useEffect(() => {
    if (visible) {
      getRole();
      if (type === 'add') {
        setChee('否');
        form.setFieldsValue({ isSubmit: '否', docycle: '一周一次' });
        setType1('');
        setType2('');
        setFiled1({});
      } else if (type === 'edit') {
        CM_XWBPlan_DataList({ id: formObj.id }).then(res => {
          let data = res.data[0];
          data && form.setFieldsValue({ ...data });
          console.log(data.businessTypee);
          setType1(data.businessType);
          setType2(data.accountName);
        });
      }
    } else {
      setChee('');
      form.resetFields();
    }
  }, [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();
        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 pickFiled = fileds => {
    if (form.getFieldValue(fileds)) {
      setTypes('add');
      setCharacterValue(form.getFieldValue(fileds));
      setCheckedList1(form.getFieldValue(fileds).split(','));
      setPickItem(fileds);
      setIsVisible(true);
    } else {
      setTypes('add');
      setCharacterValue(form.getFieldValue(fileds));
      setCheckedList1([]);
      setPickItem(fileds);
      setIsVisible(true);
    }
  };
  const pickFiled1 = fileds => {
    if (form.getFieldValue(fileds)) {
      setTypes('app');
      setCheckedList1(form.getFieldValue(fileds).split(','));
      setPickItem(fileds);
      setIsVisibleRoles(true);
    } else {
      setTypes('app');
      setCheckedList1([]);
      setPickItem(fileds);
      setIsVisibleRoles(true);
    }
  };
  const getRole = () => {
    CM_Event_LoadDepartmentAndRoles().then(res => {
      if (res.msg === 'Ok') {
        setFiled1(formateArrDataA1(res.data, 'groupType'));
        setKeepFiled(groupArr(res.data, 'groupType'));
        setFf(filed1['角色']);
      }
    });
  };

  const groupArr = (initialArr, name) => {
    let list = {};
    initialArr.data.map(i => {
      let ar = [];
      i.root.map(j => {
        let ss = {};
        ss.label = j.Name;
        ss.value = j.ID.toString();
        ar.push(ss);
        // console.log(ss);
      });
      list[i.groupType] = ar;
    });
    return list;
  };
  const getFeedbackTable = () => {
    CM_XWBPlan_feedbackTable().then(res => {
      if (res.code === 0) {
        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 => {
    setIsVisibleRoles(false);
    let inputText = {};
    inputText[prop.pickItem] = prop.str;
    setCheckedList1(prop.stt);
    form.setFieldsValue(inputText);
  };

  const onOK1 = prop => {
    console.log(prop);
    setIsVisible(false);
    let inputText = {};
    inputText[prop.pickItem] = prop.str;
    setCheckedList1(prop.stt);
    form.setFieldsValue(inputText);
  };

  const inputType = value => {
    if (value) {
      form.setFieldsValue({ businessType: value });
    }
  };
  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={24}>
            <Item
              label="业务名称"
              name="businessName"
              labelCol={{ span: 5 }}
              rules={[
                {
                  required: true,
                  message: '请输入业务名称',
                },
                {
                  validator: (rule, value) => {
                    let aa = form.getFieldValue().businessName;
                    if (type === 'add' && keepTableData.indexOf(aa) != -1) {
                      return Promise.reject('业务名称已存在');
                    }
                    if (
                      type === 'edit' &&
                      keepTableData.indexOf(aa) != -1 &&
                      aa != formObj.businessName
                    ) {
                      return Promise.reject('业务名称已存在');
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Input placeholder="业务名称不可重复" />
            </Item>
          </Col>
          <Col span={24}>
            <Item
              label="业务类型"
              name="businessType"
              labelCol={{ span: 5 }}
              rules={[
                {
                  required: true,
                  message: '请输入业务名称',
                },
                {
                  validator: (rule, value) => {
                    if (form.getFieldsValue().businessType == '') {
                      return Promise.reject('业务类型必填');
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Select placeholder="选择业务类型" onSearch={inputType} showSearch>
                <Option value="巡检">巡检</Option>
                <Option value="保养">保养</Option>
              </Select>
            </Item>
          </Col>
          <Col span={24}>
            <Item label="执行周期" name="docycle" labelCol={{ span: 5 }}>
              <Select placeholder="选择计划执行周期">
                <Option value="一周一次">一周一次</Option>
                <Option value="半月一次">半月一次</Option>
                <Option value="一月一次">一月一次</Option>
                <Option value="季度一次">季度一次</Option>
                <Option value="半年一次">半年一次</Option>
                <Option value="一年一次">一年一次</Option>
              </Select>
            </Item>
          </Col>
          <Col span={24}>
            <Item
              label="维保设备"
              name="accountName"
              labelCol={{ span: 5 }}
              rules={[
                {
                  required: true,
                  message: '请输入业务名称',
                },
                {
                  validator: (rule, value) => {
                    if (form.getFieldsValue().accountName == '') {
                      return Promise.reject('维保设备必选');
                    }
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Select placeholder="选择此计划关联的设备台账名称" showSearch>
                {treeData
                  ? treeData.map((item, index) => (
                      <Option key={index} value={item}>
                        {item}
                      </Option>
                    ))
                  : ''}
              </Select>
            </Item>
          </Col>
          <Col span={24}>
            <Item
              label="反馈名称"
              name="feedbackName"
              labelCol={{ span: 5 }}
              rules={[
                {
                  validator: (rule, value) => {
                    if (form.getFieldValue().feedbackName == '') {
                      return Promise.reject('反馈名称必填');
                    }
                    return Promise.resolve();
                  },
                },
                {
                  required: true,
                  message: '请选择反馈名称',
                },
              ]}
            >
              <div style={{ display: 'flex' }}>
                <Item name="feedbackName" style={{ marginBottom: 0, width: '100%' }}>
                  <Input placeholder="请选择反馈名称" allowClear />
                </Item>
                <Button
                  type="dashed"
                  onClick={() => pickFiled('feedbackName')}
                  icon={<PlusOutlined style={{ marginTop: '5px' }} />}
                  style={{ marginLeft: '10px', width: '70px' }}
                />
              </div>
            </Item>
          </Col>
          <Col span={24}>
            <Item
              label="执行角色"
              name="doRole"
              labelCol={{ span: 5 }}
              rules={[
                {
                  validator: (rule, value) => {
                    if (form.getFieldValue().doRole == '') {
                      return Promise.reject('执行角色必填');
                    }
                    return Promise.resolve();
                  },
                },
                {
                  required: true,
                  message: '请选择执行角色',
                },
              ]}
            >
              <div style={{ display: 'flex' }}>
                <Item name="doRole" style={{ marginBottom: 0, width: '100%' }}>
                  <Input placeholder="请选择执行角色" allowClear />
                </Item>
                <Button
                  type="dashed"
                  onClick={() => pickFiled1('doRole')}
                  icon={<PlusOutlined style={{ marginTop: '5px' }} />}
                  style={{ marginLeft: '10px', width: '70px' }}
                />
              </div>
            </Item>
          </Col>
          <Col span={12}>
            <Item
              label={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Tooltip title="任务提前生成天数，仅适用于接口定时执行">
                    <InfoCircleOutlined
                      style={{
                        color: '#1890ff',
                        marginRight: '2px',
                      }}
                    />
                  </Tooltip>

                  <span>预生成天数</span>
                </div>
              }
              labelCol={{ span: 10 }}
              name="produceDays"
              rules={[
                {
                  required: true,
                  message: '请输入预生成天数',
                },
              ]}
            >
              <Input placeholder="请输入预生成天数" />
            </Item>
          </Col>
          <Col span={12}>
            <Item
              label="在线任务量"
              name="onLines"
              labelCol={{ span: 10 }}
              rules={[
                {
                  required: true,
                  message: '请输入在线任务量',
                },
              ]}
            >
              <Input placeholder="请输入在线任务量" />
            </Item>
          </Col>
          <Col span={24}>
            <Item label="是否送审" name="isSubmit" labelCol={{ span: 5 }}>
              <Radio.Group defaultValue={chee}>
                <Radio value="否">否</Radio>
                <Radio value="是">是</Radio>
              </Radio.Group>
            </Item>
          </Col>
          <Col span={24}>
            <Item label="SQL过滤" name="filterCondition" labelCol={{ span: 5 }}>
              <TextArea placeholder="例如：and 泵房品牌='熊猫'" />
            </Item>
          </Col>
        </Row>
      </Form>
      <ChangeAdd
        visible={isVisible}
        onCancel={() => setIsVisible(false)}
        callBackSubmit={onOK1}
        newCheckedList={checkedList1}
        isType={types}
        filed={filed}
        type={type}
        filed1={filed1}
        ff={ff}
        pickItem={pickItem}
        characterValue={characterValue}
      />
      <RMSComponents
        visible={isVisibleRoles}
        onCancel={() => setIsVisibleRoles(false)}
        callBackSubmit={onOK}
        newCheckedList={checkedList1} // 单选框中的值
        pickItem={pickItem}
        groupName={groupName} // 打开组件展示的分组名，用来首次获取数据
        chooseGroupName={chooseGroupName} // 可选分组名
        keepFiled={keepFiled}
      />
    </Drawer>
  );
};
export default AddModal;
