/* eslint-disable camelcase */
import React, { useState, useEffect } from 'react';
import { Form, Input, Select, Tooltip, Button, notification, Drawer, Space } from 'antd';
import { PlusOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { LoadEventFields } from '@/services/platform/bs';
import {
  GetCM_Ledger_LoadLedgerTable,
  GetCMLedger_QueryLedgers,
  GetCMLedger_OperateLedger,
} from '@/services/standingBook/api';
import ChangeAdd from './changeAdd';

const { Option } = Select;
const { TextArea } = Input;
const BookConfig = props => {
  const { callBackSubmit, type, formObj, visible, tableData, onCancel, maxLength } = props;
  const [standingTable, setStandingTable] = useState([]);
  const [isVisible, setIsVisible] = useState(false); // 弹窗
  const [pickItem, setPickItem] = useState(''); // 选择的字段
  const [Order, setOrder] = useState(''); // 当前编辑序号
  const [filed, setFiled] = useState({}); // 传给子组件列表数据
  const [checkedList, setCheckedList] = useState([]);
  const [allFileds, setAllFileds] = useState([]); // 当前表所有的字段
  const [form] = Form.useForm();
  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 19,
    },
  };
  const { Item } = Form;
  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        let obj =
          type === 'add'
            ? { ...validate, Order: maxLength }
            : { ...validate, Order, ID: formObj.ID };
        GetCMLedger_OperateLedger(obj)
          .then(res => {
            if (res.code === 0) {
              form.resetFields();
              callBackSubmit();
              notification.success({
                message: '提示',
                duration: 3,
                description: type === 'add' ? '新增成功' : '编辑成功',
              });
            } else {
              notification.error({
                message: '提示',
                duration: 3,
                description: res.msg,
              });
            }
          })
          .catch(() => {
            notification.error({
              message: '提示',
              duration: 3,
              description: '网络异常请稍后再试',
            });
          });
      }
    });
  };
  useEffect(() => {
    if (visible) {
      // 获取台账表
      getTableData();
      if (type === 'edit') {
        GetCMLedger_QueryLedgers({ ledgerId: formObj.ID }).then(res => {
          if (res.code === 0) {
            form.setFieldsValue(res.data.root);
            setOrder(res.data.root.Order);
            changTable(res.data.root.TableName);
          }
        });
      }
    } else {
      setFiled({});
      form.resetFields();
      form.setFieldsValue({ AccountType: '台账' });
    }
  }, [visible]);

  // 获取台账表
  const getTableData = () => {
    GetCM_Ledger_LoadLedgerTable().then(res => {
      if (res.code === 0) {
        setStandingTable(res.data.root);
      }
    });
  };
  // 切换表后数据处理为对应格式
  const changTable = value => {
    LoadEventFields({ eventTableName: value, distinctFields: '' }).then(res => {
      if (res.data.root) {
        let fileMap = new Map();
        let initList = [];
        // 处理为子组件需要的格式
        res.data.root.forEach(item => {
          initList.push(item.fieldName);
          if (fileMap.has(item.group)) {
            let list = [...fileMap.get(item.group)];
            list.push(item.fieldName);
            fileMap.set(item.group, list);
          } else {
            fileMap.set(item.group, [item.fieldName]);
          }
        });
        // 给Map格式转为对象
        fileMap = Object.fromEntries(fileMap.entries());
        // 处理外部字段
        Object.keys(form.getFieldsValue()).forEach(key => {
          saveOutFieldsLength(key, initList);
        });
        setAllFileds(initList);
        setFiled(fileMap);
      }
    });
  };
  // 保存外部字段个数
  const saveOutFieldsLength = (key, initList) => {
    switch (key) {
      case 'Fields':
        form.setFieldsValue({ outListFileds: dealExternal(key, initList) });
        break;
      case 'SearchFields':
        form.setFieldsValue({ outSearchFields: dealExternal(key, initList) });
        break;
      case 'AddFields':
        form.setFieldsValue({ outAddFields: dealExternal(key, initList) });
        break;
      case 'EditFields':
        form.setFieldsValue({ outEditFields: dealExternal(key, initList) });
        break;
      case 'WebFields':
        form.setFieldsValue({ outWebFields: dealExternal(key, initList) });
        break;
      case 'MobileFields':
        form.setFieldsValue({ outMobileFields: dealExternal(key, initList) });
        break;
      default:
        break;
    }
  };
  // 选择字段回调函数
  const onOK = prop => {
    setIsVisible(false);
    let obj = {};
    obj[prop.pickItem] = prop.str;
    form.setFieldsValue(obj);
    saveOutFieldsLength(prop.pickItem, allFileds);
  };
  // 处理外部字段
  const dealExternal = (fileds, list) => {
    let isExternal;
    let externalLength = 0;
    if (form.getFieldValue(fileds)) {
      form
        .getFieldValue(fileds)
        .split(',')
        .forEach(item => {
          isExternal = list.some(val => val === item);
          if (!isExternal && item !== '') {
            // eslint-disable-next-line no-plusplus
            externalLength++;
          }
        });
    }

    return externalLength;
  };
  // 勾选字段
  const pickFiled = fileds => {
    if (!form.getFieldValue('TableName')) {
      notification.error({ message: '提示', duration: 3, description: '请选择台账表' });
      return;
    }
    // 添加外部字段
    if (type === 'edit') {
      let fil = { ...filed };
      fil['外部字段'] = [];
      let isExternal;
      form
        .getFieldValue(fileds)
        .split(',')
        .forEach(item => {
          isExternal = allFileds.some(val => val === item);
          if (!isExternal && item !== '') {
            fil['外部字段'].push(item);
          }
        });
      if (fil['外部字段'].length === 0) {
        delete fil['外部字段'];
      }
      setFiled(fil);
      setCheckedList(form.getFieldValue(fileds).split(','));
    }
    setPickItem(fileds);
    setIsVisible(true);
  };
  // 搜索框监听
  const onSearch = value => {
    if (value) {
      form.setFieldsValue({ Type: value });
    }
  };
  return (
    <Drawer
      title={`${type === 'add' ? '台账配置' : '台账编辑'}`}
      width="500px"
      visible={visible}
      onClose={onCancel}
      destroyOnClose
      footer={
        <Space>
          <Button onClick={onCancel}>取消</Button>
          <Button onClick={onSubmit} type="primary">
            确定
          </Button>
        </Space>
      }
    >
      <Form form={form} {...layout}>
        <Item label="分组" name="Type" rules={[{ required: true, message: '请选择分组' }]}>
          <Select
            showSearch
            filterOption={false}
            onSearch={onSearch}
            placeholder="请输入分组名称"
            allowClear
          >
            {tableData.map((item, index) => (
              <Option value={item} key={index}>
                {item}
              </Option>
            ))}
          </Select>
        </Item>
        <Item label="台账类型" name="AccountType">
          <Select placeholder="请选择台账类型">
            <Option value="台账">台账</Option>
            <Option value="反馈">反馈</Option>
            <Option value="设备">设备</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.map((item, index) => (
              <Option key={index} value={item.value}>
                {item.text}
              </Option>
            ))}
          </Select>
        </Item>
        <Item
          label={
            <>
              {form.getFieldValue('outListFileds') > 0 ? (
                <Tooltip title={`外部字段${form.getFieldValue('outListFileds')}个`}>
                  <InfoCircleOutlined style={{ color: 'red', margin: '2px 3px 0 3px' }} />
                </Tooltip>
              ) : (
                ''
              )}
              <span>台账字段</span>
            </>
          }
          name="Fields"
        >
          <div style={{ display: 'flex' }}>
            <Form.Item name="Fields" style={{ marginBottom: 0, width: '100%' }}>
              <TextArea placeholder="前端详情查看字段" allowClear />
            </Form.Item>
            <Button
              type="dashed"
              style={{ height: '54px', width: '50px', marginLeft: '10px' }}
              icon={<PlusOutlined />}
              onClick={() => {
                pickFiled('Fields');
              }}
            />
          </div>
        </Item>
        <Item
          label={
            <>
              {form.getFieldValue('outSearchFields') > 0 ? (
                <Tooltip title={`外部字段${form.getFieldValue('outSearchFields')}个`}>
                  <InfoCircleOutlined style={{ color: 'red', margin: '2px 3px 0 3px' }} />
                </Tooltip>
              ) : (
                ''
              )}
              <span>检索字段</span>
            </>
          }
          name="SearchFields"
        >
          <div style={{ display: 'flex' }}>
            <Form.Item name="SearchFields" style={{ marginBottom: 0, width: '100%' }}>
              <TextArea placeholder="前端列表检索字段" allowClear />
            </Form.Item>
            <Button
              type="dashed"
              style={{ height: '54px', width: '50px', marginLeft: '10px' }}
              icon={<PlusOutlined />}
              onClick={() => {
                pickFiled('SearchFields');
              }}
            />
          </div>
        </Item>
        <Item
          label={
            <>
              {form.getFieldValue('outAddFields') > 0 ? (
                <Tooltip title={`外部字段${form.getFieldValue('outAddFields')}个`}>
                  <InfoCircleOutlined style={{ color: 'red', margin: '2px 3px 0 3px' }} />
                </Tooltip>
              ) : (
                ''
              )}
              <span>添加字段</span>
            </>
          }
          name="AddFields"
        >
          <div style={{ display: 'flex' }}>
            <Form.Item name="AddFields" style={{ marginBottom: 0, width: '100%' }}>
              <TextArea placeholder="前端数据添加字段" allowClear />
            </Form.Item>
            <Button
              type="dashed"
              style={{ height: '54px', width: '50px', marginLeft: '10px' }}
              icon={<PlusOutlined />}
              onClick={() => {
                pickFiled('AddFields');
              }}
            />
          </div>
        </Item>
        <Item
          label={
            <>
              {form.getFieldValue('outEditFields') > 0 ? (
                <Tooltip title={`外部字段${form.getFieldValue('outEditFields')}个`}>
                  <InfoCircleOutlined style={{ color: 'red', margin: '2px 3px 0 3px' }} />
                </Tooltip>
              ) : (
                ''
              )}
              <span>编辑字段</span>
            </>
          }
          name="EditFields"
        >
          <div style={{ display: 'flex' }}>
            <Form.Item name="EditFields" style={{ marginBottom: 0, width: '100%' }}>
              <TextArea placeholder="前端可编辑字段" allowClear />
            </Form.Item>
            <Button
              type="dashed"
              style={{ height: '54px', width: '50px', marginLeft: '10px' }}
              icon={<PlusOutlined />}
              onClick={() => {
                pickFiled('EditFields');
              }}
            />
          </div>
        </Item>
        <Item
          label={
            <>
              {form.getFieldValue('outWebFields') > 0 ? (
                <Tooltip title={`外部字段${form.getFieldValue('outWebFields')}个`}>
                  <InfoCircleOutlined style={{ color: 'red', margin: '2px 3px 0 3px' }} />
                </Tooltip>
              ) : (
                ''
              )}
              <span>前端字段</span>
            </>
          }
          name="WebFields"
        >
          <div style={{ display: 'flex' }}>
            <Form.Item name="WebFields" style={{ marginBottom: 0, width: '100%' }}>
              <TextArea placeholder="前端列表展示字段" allowClear />
            </Form.Item>
            <Button
              type="dashed"
              style={{ height: '54px', width: '50px', marginLeft: '10px' }}
              icon={<PlusOutlined />}
              onClick={() => {
                pickFiled('WebFields');
              }}
            />
          </div>
        </Item>
        <Item
          label={
            <>
              {form.getFieldValue('outMobileFields') > 0 ? (
                <Tooltip title={`外部字段${form.getFieldValue('outMobileFields')}个`}>
                  <InfoCircleOutlined style={{ color: 'red', margin: '2px 3px 0 3px' }} />
                </Tooltip>
              ) : (
                ''
              )}
              <span>手持字段</span>
            </>
          }
          name="MobileFields"
        >
          <div style={{ display: 'flex' }}>
            <Form.Item name="MobileFields" style={{ marginBottom: 0, width: '100%' }}>
              <TextArea placeholder="手持展示字段" allowClear />
            </Form.Item>
            <Button
              type="dashed"
              style={{ height: '54px', width: '50px', marginLeft: '10px' }}
              icon={<PlusOutlined />}
              onClick={() => {
                pickFiled('MobileFields');
              }}
            />
          </div>
        </Item>
        <Item label="接口配置" name="Interface">
          <Input placeholder="服务项目dll库" allowClear />
        </Item>
      </Form>
      <ChangeAdd
        visible={isVisible}
        onCancel={() => setIsVisible(false)}
        callBackSubmit={onOK}
        newCheckedList={checkedList}
        filed={filed}
        pickItem={pickItem}
        formObj={formObj}
      />
    </Drawer>
  );
};
export default BookConfig;
