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

const AddModal = props => {
  const { onSubumit, handleCancel, visible, msg, flowId, modalType, title } = props;
  const [flowNodes, setFlowNodes] = useState([]);
  const [timeLimitFlowNodes, setTimeLimitFlowNodes] = 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();
      getLimitadFlowNodes();
      if (modalType === 'edit') {
        getFormData();
      } else {
        form.setFieldsValue({ FlowName: title });
      }
    }
  }, [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 = () => {
    reloadTimeLimitadFlowNodes({ flowNodeTableName: title }).then(res => {
      if (res.code === 0) {
        setTimeLimitFlowNodes(res.data);
      }
    });
  };
  // 根据流程ID加载起止节点和终止节点
  const getFlowNodes = () => {
    flowReloadFlowNodes({ flowId }).then(res => {
      if (res.code === 0) {
        setFlowNodes(res.data);
      }
    });
  };
  // 获取表单回显
  const getFormData = () => {
    console.log(msg);
    form.setFieldsValue({ ...msg, FlowName: title });
  };
  // 表单监听
  const onValuesChange = val => {
    if (Object.keys(val)[0] === 'StartNode') {
      flowNodes.forEach((item, index) => {
        if (item.Name === val.StartNode) {
          setStartNodeIndex(index);
        }
      });
    }
    if (Object.keys(val)[0] === 'EndNode') {
      flowNodes.forEach((item, index) => {
        if (item.Name === val.EndNode) {
          setEndNodeIndex(index);
        }
      });
    }
  };
  // 提交表单
  const onFinish = () => {
    form.validateFields().then(validate => {
      if (validate) {
        let obj = {};
        console.log(modalType);
        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
    >
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        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={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="TimeLimitInt"
              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="时限指派字段"
          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>
        <Form.Item
          label="超时记录字段"
          name="TimeoutField"
          rules={[{ required: true, message: '请选择超时记录字段' }]}
        >
          <Select>
            {timeLimitFlowNodes.map(item => (
              <Option value={item.Name} key={item.ID}>
                <span>{item.Name}</span>
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default AddModal;
