/* eslint-disable indent */
/* eslint-disable react/jsx-no-duplicate-props */
/* eslint-disable no-shadow */
/* eslint-disable no-undef */
/* eslint-disable eqeqeq */
/* eslint-disable array-callback-return */
/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
/* eslint-disable camelcase */
import React, { useState, useEffect } from 'react';
import {
  Modal,
  Form,
  Input,
  notification,
  message,
  Row,
  Col,
  Select,
  Drawer,
  Space,
  Button,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import ChangeAddFlows from './ChangeAddFlows';
import {
  CM_Event_ReloadFlows,
  CM_Event_LoadDepartmentAndRoles,
  CM_Event_AddEvenFlow,
  CM_Event_EditEvenFlow,
} from '@/services/standingBook/api';
import styles from './incident.less';

const { Option } = Select;
const AddFlowsModal = props => {
  const {
    callBackSubmit = () => {},
    type,
    visible,
    onClose,
    formObj,
    obj,
    maxLength,
    record,
  } = props;
  const [form] = Form.useForm();
  const { Item } = Form;

  const [filed1, setFiled1] = useState({}); // 传给子组件列表数据
  const [standingTable, setStandingTable] = useState([]);
  const [visible1, setVisible1] = useState(false);
  const [pickItem, setPickItem] = useState('');
  const [checkedList1, setCheckedList1] = useState([]);
  const [nu1, setNu1] = useState([]);
  const [inputValue, setInputValue] = useState({ Roles: '' });
  const [selectValue, setSelectValue] = useState('');
  const [characterValue, setCharacterValue] = useState('');
  const [Order, setOrder] = useState(''); // 弹窗类型
  const [strr, setStrr] = useState('');

  useEffect(() => {
    console.log(formObj);
    getRole();
    console.log(obj);
    CM_Event_ReloadFlows({ eventTypeId: obj }).then(res => {
      if (res.msg === 'Ok') {
        console.log(res.data);
        let arr = formateArrDataA(res.data, 'System');
        let newArr = [];
        Object.keys(arr).map((item, index) => {
          newArr.push(item);
        });
        console.log(newArr);
        setStandingTable(newArr);
      }
    });
    if (type === 'add') {
      setInputValue({ Roles: '' });
      setFiled1({});
      form.resetFields();
    } else if (type === 'edit') {
      setStrr(record.FlowRoles);
      console.log(record);
      setInputValue({
        Roles: record.FlowRoles,
      });
      setSelectValue(record.FlowName);
      console.log(selectValue);
    }
  }, [visible]);
  const formateArrDataA = (initialArr, name) => {
    // 判定传参是否符合规则
    if (!(initialArr instanceof Array)) {
      return '请传入正确格式的数组';
    }
    if (!name) {
      return '请传入对象属性';
    }
    // 先获取一下这个数组中有多少个"name"
    let nameArr = [];
    for (let i in initialArr) {
      if (nameArr.indexOf(initialArr[i][`${name}`]) === -1) {
        nameArr.push(initialArr[i][`${name}`]);
      }
    }
    // 新建一个包含多个list的结果对象
    let tempObj = {};
    // 根据不同的"name"生成多个数组
    for (let k in nameArr) {
      for (let j in initialArr) {
        if (initialArr[j][`${name}`] == nameArr[k]) {
          // 每次外循环时新建一个对应"name"的数组, 内循环时当前数组不变
          tempObj[nameArr[k]] = tempObj[nameArr[k]] || [];
          tempObj[nameArr[k]].push(initialArr[j]);
        }
      }
    }
    for (let keys in tempObj) {
      let arr = [];
      tempObj[keys].map((item, index) => {
        tempObj[keys] = arr;
        item.key = index;
        arr.push(item);
      });
    }
    return tempObj;
  };
  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 onSumbit = () => {
    callBackSubmit();
    // setLoading(true);
    let aa = form.getFieldsValue().FlowName;
    console.log(aa);
    console.log(inputValue);
    console.log(strr);
    if (type == 'add') {
      let index = aa.lastIndexOf('\\');
      aa = aa.substring(index + 1, aa.length);
      CM_Event_AddEvenFlow({
        eventTypeId: formObj.ID,
        flowName: aa,
        roles: inputValue.Roles,
        order: maxLength,
      })
        .then(res => {
          // setLoading(false);
          if (res.msg === 'Ok') {
            form.resetFields();
            callBackSubmit();
            notification.success({
              message: '提示',
              duration: 3,
              description: '新增成功',
            });
          } else {
            notification.error({
              message: '提示',
              duration: 3,
              description: res.msg,
            });
          }
        })
        .catch(error => {
          notification.error({
            message: '提示',
            duration: 3,
            description: '新增失败',
          });
          // setLoading(false);
        });
    }
    if (type == 'edit') {
      CM_Event_EditEvenFlow({
        eventTypeId: formObj.ID,
        eventFlowId: record.ID,
        roles: inputValue.Roles,
      })
        .then(res => {
          // setLoading(false);
          if (res.msg === '') {
            form.resetFields();
            callBackSubmit();
            notification.success({
              message: '提示',
              duration: 3,
              description: '编辑成功',
            });
          } else {
            notification.error({
              message: '提示',
              duration: 3,
              description: res.msg,
            });
          }
        })
        .catch(error => {
          notification.error({
            message: '提示',
            duration: 3,
            description: '编辑失败',
          });
          // setLoading(false);
        });
    }
  };

  const getRole = () => {
    CM_Event_LoadDepartmentAndRoles().then(res => {
      if (res.msg === 'Ok') {
        setNu1(res.data);
        setFiled1(formateArrDataA1(res.data, 'groupType'));
        console.log(res.data);
      }
    });
  };
  const changeText = (e, type) => {
    let inputText = { ...inputValue };
    inputText[type] = e.target.value;
    setInputValue(inputText);
  };
  const pickFiled1 = fileds => {
    // setTypes('app')
    let pp = formateArrDataA1(nu1, 'group');
    let ab = inputValue[fileds].split(',');
    console.log(pp);
    let arr = Object.keys(pp);
    let b = [];
    let a = [];
    arr.map((item, index) => {
      pp[item].map((i, j) => {
        b.push(i);
      });
    });
    console.log(ab);
    ab.map((item, index) => {
      if (b.includes(item) == false) {
        if (item == '') {
          a = [];
        } else {
          a.push(item);
        }
      }
    });
    // if (a.length > 0) {
    //   pp.外部字段 = a;
    //   console.log(pp);
    //   arr.push('外部字段');
    // }
    console.log(a);
    console.log(pp);
    setFiled1(pp);
    console.log(fileds);
    setCharacterValue(inputValue[fileds]);
    setCheckedList1(inputValue[fileds].split(','));
    setPickItem(fileds);
    setVisible1(true);
  };
  const onOKk = prop => {
    // let { title } = prop;
    // let selectData = prop.stt;
    // let ff = prop.filed22;
    // let aa = [];
    // let bb = 0;
    // title.map((item, index) => {
    //   console.log(ff[item]);
    //   aa = [];
    //   selectData.map((item1, index1) => {
    //     console.log(item1);
    //     if (ff[item].indexOf(item1) != -1) {
    //       aa.push(item1);
    //     }
    //   });
    //   console.log(aa);
    //   if (aa.length == 0) {
    //     bb = 1;
    //   }
    // });
    // console.log(aa);
    // if (bb == 1) {
    //   notification.error({
    //     message: '提示',
    //     description: '权限角色部门必须都选至少一项',
    //   });
    // } else {
    //   setVisible1(false);
    //   let inputText = { ...inputValue };
    //   inputText[prop.pickItem] = prop.str;
    //   console.log(prop.str);
    //   console.log(inputText);
    //   setStrr(prop.str);
    //   setCheckedList1(prop.checkedList);
    //   setInputValue(inputText);
    // }
    setVisible1(false);
    let inputText = { ...inputValue };
    inputText[prop.pickItem] = prop.str;
    console.log(prop.str);
    console.log(inputText);
    setStrr(prop.str);
    setCheckedList1(prop.stt);
    setInputValue(inputText);
  };
  return (
    <Drawer
      title={type === 'add' ? '添加受理流程' : '编辑受理流程'}
      visible={visible}
      width="500px"
      onClose={onClose}
      destroyOnClose
      footer={
        <Space>
          <Button onClick={onSumbit} type="primary">
            确定
          </Button>
        </Space>
      }
    >
      <Form form={form} labelCol={{ span: 7 }} style={{ overflowY: 'scroll' }}>
        <Row>
          <Col span={24}>
            {type === 'edit' ? (
              <>
                <Item label="受理流程" name="FlowName" labelCol={{ span: 4 }}>
                  <Select placeholder="选择受理流程" placeholder={selectValue} disabled>
                    {standingTable
                      ? standingTable.map((item, index) => (
                          <Option key={index} value={item}>
                            {item}
                          </Option>
                        ))
                      : ''}
                  </Select>
                </Item>
              </>
            ) : (
              <>
                <Item label="受理流程" name="FlowName" labelCol={{ span: 4 }}>
                  <Select placeholder="选择受理流程">
                    {standingTable
                      ? standingTable.map((item, index) => (
                          <Option key={index} value={item}>
                            {item}
                          </Option>
                        ))
                      : ''}
                  </Select>
                </Item>
              </>
            )}
          </Col>
          <Col span={24}>
            <Item label="受理权限" name="Roles" labelCol={{ span: 4 }}>
              <div className={styles.filed_listItem}>
                <Input
                  style={{ width: '83%' }}
                  placeholder="请选择受理权限"
                  onChange={e => changeText(e, 'Roles')}
                  value={inputValue.Roles}
                  allowClear
                />
                <Button
                  type="dashed"
                  onClick={() => pickFiled1('Roles')}
                  icon={<PlusOutlined style={{ marginTop: '5px' }} />}
                  style={{ marginLeft: '5px', width: '58px' }}
                />
              </div>
            </Item>
          </Col>
        </Row>
      </Form>
      <ChangeAddFlows
        visible={visible1}
        onCancel={() => setVisible1(false)}
        callBackSubmit={onOKk}
        newCheckedList={checkedList1}
        filed11={filed1}
        pickItem={pickItem}
        characterValue={characterValue}
        formObj={formObj}
      />
    </Drawer>
  );
};
export default AddFlowsModal;