import React, { useEffect, useState } from 'react';
import {
  flowReloadFlowNodes,
  reloadTimeLimitadFlowNodes,
  operateFlowTimer,
  reloadFlowNodes,
} from '@/services/flow/flow';
import { Form, Modal, Input, notification, Select } from 'antd';
const { Option } = Select;

const AddModal = props => {
  const { onSubumit, handleCancel, visible, msg, flowId, modalType, title, finishNodes } = props;
  const [flowNodes, setFlowNodes] = useState([]);
  const [timeLimitFlowNodes, setTimeLimitFlowNodes] = useState([]);
  const [timeLimitFlowNodesEnd, setTimeLimitFlowNodesEnd] = useState([]);
  const [startNodeIndex, setStartNodeIndex] = useState(null);
  const [endNodeIndex, setEndNodeIndex] = useState(null);

  const [form] = Form.useForm();
  useEffect(() => {
    form.resetFields();
    setStartNodeIndex(null);
    setEndNodeIndex(null);
    if (visible) {
      getFlowNodes();
      if (modalType === 'edit') {
        console.log(msg, 'aa ');
        reloadFlowNodes({ flowName: title }).then(res => {
          if (res.code === 0) {
            let aa = res.data[0].Items.find(i => i.name == msg.StartNode);
            getLimitadFlowNodes(aa.extendTableName);
            let bb = res.data[0].Items.find(i => i.name == msg.EndNode);
            getLimitadFlowNodesEnd(bb.extendTableName);
            // 存入需要展开得节点
          }
        });
        getFormData();
      } else {
        form.setFieldsValue({
          FlowName: title,
          TimeLimit: 0,
          TimeUnit: '小时',
          TimeLimitField: '(未配置)',
          TimeoutField: '(未配置)',
        });
      }
    } else {
      setTimeLimitFlowNodes([]);
      setTimeLimitFlowNodesEnd([]);
    }
  }, [visible]);
  // 获取到节点后存入当前选中对应的索引用于限制选择节点
  useEffect(() => {
    if (flowNodes.length > 0) {
      flowNodes.forEach((item, index) => {
        if (item.Name === msg.StartNode && modalType === 'edit') {
          setStartNodeIndex(index);
        }
        if (item.Name === msg.EndNode && modalType === 'edit') {
          setEndNodeIndex(index);
        }
      });
    }
  }, [flowNodes]);
  // 根据下拉框选择的流程节点关联的表名加载指派字段
  const getLimitadFlowNodes = e => {
    reloadTimeLimitadFlowNodes({ flowNodeTableName: e }).then(res => {
      if (res.code === 0) {
        setTimeLimitFlowNodes(res.data);
      }
    });
  };

  const getLimitadFlowNodesEnd = e => {
    reloadTimeLimitadFlowNodes({ flowNodeTableName: e }).then(res => {
      if (res.code === 0) {
        setTimeLimitFlowNodesEnd(res.data);
      }
    });
  };
  // 根据流程ID加载起止节点和终止节点
  const getFlowNodes = () => {
    flowReloadFlowNodes({ flowId }).then(res => {
      if (res.code === 0) {
        setFlowNodes(res.data);
      }
    });
  };
  // 获取表单回显
  const getFormData = () => {
    form.setFieldsValue({ ...msg, FlowName: title });
  };
  // 表单监听
  const onValuesChange = val => {
    if (Object.keys(val)[0] === 'StartNode') {
      reloadFlowNodes({ flowName: title }).then(res => {
        if (res.code === 0) {
          let aa = res.data[0].Items.find(i => i.name == val.StartNode);
          getLimitadFlowNodes(aa.extendTableName);
          // 存入需要展开得节点
        }
      });
      flowNodes.forEach((item, index) => {
        if (item.Name === val.StartNode) {
          setStartNodeIndex(index);
        }
      });
    }
    if (Object.keys(val)[0] === 'EndNode') {
      reloadFlowNodes({ flowName: title }).then(res => {
        if (res.code === 0) {
          let aa = res.data[0].Items.find(i => i.name == val.EndNode);
          getLimitadFlowNodesEnd(aa.extendTableName);
          // 存入需要展开得节点
        }
      });
      flowNodes.forEach((item, index) => {
        if (item.Name === val.EndNode) {
          setEndNodeIndex(index);
        }
      });
    }
  };
  // 提交表单
  const onFinish = () => {
    form.validateFields().then(validate => {
      if (validate) {
        validate.TimeLimitField =
          validate.TimeLimitField === '(未配置)' ? '' : validate.TimeLimitField;
        validate.TimeoutField = validate.TimeoutField === '(未配置)' ? '' : validate.TimeoutField;
        let obj = {};
        if (modalType === 'add') {
          obj = { ...validate, ID: 0 };
        } else {
          obj = { ...validate, ID: msg.ID };
        }
        operateFlowTimer(obj)
          .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: '网络异常',
            });
          });
      }
    });
  };
  return (
    <Modal
      title="流程时限规则配置"
      visible={visible}
      onOk={onFinish}
      onCancel={handleCancel}
      maskClosable={false}
      destroyOnClose
      width={550}
    >
      <Form
        form={form}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 19 }}
        initialValues={{ remember: true }}
        onValuesChange={onValuesChange}
      >
        <Form.Item label="流程名称" name="FlowName">
          <Input disabled />
        </Form.Item>
        <Form.Item label="规则名称" name="Name" rules={[{ required: true }]}>
          <Input placeholder="请输入规则名称" />
        </Form.Item>
        <Form.Item label="起止节点" style={{ marginBottom: 0, message: '请选择节点' }} required>
          <div style={{ display: 'flex' }}>
            <Form.Item
              name="StartNode"
              style={{ width: '100%' }}
              rules={[{ required: true, message: '请选择节点' }]}
            >
              <Select>
                {flowNodes.map((item, index) => (
                  <Option
                    value={item.Name}
                    key={item.ID}
                    disabled={endNodeIndex !== null && index >= endNodeIndex}
                  >
                    {item.Name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <span style={{ width: '40px', textAlign: 'center' }}>--</span>
            <Form.Item
              name="EndNode"
              style={{ width: '100%' }}
              rules={[{ required: true, message: '请选择节点' }]}
            >
              <Select>
                {flowNodes.map((item, index) => (
                  <Option
                    value={item.Name}
                    key={item.ID}
                    disabled={
                      finishNodes.some(ele => item.Name === ele) ||
                      (startNodeIndex !== null && index <= startNodeIndex)
                    }
                  >
                    {item.Name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </div>
        </Form.Item>
        <Form.Item label="默认时限" style={{ marginBottom: 0 }} required>
          <div style={{ display: 'flex' }}>
            <Form.Item
              name="TimeLimit"
              style={{ marginRight: '18px', width: '100%' }}
              rules={[
                { required: true, message: '请选填写时限' },
                {
                  validator: (_, value) =>
                    value < 0 ? Promise.reject(new Error('默认时限需要大于零')) : Promise.resolve(),
                },
              ]}
            >
              <Input placeholder="请输入默认时限" />
            </Form.Item>
            <Form.Item
              name="TimeUnit"
              style={{ width: '100%' }}
              rules={[{ required: true, message: '请选择时限单位' }]}
            >
              <Select>
                <Option value="小时">小时</Option>
                <Option value="自然日">自然日</Option>
                <Option value="工作日">工作日</Option>
              </Select>
            </Form.Item>
          </div>
        </Form.Item>
        <Form.Item label="时限指派字段" required>
          <Form.Item
            name="TimeLimitField"
            rules={[{ required: true, message: '请选择时限指派字段' }]}
          >
            <Select>
              {timeLimitFlowNodes.map(item => (
                <Option value={item.Name} key={item.ID}>
                  <span>{item.Name}</span>
                </Option>
              ))}
            </Select>
          </Form.Item>
          <div style={{ marginTop: '-15px' }}>
            ● 来自起始节点工单表，可以为选择器，配置读取字典表；可以为日期/时间控件，用户自行选择。
          </div>
        </Form.Item>
        <Form.Item label="超时记录字段" required>
          <Form.Item
            name="TimeoutField"
            rules={[{ required: true, message: '请选择超时记录字段' }]}
          >
            <Select>
              {timeLimitFlowNodesEnd.map(item => (
                <Option value={item.Name} key={item.ID}>
                  <span>{item.Name}</span>
                </Option>
              ))}
            </Select>
          </Form.Item>
          <div style={{ marginTop: '-15px' }}>
            ● 来自终止节点工单表，由系统自动填写该工单是否超时。
          </div>
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default AddModal;
