import React, { useEffect, useState } from 'react';
import {
  getFlowNode,
  loadRollbackNodes,
  loadEventTypeTable,
  loadEventFields,
  loadFeedbackType,
  editFlowNodeExtend,
} from '@/services/flow/flow';

import {
  Form,
  Input,
  Radio,
  Select,
  notification,
  Checkbox,
  Button,
  message,
  Drawer,
  Space,
  Tooltip,
} from 'antd';
import { PlusOutlined, InfoCircleOutlined } from '@ant-design/icons';
import Fieldselection from './nodeEditComponents/Fieldselection';
import styles from '../flowNode.less';
const { Option } = Select;

const NodeEdit = props => {
  const { onSubumit, handleCancel, visible, msg } = props;
  const [fieldList, setFieldList] = useState([]); // 当前选择库字段列表
  const [showField, setShowField] = useState(false); // 选择字段弹窗
  const [fieldName, setFieldName] = useState(); // 编辑的字段
  const [backNodes, setBackNodes] = useState([]); // 允许返回的节点
  const [backType, setBackType] = useState([]); // 反馈类型
  const [eventTable, setEventTable] = useState([]); // 表名
  const [isDisable, setIsDisable] = useState(); // 允许回退是否可选择
  const [filedData, setFiledData] = useState([]); // 已选字段列表
  const [filedList, setFiledList] = useState([]); // 当前选择表的所有字段

  const [form] = Form.useForm();
  useEffect(() => {
    if (visible) {
      // 获取表单回显
      getFormData();
      // 获取返回步骤
      rollBackNodes();
      // 获取表名
      getTableName();
      // 获取反馈类型
      getFeedbackName();
    } else {
      form.resetFields();
    }
  }, [visible]);
  // 获取表单回显
  const getFormData = () => {
    getFlowNode({ flowNodeId: msg.ID }).then(res => {
      if (res.code === 0) {
        let obj = {
          ...res.data.Extend,
          FlowName: res.data.FlowName,
        };
        if (res.data.Extend && res.data.Extend.Rollbackable) {
          setIsDisable(false);
        } else {
          setIsDisable(true);
        }
        changTable(obj.TableName);
        form.setFieldsValue(obj);
      }
    });
  };
  // 获取反馈类型
  const getFeedbackName = () => {
    loadFeedbackType().then(res => {
      if (res.code === 0) {
        setBackType(res.data);
      }
    });
  };
  // 获取表名
  const getTableName = () => {
    loadEventTypeTable({ flowNodeId: msg.ID }).then(res => {
      if (res.code === 0) {
        setEventTable(res.data);
      }
    });
  };
  // 加载修改流程节点配置允许退回列表
  const rollBackNodes = () => {
    loadRollbackNodes({ flowNodeId: msg.ID }).then(res => {
      if (res.code === 0) {
        setBackNodes(res.data);
      }
    });
  };
  // 字段配置
  const deployField = val => {
    let value = form.getFieldsValue(true);
    if (!value.TableName) {
      message.error('请先选择表');
      return;
    }
    setFieldName(val);
    loadEventFields({ eventTableName: value.TableName }).then(res => {
      if (res.code === 0) {
        let defaultCheckedList = value[val] ? value[val].split(',') : [];

        // 保存所有的字段用于右侧显示
        setFiledData(defaultCheckedList);
        let allFields = []; // 所有得字段用来判断是否为外部字段
        // 处理树形结构
        let checkList = res.data.map(item => {
          let plainOptions = [];
          // 存入没个组得字段
          item.root.forEach(ele => {
            plainOptions = [...plainOptions, ele.fieldName];
          });
          // 存所有得字段
          allFields = [...allFields, ...plainOptions];
          return {
            groupName: item.groupName,
            plainOptions,
            defaultCheckedList: [],
          };
        });
        let externalFields = {
          groupName: '外部字段',
          indeterminate: false,
          checkAll: true,
          plainOptions: [],
          defaultCheckedList: [],
        }; // 外部字段
        defaultCheckedList.forEach(item => {
          // 添加外部字段
          let isExternal = allFields.some(checkName => checkName === item);
          if (!isExternal) {
            externalFields.plainOptions.push(item);
            externalFields.defaultCheckedList.push(item);
          }
          checkList.forEach(element => {
            // 当前得模块是否有当前字段
            let indeterminate = element.plainOptions.some(checkName => checkName === item);
            // 处理已选中的字段
            if (indeterminate) {
              element.defaultCheckedList.push(item);
            }
            if (
              element.defaultCheckedList.length > 0 &&
              element.defaultCheckedList.length < element.plainOptions.length
            ) {
              element.indeterminate = true;
            } else {
              element.indeterminate = false;
            }
            // 处理是否全选字段
            if (element.defaultCheckedList.length === element.plainOptions.length) {
              element.checkAll = true;
            } else {
              element.checkAll = false;
            }
          });
        });
        // 添加外部字段
        if (externalFields.plainOptions.length > 0) {
          checkList.push(externalFields);
        }
        setFieldList(checkList);
        setTimeout(() => {
          setShowField(true);
        }, 0);
      }
    });
  };
  // 字段修改后回调函数
  const setFiled = val => {
    let Fields = '';
    val.forEach((item, index) => {
      if (index === val.length - 1) {
        Fields = `${Fields + item}`;
      } else {
        Fields = `${Fields + item},`;
      }
    });
    let obj = {};
    obj[fieldName] = Fields;
    form.setFieldsValue(obj);
    saveOutFieldsLength(fieldName, filedList);
    setShowField(false);
  };
  // 提交表单
  const onFinish = () => {
    form.validateFields().then(validate => {
      if (validate) {
        editFlowNodeExtend({ ...validate, flowNodeId: msg.ID })
          .then(res => {
            if (res.code === 0) {
              notification.success({
                message: '提示',
                duration: 3,
                description: '编辑成功',
              });
              onSubumit();
            } else {
              notification.error({
                message: '提示',
                duration: 3,
                description: res.msg,
              });
            }
          })
          .catch(() => {
            notification.error({
              message: '提示',
              duration: 3,
              description: '网络异常',
            });
          });
      }
    });
  };
  // 表单监听
  const onValuesChange = val => {
    if (Object.keys(val)[0] === 'Rollbackable') {
      if (val.Rollbackable) {
        setIsDisable(false);
      } else {
        setIsDisable(true);
      }
    }
  };
  // 表切换
  const changTable = val => {
    loadEventFields({ eventTableName: val }).then(res => {
      if (res.code === 0) {
        let initList = [];
        res.data.forEach(item => {
          item.root.forEach(ele => {
            initList.push(ele.fieldName);
          });
        });
        // 处理外部字段
        Object.keys(form.getFieldsValue()).forEach(key => {
          saveOutFieldsLength(key, initList);
        });
        setFiledList(initList);
      }
    });
  };
  // 保存外部字段个数
  const saveOutFieldsLength = (key, initList) => {
    switch (key) {
      case 'Fields':
        form.setFieldsValue({ OutFields: dealExternal(key, initList) });
        break;
      case 'SeeFields':
        form.setFieldsValue({ OutSeeFields: dealExternal(key, initList) });
        break;
      default:
        break;
    }
  };
  // 处理外部字段
  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;
  };
  return (
    <Drawer
      title="流程节点配置"
      width="500px"
      onClose={handleCancel}
      destroyOnClose
      visible={visible}
      footer={
        <Space>
          <Button onClick={handleCancel}>取消</Button>
          <Button onClick={onFinish} type="primary">
            确定
          </Button>
        </Space>
      }
    >
      <Form
        form={form}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 18 }}
        initialValues={{ remember: true }}
        className={styles.formData}
        onValuesChange={onValuesChange}
      >
        <Form.Item label="流程节点" name="FlowName">
          <Input disabled />
        </Form.Item>
        <Form.Item label="节点别名" name="NodeAliasName">
          <Input placeholder="请输入节点别名" />
        </Form.Item>
        <Form.Item label="节点类型">
          <Form.Item name="NodeType" style={{ marginBottom: '10px' }}>
            <Select placeholder="请选择节点类型">
              <Option value="办理">办理</Option>
              <Option value="上报">上报</Option>
              <Option value="分派">分派</Option>
              <Option value="审核">审核</Option>
              <Option value="办理关单">办理关单</Option>
            </Select>
          </Form.Item>
          <Form.Item name="EditableLater" valuePropName="checked" style={{ marginBottom: 0 }}>
            <Checkbox>允许补正(事后修改)</Checkbox>
          </Form.Item>
          <div style={{ display: 'flex' }}>
            <Form.Item
              name="Rollbackable"
              valuePropName="checked"
              style={{ marginBottom: 0, width: '150px' }}
            >
              <Checkbox>允许回退至</Checkbox>
            </Form.Item>
            <Form.Item
              name="RollbackNode"
              style={{ marginBottom: 0, width: '100%' }}
              initialValue="(上一节点)"
            >
              <Select disabled={isDisable} placeholder="请选择回退节点">
                {backNodes.map(item => (
                  <Option value={item.Name} key={item.ID}>
                    {item.Name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </div>
        </Form.Item>
        <Form.Item label="移交方式" name="Handover">
          <Select>
            <Option value="移交选择人">移交选择人</Option>
            <Option value="自处理">自处理</Option>
            <Option value="自处理或者移交选择人">自处理或者移交选择人</Option>
            <Option value="移交默认人">移交默认人</Option>
            <Option value="跨站移交">跨站移交</Option>
            <Option value="处理站点移交">处理站点移交</Option>
            <Option value="本人站点移交">本人站点移交</Option>
            <Option value="移交上报人">移交上报人</Option>
          </Select>
        </Form.Item>
        <Form.Item label="平级移交" name="Transferable">
          <Radio.Group>
            <Radio value="0">否</Radio>
            <Radio value="1">是</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="显示事件信息" name="EventsInformation">
          <Radio.Group>
            <Radio value="0">否</Radio>
            <Radio value="1">是</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="是否发送短信" name="IsSendMessage">
          <Radio.Group>
            <Radio value={0}>否</Radio>
            <Radio value={1}>是</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="工单主表" name="TableName">
          <Select placeholder="请选择工单主表" onChange={changTable}>
            {eventTable.map(item => (
              <Option value={item.Name} key={item.ID}>
                {item.Name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label={
            <div className={styles.formData_label}>
              {form.getFieldValue('OutFields') ? (
                <Tooltip title={`外部字段${form.getFieldValue('OutFields')}个`}>
                  <InfoCircleOutlined style={{ color: 'red', padding: '0.2rem 0.2rem 0 0' }} />
                </Tooltip>
              ) : (
                ''
              )}
              <span>字段编辑</span>
            </div>
          }
        >
          <div className={styles.filedListItem}>
            <Form.Item name="Fields" style={{ marginBottom: 0, width: '100%' }}>
              <Input placeholder="请选编辑字段" allowClear />
            </Form.Item>
            <Button
              type="dashed"
              icon={<PlusOutlined />}
              onClick={() => {
                deployField('Fields');
              }}
            />
          </div>
        </Form.Item>
        <Form.Item
          label={
            <div className={styles.formData_label}>
              {form.getFieldValue('OutSeeFields') ? (
                <Tooltip title={`外部字段${form.getFieldValue('OutSeeFields')}个`}>
                  <InfoCircleOutlined style={{ color: 'red', padding: '0.2rem 0.2rem 0 0' }} />
                </Tooltip>
              ) : (
                ''
              )}
              <span>查看字段</span>
            </div>
          }
        >
          <div className={styles.filedListItem}>
            <Form.Item name="SeeFields" style={{ marginBottom: 0, width: '100%' }}>
              <Input placeholder="请选择查看字段（工程模型）" allowClear />
            </Form.Item>
            <Button
              type="dashed"
              icon={<PlusOutlined />}
              onClick={() => {
                deployField('SeeFields');
              }}
            />
          </div>
        </Form.Item>
        <Form.Item label="前端视图" name="WebPage">
          <Input placeholder="请配置前端视图" />
        </Form.Item>
        <Form.Item label="手持视图" name="MobilePage">
          <Input placeholder="请配置手持视图" />
        </Form.Item>
        <Form.Item label="视图参数" name="PageParam">
          <Input placeholder="请配置视图参数" />
        </Form.Item>
        <Form.Item label="反馈类型" name="FeedbackName">
          <Select placeholder="请选择反馈类型" allowClear>
            {backType.map(item => (
              <Option value={item.value} key={item.value}>
                {item.value}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          name="FeedbackToEvent"
          valuePropName="checked"
          wrapperCol={{ offset: 5, span: 18 }}
        >
          <Checkbox>将反馈信息显示到事件级别</Checkbox>
        </Form.Item>
      </Form>
      {/* 字段集选择 */}
      <Fieldselection
        visible={showField}
        handleCancel={() => setShowField(false)}
        fieldList={fieldList}
        onSubumit={val => setFiled(val)}
        filedData={filedData}
      />
    </Drawer>
  );
};
export default NodeEdit;
