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,
  Switch,
  Row,
  Col,
} 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, allDisabled } = 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 [visibleChecked, setVisibleChecked] = useState('');
  const [visibleChecked1, setVisibleChecked1] = useState('');
  const [visibleChecked2, setVisibleChecked2] = useState('');
  const [visibleChecked3, setVisibleChecked3] = useState('');
  const [visibleChecked5, setVisibleChecked5] = useState('');
  const [visibleChecked6, setVisibleChecked6] = useState('');
  const [autoClose, setAutoClose] = useState(false);
  const [transfer, setTransfer] = useState(false);
  const [half, setHalf] = useState(false);

  const [form] = Form.useForm();
  useEffect(() => {
    if (visible) {
      // 获取表单回显
      getFormData();
      // 获取返回步骤
      rollBackNodes();
      // 获取表名
      getTableName();
      // 获取反馈类型
      getFeedbackName();
    } else {
      form.resetFields();
      setVisibleChecked(false);
      setVisibleChecked1(false);
      setVisibleChecked2(false);
      setVisibleChecked3(false);
      setVisibleChecked5(false);
      setVisibleChecked6(false);
      setTransfer(false);
    }
  }, [visible]);
  // 获取表单回显
  const getFormData = () => {
    getFlowNode({ flowNodeId: msg.ID }).then(res => {
      if (res.code === 0) {
        // 结束节点
        if (res.data.Type == 2) {
          if (res.data.Extend && res.data.Extend.AutoClose === '是') {
            res.data.Extend.AutoClose = true;
            setVisibleChecked3(true);
          } else if (res.data.Extend && res.data.Extend.AutoClose === '否') {
            res.data.Extend.AutoClose = false;
            setVisibleChecked3(false);
          }
          setAutoClose(true);
        } else {
          setAutoClose(false);
        }
        if (res.data.Type == 1) {
          setTransfer(true);
        } else {
          setTransfer(false);
        }
        if (res.data.Type != 2 && res.data.Type != 1) {
          setHalf(false);
        } else {
          setHalf(true);
        }
        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);
        if (res.data.Extend != null) {
          obj.NodeAliasName = obj.NodeAliasName || res.data.Name;
          obj.Transferable = obj.Transferable == 1;
          setVisibleChecked(obj.Transferable == 1);
          obj.IsSave = obj.IsSave == 1;
          setVisibleChecked5(obj.IsSave == 1);
          setVisibleChecked6(obj.halfwayClose == 1);
          if (obj.EventsInformation === 1 || obj.EventsInformation === 0) {
            console.log(12);
            if (obj.EventsInformation === 1) {
              obj.EventsInformation = true;
              setVisibleChecked1(true);
            } else {
              obj.EventsInformation = false;
              setVisibleChecked1(false);
            }
          } else {
            obj.EventsInformation = true;
            setVisibleChecked1(true);
          }
          if (obj.IsSendMessage == 0 || obj.IsSendMessage == 1) {
            if (obj.IsSendMessage == 1) {
              obj.IsSendMessage = true;
              setVisibleChecked2(true);
            } else {
              obj.IsSendMessage = false;
              setVisibleChecked2(false);
            }
          } else {
            obj.IsSendMessage = true;
            setVisibleChecked2(true);
          }

          if (!obj.Handover) {
            obj.Handover = '移交选择人';
          }
          console.log(obj);
          form.setFieldsValue(obj);
        } else {
          setVisibleChecked(false);
          setVisibleChecked1(true);
          setVisibleChecked2(true);
          setVisibleChecked5(false);
          setVisibleChecked6(false);

          form.setFieldsValue({
            FlowName: res.data.FlowName,
            NodeAliasName: res.data.Name,
            Handover: '移交选择人',
          });
        }
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };
  // 获取反馈类型
  const getFeedbackName = () => {
    loadFeedbackType().then(res => {
      if (res.code === 0) {
        setBackType(res.data);
      }
    });
  };
  // 获取表名
  const getTableName = () => {
    loadEventTypeTable({ flowNodeId: msg.ID, nodeType: Number(msg.nodeType) }).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) {
        console.log(validate);
        validate.Transferable = visibleChecked ? 1 : 0;
        validate.EventsInformation = visibleChecked1 ? 1 : 0;
        validate.IsSendMessage = visibleChecked2 ? 1 : 0;
        validate.IsSave = visibleChecked5 ? 1 : 0;
        validate.AutoClose = visibleChecked3 ? '是' : '否';
        validate.halfwayClose = visibleChecked6 ? 1 : 0;
        console.log(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;
  };
  const change = e => {
    console.log(e);
    setVisibleChecked(e);
  };
  const change1 = e => {
    console.log(e);
    setVisibleChecked1(e);
  };
  const change2 = e => {
    console.log(e);
    setVisibleChecked2(e);
  };
  const change3 = e => {
    console.log(e);
    setVisibleChecked3(e);
  };
  const change5 = e => {
    console.log(e);
    setVisibleChecked5(e);
  };

  const change6 = e => {
    console.log(e);
    setVisibleChecked6(e);
  };

  return (
    <Drawer
      title={allDisabled ? '流程节点查看' : '流程节点配置'}
      width="500px"
      onClose={handleCancel}
      destroyOnClose
      visible={visible}
      footer={
        allDisabled ? null : (
          <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"
          rules={[{ required: true, message: '请填写节点别名' }]}
        >
          <Input disabled={allDisabled} placeholder="请输入节点别名" />
        </Form.Item>
        <Form.Item label="节点类型">
          <Form.Item name="NodeType" style={{ marginBottom: '10px' }}>
            <Select disabled={allDisabled} placeholder="请选择节点类型" style={{ width: '334px' }}>
              <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> */}
          <Row span={24}>
            <Col span={9}>
              <Form.Item name="Rollbackable" valuePropName="checked" style={{ marginBottom: 0 }}>
                <Checkbox disabled={allDisabled}>允许回退至</Checkbox>
              </Form.Item>
            </Col>
            <Col span={9}>
              <Form.Item name="RollbackNode" style={{ marginBottom: 0 }} initialValue="(上一节点)">
                <Select
                  disabled={allDisabled || isDisable}
                  placeholder="请选择回退节点"
                  style={{ width: '209px' }}
                >
                  {backNodes.map(item => (
                    <Option value={item.Name} key={item.ID}>
                      {item.Name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form.Item>
        <Form.Item label="工单主表" name="TableName">
          <Select
            placeholder="请选择工单主表"
            onChange={changTable}
            showSearch
            style={{ width: '100%' }}
            disabled={allDisabled}
          >
            {eventTable.map(item => (
              <Option value={item.Name} key={item.ID}>
                {item.Name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="移交方式" name="Handover">
          <Radio.Group disabled={allDisabled}>
            <Radio value="移交选择人">移交选择人</Radio>
            <Radio value="自处理">自处理</Radio>
            <Radio value="移交默认人">移交默认人</Radio>
            <Radio value="移交发起人">移交发起人</Radio>
            {/* <Option value="移交选择人">移交选择人</Option>
            <Option value="自处理">自处理</Option>
            <Option value="自处理或者移交选择人">自处理或者移交选择人</Option>
            <Option value="移交默认人">移交默认人</Option>
            <Option value="移交发起人">移交发起人</Option>
            <Option value="跨站移交">跨站移交</Option>
            <Option value="处理站点移交">处理站点移交</Option>
            <Option value="本人站点移交">本人站点移交</Option> */}
          </Radio.Group>
        </Form.Item>
        {/* <Form.Item label="检查前面在办" name="aheadHandle">
          <Select>
            <Option value={0}>前面有在办也能移交</Option>
            <Option value={1}>前面有在办不能移交</Option>
          </Select>
        </Form.Item>
        <Form.Item label="节点办理情况" name="NodeHandling">
          <Select>
            <Option value={0}>多人接收,多人办理</Option>
            <Option value={1}>多人接收,一人办理</Option>
            <Option value={2}>一人接收,一人办理</Option>
          </Select>
        </Form.Item> */}
        <Form.Item
          label={
            <div style={{ display: 'flex', alignItems: 'center' }}>
              {transfer ? (
                <>
                  <Tooltip title="开始节点不允许转单">
                    <InfoCircleOutlined style={{ color: '#1890ff', marginRight: '3px' }} />
                  </Tooltip>
                  <span>转单</span>
                </>
              ) : (
                <span>转单</span>
              )}
            </div>
          }
          name="Transferable"
        >
          <Switch
            checkedChildren="是"
            unCheckedChildren="否"
            checked={visibleChecked}
            onChange={change}
            disabled={allDisabled || transfer}
          />
        </Form.Item>
        <Form.Item label="暂存" name="IsSave">
          <Switch
            checkedChildren="是"
            unCheckedChildren="否"
            checked={visibleChecked5}
            onChange={change5}
            disabled={allDisabled}
          />
        </Form.Item>
        <Form.Item
          label={
            <div style={{ display: 'flex', alignItems: 'center' }}>
              {half == true ? (
                <>
                  <Tooltip title="开始节点和结束节点不可配置中途关单">
                    <InfoCircleOutlined style={{ color: '#1890ff', marginRight: '3px' }} />
                  </Tooltip>
                  <span>中途关单</span>
                </>
              ) : (
                <span>中途关单</span>
              )}
            </div>
          }
          name="halfwayClose"
        >
          <Switch
            checkedChildren="是"
            unCheckedChildren="否"
            checked={visibleChecked6}
            onChange={change6}
            disabled={allDisabled || half}
          />
        </Form.Item>

        <Form.Item
          label={
            <div style={{ display: 'flex', alignItems: 'center' }}>
              {autoClose == false ? (
                <>
                  <Tooltip title="结束节点可配置自动关单">
                    <InfoCircleOutlined style={{ color: '#1890ff', marginRight: '3px' }} />
                  </Tooltip>
                  <span>自动关单</span>
                </>
              ) : (
                <span>自动关单</span>
              )}
            </div>
          }
          name="AutoClose"
        >
          <Switch
            checkedChildren="是"
            unCheckedChildren="否"
            checked={visibleChecked3}
            onChange={change3}
            disabled={allDisabled || !autoClose}
          />
        </Form.Item>

        <Form.Item label="显示事件信息" name="EventsInformation">
          <Switch
            checkedChildren="是"
            unCheckedChildren="否"
            checked={visibleChecked1}
            onChange={change1}
            disabled={allDisabled}
          />
          {/* <Radio.Group>
            <Radio value="0">否</Radio>
            <Radio value="1">是</Radio>
          </Radio.Group> */}
        </Form.Item>
        <Form.Item label="是否发送短信" name="IsSendMessage">
          <Switch
            checkedChildren="是"
            unCheckedChildren="否"
            checked={visibleChecked2}
            onChange={change2}
            disabled={allDisabled}
          />
          {/* <Radio.Group>
            <Radio value={0}>否</Radio>
            <Radio value={1}>是</Radio>
          </Radio.Group> */}
        </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 disabled={allDisabled} placeholder="请选编辑字段" allowClear />
            </Form.Item>
            {allDisabled ? null : (
              <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;