/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
import React, { useState, useEffect } from 'react';
import {
  Form,
  Modal,
  Input,
  Select,
  Tooltip,
  Button,
  notification,
  Image,
  Menu,
  Dropdown,
  Drawer,
  Space,
} from 'antd';
import {
  PlusOutlined,
  InfoCircleOutlined,
  DownOutlined,
} from '@ant-design/icons';
import { LoadEventFields } from '@/services/platform/bs';
import add from '@/assets/images/thumbnail/add.jpg';
import editor from '@/assets/images/thumbnail/editor.jpg';
import hand from '@/assets/images/thumbnail/hand.png';
import search from '@/assets/images/thumbnail/search.jpg';
import taizhang from '@/assets/images/thumbnail/taizhang.jpg';
import web from '@/assets/images/thumbnail/web.jpg';
import {
  GetCM_Ledger_LoadLedgerTable,
  GetCMLedger_QueryLedgers,
  GetCMLedger_OperateLedger,
} from '@/services/standingBook/api';
import styles from './standingBook.less';
import ChangeAdd from './changeAdd';
import { orderBy } from 'lodash';
const { Option } = Select;
const { TextArea } = Input;
const AddModal = props => {
  const {
    callBackSubmit = () => {},
    type,
    formObj,
    visible,
    tableData,
    maxLength,
    onCancel,
  } = props;
  const [standingTable, setStandingTable] = useState([]);
  const [inputValue, setInputVaule] = useState({
    Fields: '',
    EditFields: '',
    AddFields: '',
    MobileFields: '',
    SearchFields: '',
    WebFields: '',
  });
  const [isVisible, setIsVisible] = useState(false); // 弹窗
  const [loading, setLoading] = useState(false);
  const [pickItem, setPickItem] = useState('');
  const [filed, setFiled] = useState({}); // 传给子组件列表数据
  const [types, setTypes] = useState(''); // 弹窗类型
  const [Order, setOrder] = useState(''); // 弹窗类型
  const [checkedList, setCheckedList] = useState([]);
  const [Type, setType] = useState('');
  const [characterValue, setCharacterValue] = useState('');
  const [standingType, setStandingType] = useState(['台账', '反馈', '设备']);
  const [allFileds, setAllFileds] = useState([]); // 当前表所有的字段
  const [form] = Form.useForm();
  const { Item } = Form;
  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setLoading(true);
        let obj = form.getFieldsValue();
        let data =
          type == 'add'
            ? { ...obj, ...inputValue, Order: maxLength }
            : { ...obj, Order, ID: formObj.ID };
        GetCMLedger_OperateLedger(data)
          .then(res => {
            setLoading(false);
            if (res.msg === '') {
              form.resetFields();
              callBackSubmit();
              notification.success({
                message: '提示',
                duration: 3,
                description: type == 'add' ? '新增成功' : '编辑成功',
              });
            } else {
              notification.error({
                message: '提示',
                duration: 3,
                description: res.msg,
              });
            }
          })
          .catch(err => {
            notification.error({
              message: '提示',
              duration: 3,
              description: '新增失败',
            });
            setLoading(false);
          });
      }
    });
  };

  const onFinish = value => {};
  useEffect(() => {
    getTableData();
    if (type === 'edit') {
      GetCMLedger_QueryLedgers({ ledgerId: formObj.ID }).then(res => {
        res.data.root && form.setFieldsValue({ ...res.data.root });
        setInputVaule({ ...res.data.root });
        setOrder(res.data.root.Order);
        setType(res.data.root.Type);
        changTable(res.data.root.TableName);
      });
    } else if (type === 'add') {
      setInputVaule({
        Fields: '',
        EditFields: '',
        AddFields: '',
        MobileFields: '',
        SearchFields: '',
        WebFields: '',
      });
      setFiled({});
      form.resetFields();
      form.setFieldsValue({ AccountType: '台账' });
    }
  }, [visible]);

  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 19,
    },
  };
  const getTableData = () => {
    setType('');
    GetCM_Ledger_LoadLedgerTable().then(res => {
      if (res.msg === 'Ok') {
        setStandingTable(res.data.root);
      }
    });
  };
  const changTable = value => {
    LoadEventFields({ eventTableName: value, distinctFields: '' }).then(res => {
      if (res.data.root && res.data.root.length) {
        setFiled(formateArrDataA(res.data.root, 'group'));
      }
    });
  };

  const formateArrDataA = (initialArr, name) => {
    // 判定传参是否符合规则
    if (!(initialArr instanceof Array)) {
      return '请传入正确格式的数组';
    }
    if (!name) {
      return '请传入对象属性';
    }
    // 先获取一下这个数组中有多少个"name"
    let nameArr = [];
    let allFile = [];
    for (let i in initialArr) {
      allFile.push(initialArr[i].fieldName);
      if (nameArr.indexOf(initialArr[i][`${name}`]) === -1) {
        nameArr.push(initialArr[i][`${name}`]);
      }
    }
    // 保存所有的字段用来比较是否有外部字段
    setAllFileds(allFile);
    // 新建一个包含多个list的结果对象
    let tempObj = {};
    // 根据不同的"name"生成多个数组
    console.log(initialArr);
    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]);
        }
      }
    }
    console.log(tempObj);
    for (let key in tempObj) {
      let arr = [];
      tempObj[key].map(item => {
        tempObj[key] = arr;
        arr.push(item.fieldName);
      });
    }
    return tempObj;
  };
  const onOK = prop => {
    setIsVisible(false);
    let inputText = { ...inputValue };
    inputText[prop.pickItem] = prop.str;
    setCheckedList(prop.checkedList);
    setInputVaule(inputText);
  };
  const pickFiled = fileds => {
    // 添加外部字段
    let fil = { ...filed };
    fil['外部字段'] = [];
    let isExternal;
    inputValue[fileds].split(',').forEach(item => {
      isExternal = allFileds.some(val => val === item);
      if (!isExternal && item !== '') {
        fil['外部字段'].push(item);
      }
    });
    if (fil['外部字段'].length === 0) {
      delete fil['外部字段'];
    }

    setFiled(fil);

    setTypes('add');
    setCharacterValue(inputValue[fileds]);
    setCheckedList(inputValue[fileds].split(','));

    setPickItem(fileds);
    setIsVisible(true);
  };
  const changeText = (e, type) => {
    let inputText = { ...inputValue };
    inputText[type] = e.target.value;
    console.log(inputText, '32555');
    setInputVaule(inputText);
  };
  const inputType = e => {
    e.persist();
    console.log(e.target.value, 'value');
    setType(e.target.value);
    form.setFieldsValue({ Type: e.target.value });
  };

  return (
    <Drawer
      title={`${type === 'add' ? '台账配置' : '台账编辑'}`}
      width="500px"
      visible={visible}
      onClose={onCancel}
      footer={
        <Space>
          <Button onClick={onCancel}>取消</Button>
          <Button onClick={onSubmit} type="primary">
            确定
          </Button>
        </Space>
      }
    >
      {visible && (
        <div className={styles.formData}>
          <Form form={form} {...layout} onFinish={onFinish}>
            <Item
              label="分组"
              name="Type"
              rules={[{ required: true, message: '请选择分组' }]}
            >
              <div>
                <Input
                  className="ue-editable-select-input"
                  onChange={e => inputType(e)}
                  value={Type}
                />
                <Dropdown
                  placement="bottomRight"
                  style={{ width: '20rem' }}
                  overlay={
                    <Menu>
                      {tableData.length
                        ? tableData.map((item, index) => {
                            return (
                              <Menu.Item
                                onClick={() => {
                                  setType(item);
                                  form.setFieldsValue({ Type: item });
                                }}
                                style={{ width: '26.6rem' }}
                                key={index}
                              >
                                {item}
                              </Menu.Item>
                            );
                          })
                        : ''}
                    </Menu>
                  }
                >
                  <div
                    className={styles.linkDrowp}
                    onClick={e => e.preventDefault()}
                  >
                    <DownOutlined
                      style={{ fontSize: '12px', color: 'rgba(0, 0, 0, 0.25)' }}
                    />
                  </div>
                </Dropdown>
                {/* {tableData.length ? tableData.map((item, index) => { return <Option key={index} value={item}>{item}</Option> }) : ''} */}
              </div>
            </Item>
            <Item label="台账类型" name="AccountType">
              <Select placeholder="选择台账类型">
                {standingType.length
                  ? standingType.map((item, index) => {
                      return (
                        <Option key={index} value={item}>
                          {item}
                        </Option>
                      );
                    })
                  : ''}
              </Select>
            </Item>
            <Item
              label="台账名称"
              name="Name"
              rules={[{ required: true, message: '请输入台账名称' }]}
            >
              <Input placeholder="台账名称不可重复" allowClear />
            </Item>

            <Item
              label="台账表"
              name="TableName"
              rules={[{ required: true, message: '请选择台账表' }]}
            >
              <Select
                placeholder=""
                optionFilterProp="children"
                onChange={changTable}
              >
                {standingTable.length
                  ? standingTable.map((item, index) => {
                      return (
                        <Option key={index} value={item.value}>
                          {item.text}
                        </Option>
                      );
                    })
                  : ''}
              </Select>
            </Item>
            <Item
              label={
                <div className={styles.formData_label}>
                  <Tooltip title={<Image width={200} src={taizhang} />}>
                    <InfoCircleOutlined
                      style={{ color: '#1890FF', padding: '0.2rem 0.2rem 0 0' }}
                    />
                  </Tooltip>
                  <span>台账字段</span>{' '}
                </div>
              }
              name="Fields"
            >
              <div className={styles.filed_listItem}>
                <TextArea
                  placeholder="前端详情查看字段"
                  onChange={e => changeText(e, 'Fields')}
                  value={inputValue.Fields}
                  allowClear
                />
                <Button
                  type="dashed"
                  onClick={() => pickFiled('Fields')}
                  icon={<PlusOutlined />}
                  style={{
                    marginLeft: '0.5rem',
                    height: '100%',
                    width: '3.5rem',
                  }}
                />
              </div>
            </Item>
            <Item
              label={
                <div className={styles.formData_label}>
                  {' '}
                  <Tooltip title={<Image width={200} src={search} />}>
                    <InfoCircleOutlined
                      style={{ color: '#1890FF', padding: '0.2rem 0.2rem 0 0' }}
                    />
                  </Tooltip>
                  <span>检索字段</span>{' '}
                </div>
              }
              name="SearchFields"
            >
              <div className={styles.filed_listItem}>
                <TextArea
                  placeholder="前端列表检索字段"
                  onChange={e => changeText(e, 'SearchFields')}
                  value={inputValue.SearchFields}
                  allowClear
                />
                <Button
                  type="dashed"
                  onClick={() => pickFiled('SearchFields')}
                  icon={<PlusOutlined />}
                  style={{
                    marginLeft: '0.5rem',
                    height: '100%',
                    width: '3.5rem',
                  }}
                />
              </div>
            </Item>
            <Item
              label={
                <div className={styles.formData_label}>
                  {' '}
                  <Tooltip title={<Image width={200} src={add} />}>
                    <InfoCircleOutlined
                      style={{ color: '#1890FF', padding: '0.2rem 0.2rem 0 0' }}
                    />
                  </Tooltip>
                  <span>添加字段</span>{' '}
                </div>
              }
              name="AddFields"
            >
              <div className={styles.filed_listItem}>
                <TextArea
                  placeholder="前端数据添加字段"
                  onChange={e => changeText(e, 'AddFields')}
                  value={inputValue.AddFields}
                  allowClear
                />
                <Button
                  type="dashed"
                  onClick={() => pickFiled('AddFields')}
                  icon={<PlusOutlined />}
                  style={{
                    marginLeft: '0.5rem',
                    height: '100%',
                    width: '3.5rem',
                  }}
                />
              </div>
            </Item>

            <Item
              label={
                <div className={styles.formData_label}>
                  <Tooltip title={<Image width={200} src={editor} />}>
                    <InfoCircleOutlined
                      style={{ color: '#1890FF', padding: '0.2rem 0.2rem 0 0' }}
                    />
                  </Tooltip>
                  <span>编辑字段</span>{' '}
                </div>
              }
              name="EditFields"
            >
              <div className={styles.filed_listItem}>
                <TextArea
                  placeholder="前端可编辑字段"
                  onChange={e => changeText(e, 'EditFields')}
                  value={inputValue.EditFields}
                  allowClear
                />
                <Button
                  type="dashed"
                  onClick={() => pickFiled('EditFields')}
                  icon={<PlusOutlined />}
                  style={{
                    marginLeft: '0.5rem',
                    height: '100%',
                    width: '3.5rem',
                  }}
                />
              </div>
            </Item>
            <Item
              label={
                <div className={styles.formData_label}>
                  <Tooltip title={<Image width={200} src={web} />}>
                    <InfoCircleOutlined
                      style={{ color: '#1890FF', padding: '0.2rem 0.2rem 0 0' }}
                    />
                  </Tooltip>
                  <span>前端字段</span>{' '}
                </div>
              }
              name="WebFields"
            >
              <div className={styles.filed_listItem}>
                <TextArea
                  placeholder="前端列表展示字段"
                  onChange={e => changeText(e, 'WebFields')}
                  value={inputValue.WebFields}
                  allowClear
                />
                <Button
                  type="dashed"
                  onClick={() => pickFiled('WebFields')}
                  icon={<PlusOutlined />}
                  style={{
                    marginLeft: '0.5rem',
                    height: '100%',
                    width: '3.5rem',
                  }}
                />
              </div>
            </Item>
            <Item
              label={
                <div className={styles.formData_label}>
                  <Tooltip title={<Image width={100} src={hand} />}>
                    <InfoCircleOutlined
                      style={{ color: '#1890FF', padding: '0.2rem 0.2rem 0 0' }}
                    />
                  </Tooltip>
                  <span>手持字段</span>{' '}
                </div>
              }
              name="MobileFields"
            >
              <div className={styles.filed_listItem}>
                <TextArea
                  placeholder="手持展示字段"
                  onChange={e => changeText(e, 'MobileFields')}
                  value={inputValue.MobileFields}
                  allowClear
                />
                <Button
                  type="dashed"
                  onClick={() => pickFiled('MobileFields')}
                  icon={<PlusOutlined />}
                  style={{
                    marginLeft: '0.5rem',
                    height: '100%',
                    width: '3.5rem',
                  }}
                />
              </div>
            </Item>
            <Item label="接口配置" name="Interface">
              <div className={styles.filed_listItem}>
                <TextArea placeholder="服务项目dll库" allowClear />
              </div>
            </Item>
          </Form>
          <ChangeAdd
            visible={isVisible}
            onCancel={() => setIsVisible(false)}
            callBackSubmit={onOK}
            newCheckedList={checkedList}
            isType={types}
            filed={filed}
            pickItem={pickItem}
            characterValue={characterValue}
            formObj={formObj}
          />
        </div>
      )}
    </Drawer>
  );
};
export default AddModal;
