/* 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,
  Tooltip,
} from 'antd';
import { PlusOutlined, InfoCircleOutlined } from '@ant-design/icons';
import ChangeAddFlows from './ChangeAddFlows';
import RMSComponents from '@/components/RolePmSite/index';
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 { TextArea } = Input;
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 [strr, setStrr] = useState('');
  const [groupName, setGroupName] = useState('角色');
  const [chooseGroupName, setChooseGroupName] = useState(['角色', '部门', '站点']);
  const [keepFiled, setKeepFiled] = useState([]);

  useEffect(() => {
    getRole();
    CM_Event_ReloadFlows({ eventTypeId: obj }).then(res => {
      if (res.code === 0) {
        res.data.forEach(item => {
          item.System = item.System.split('\\')[0];
        });
        console.log(res.data);
        let arr = formateArrDataA(res.data, 'System');

        console.log(arr, 'arr');
        let newArr = Object.keys(arr).map((item, index) => {
          // newArr.push(item);
          arr[item].sort((a, b) => b.IsOptional - a.IsOptional);
          return {
            label: item,
            options: arr[item].map(ele => ({
              label: ele.FlowName,
              value: ele.FlowName,
              disabled: !ele.IsOptional,
            })),
          };
        });
        // Object.keys(arr).map((item, index) => {
        //   newArr.push(arr[item]);
        // });
        console.log(newArr, 'newArr');
        setStandingTable(newArr);
      }
    });
    if (type === 'add') {
      setInputValue({ Roles: '' });
      setFiled1({});
      form.resetFields();
    } else if (type === 'edit') {
      setStrr(record.FlowRoles);
      setInputValue({
        Roles: record.FlowRoles,
      });
      setSelectValue(record.FlowName);
    }
  }, [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'));
        setKeepFiled(groupArr(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);
    setKeepFiled(groupArr(nu1, 'group'));
    // setFiled1(pp);
    console.log(fileds);
    setCharacterValue(inputValue[fileds]);
    setCheckedList1(inputValue[fileds].split(','));
    setPickItem(fileds);
    setVisible1(true);
  };

  const groupArr = (initialArr, name) => {
    let list = {};
    console.log(initialArr);
    initialArr.data.map(i => {
      console.log(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;
    });
    console.log(list);
    return list;
  };
  const onOKk = prop => {
    setVisible1(false);
    let inputText = { ...inputValue };
    inputText[prop.pickItem] = prop.str;
    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}>
            <Item
              label={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Tooltip title="若存在不可用流程，请检查流程配置">
                    <InfoCircleOutlined
                      style={{
                        color: '#1890ff',
                      }}
                    />
                  </Tooltip>
                  <span>受理流程</span>
                </div>
              }
              name="FlowName"
              labelCol={{ span: 5 }}
            >
              <Select
                options={standingTable}
                placeholder="选择受理流程"
                disabled={type === 'edit'}
              />
            </Item>
          </Col>
          {/* <Col span={24}>
            <Item label="受理权限" name="Roles" labelCol={{ span: 5 }}>
              <div style={{ display: 'flex', alignContent: 'flex-start' }}>
                <TextArea
                  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', height: '54px' }}
                />
              </div>
            </Item>
          </Col> */}
        </Row>
      </Form>
      {/* <ChangeAddFlows
        visible={visible1}
        onCancel={() => setVisible1(false)}
        callBackSubmit={onOKk}
        newCheckedList={checkedList1}
        filed11={filed1}
        pickItem={pickItem}
      /> */}
      <RMSComponents
        visible={visible1}
        onCancel={() => setVisible1(false)}
        callBackSubmit={onOKk}
        newCheckedList={checkedList1} // 单选框中的值
        pickItem={pickItem}
        groupName={groupName} // 打开组件展示的分组名，用来首次获取数据
        chooseGroupName={chooseGroupName} // 可选分组名
        keepFiled={keepFiled}
        dataType="name"
      />
    </Drawer>
  );
};
export default AddFlowsModal;
