import React, { useState, useEffect } from 'react';
import { Form, Select, Modal, Input, TreeSelect } from 'antd';
import moment from 'moment';
import provinces from './provinces';
import { queryApproval } from '@/services/approval';
const { Option } = Select;
const { TreeNode } = TreeSelect;
// 新建
function AddModal(props) {
  const {
    total,
    dispatch,
    visible,
    onClose,
    onOk,
    data,
    currentUser,
    depUserTree,
    flowList = [],
    industryList = [],
    typeList = [],
    disabled,
    loading,
  } = props;
  const [form] = Form.useForm();
  const [codes, setCodes] = useState({
    type: '',
    industry: '',
    location: '',
    name: '',
    version: '',
  });
  const [type, setType] = useState({});

  const handleOk = () => {
    form.validateFields().then((fieldsValue) => {
      let values = { ...fieldsValue, id: data.id };
      values.project_name = fieldsValue.project_name;
      values.flow_id = Number(fieldsValue.flow_id);
      values.type_id = Number(fieldsValue.type_id);
      // 获得flow下第一个node的id
      values.node_id = flowList.find(
        (item) => item.id == values.flow_id,
      ).Nodes[0].id;
      //项目分类为不为研发时
      if (fieldsValue.type_id != 7) {
        values.industry_id = Number(fieldsValue.industry_id);
        let [location, location_code] = fieldsValue.location.split('##');
        values.location = location;
        values.location_code = location_code;
        values.project_full_code = `${codes.type}${codes.industry}${codes.location}${codes.name}${codes.version}`;
      }
      if (fieldsValue.author) {
        values.author = Number(fieldsValue.author.split('||')[0]);
        values.author_dep_id = Number(fieldsValue.author.split('||')[1]);
      } else {
        values.author = null;
      }
      onOk(values);
    });
  };

  const renderTreeNodes = (data) => {
    return data.map((item) => {
      let title = item.name;
      let code = item.code || '';
      if (code.length == 4) {
        code = code.substr(1);
      }
      if (code) {
        title += `(${code})`;
      }
      let key = `${item.name}##${code}`;
      return (
        <TreeNode
          title={title}
          key={key}
          value={key}
          dataRef={item}
          selectable={Boolean(code)}
        >
          {item.children && renderTreeNodes(item.children || [])}
        </TreeNode>
      );
    });
  };
  const changeType = (id) => {
    const item = typeList.find((item) => item.id == id);
    setCodes({
      ...codes,
      type: item.code,
    });
    setType(item);
    form.setFieldsValue({ flow_id: id == 7 ? '4' : '1' });
  };
  const changeIndustry = (id) => {
    const item = industryList.find((item) => item.id == id);
    setCodes({
      ...codes,
      industry: item.code,
    });
  };
  const changeVersion = (index) => {
    setCodes({
      ...codes,
      version: index,
    });
  };
  const changeLocation = (value) => {
    const [location, code] = value.split('##');
    setCodes({
      ...codes,
      location: code,
    });
  };
  const onBlurName = (e) => {
    let value = e.target.value.toUpperCase();
    while (value.length < 3) {
      value = value + 'V';
    }
    form.setFieldsValue({
      name: value,
    });
    setCodes({
      ...codes,
      name: value,
    });
  };

  const renderDetail = () => {
    return (
      <>
        <Form.Item
          label="行业名称"
          name="industry_id"
          initialValue={String(data.industry_id || '')}
          rules={[{ required: true, message: '请选择行业名称' }]}
        >
          <Select style={{ width: '100%' }} onChange={changeIndustry}>
            {industryList.map((item) => (
              <Option key={item.id}>
                {item.name}({item.code})
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label="项目地区"
          name="location"
          initialValue={data.location}
          rules={[{ required: true, message: '请选择项目地区' }]}
        >
          <TreeSelect
            dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
            onChange={changeLocation}
          >
            {renderTreeNodes(provinces)}
          </TreeSelect>
        </Form.Item>
        <Form.Item
          label="项目简称"
          name="name"
          initialValue={data.name}
          rules={[
            { required: true, message: '请输入项目简称' },
            {
              validator: (rule, value) => {
                if (value && value.match(/[^A-Za-z]/g))
                  return Promise.reject(new Error('项目简称只能是英文字符'));
                else return Promise.resolve();
              },
            },
          ]}
        >
          <Input maxLength={3} onBlur={onBlurName} />
        </Form.Item>
        <Form.Item
          label="项目期数"
          name="version"
          initialValue={data.version}
          rules={[{ required: true, message: '请选择项目期数' }]}
        >
          <Select style={{ width: '100%' }} onChange={changeVersion}>
            {['一期', '二期', '三期', '四期', '五期'].map((item, index) => (
              <Option key={index + 1}>{item}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="项目编号">
          {codes.type || '***'}-{codes.industry || '***'}-
          {codes.location || '***'}-{codes.name || '***'}-{codes.version || '*'}
        </Form.Item>
      </>
    );
  };

  useEffect(() => {
    if (data.id) {
      const type = typeList.find((item) => item.id == data.type_id);
      const industry = industryList.find((item) => item.id == data.industry_id);
      setCodes({
        type: type?.code,
        industry: industry?.code,
        location: data.location_code,
        name: data.name,
        version: data.version,
      });
      setType(type);
    } else {
      setCodes({
        type: '',
        industry: '',
        location: '',
        name: '',
        version: '',
      });
      setType({});
    }
  }, [data, visible]);

  useEffect(() => {
    form.resetFields();
  }, [visible]);

  return (
    <Modal
      title="项目立项"
      confirmLoading={loading}
      maskClosable={false}
      destroyOnClose
      open={visible}
      onCancel={onClose}
      onOk={handleOk}
    >
      <Form labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} form={form}>
        <Form.Item
          label="项目名称"
          name="project_name"
          initialValue={String(data.project_name || '')}
          rules={[{ required: true, message: '请输入项目名称' }]}
        >
          <Input style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          label="项目类别"
          name="type_id"
          initialValue={String(data.type_id || '')}
          rules={[{ required: true, message: '请选择项目类别' }]}
        >
          <Select style={{ width: '100%' }} onChange={changeType}>
            {typeList.map((item) => (
              <Option key={item.id}>
                {item.name}({item.code})
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label="流程"
          name="flow_id"
          initialValue={String(data.flow_id || '')}
          rules={[{ required: true, message: '请选择流程' }]}
        >
          <Select style={{ width: '100%' }} disabled>
            {flowList
              .filter((item) => item && item.id != 2 && item.id != 3)
              .map((item) => (
                <Option key={item.id}>{item.name}</Option>
              ))}
          </Select>
        </Form.Item>
        {currentUser.IsSuper && (
          <Form.Item
            label="售前经理"
            name="author"
            initialValue={String(
              data.author && data.author_dep_id
                ? `${data.author}||${data.author_dep_id}`
                : '',
            )}
          >
            <TreeSelect
              showSearch
              allowClear
              style={{ width: '100%' }}
              multiple={false}
              filterTreeNode={(input, option) => {
                return option.props.title === input;
              }}
              treeData={depUserTree}
            />
          </Form.Item>
        )}
        {type?.id != 7 && renderDetail()}
      </Form>
    </Modal>
  );
}
export default AddModal;
