import React, { useState } from 'react';
import { message, Form, Modal, Select, DatePicker, TreeSelect } from 'antd';
import { connect } from 'dva';
import moment from 'moment';

const { Option } = Select;
const { MonthPicker } = DatePicker;
const { TreeNode } = TreeSelect;

function AddModal(props) {
  const {
    visible,
    onOk,
    onCancel,
    time,
    typeList = [],
    subTypeList = [],
    dispatch,
    project = [],
    loading,
    depUserTree,
  } = props;
  const [form] = Form.useForm();
  const [type, setType] = useState({});
  const [subType, setSubType] = useState({});
  const [showDepSelect, setShowDepSelect] = useState(false);
  const handleOk = () => {
    form.validateFields().then((values) => {
      if (type.type == 0 || subType.type == 0) {
        if (!values.project) {
          message.error('请选择项目');
          return;
        }
      } else {
        values.project = '0';
      }

      let params = [
        {
          type_id: Number(values.subType),
          comment: '',
          // 父级id
          parent_type_id: Number(values.type),
          data: [
            {
              project_id: Number(values.project),
              workload: 0,
              day: time,
            },
          ],
        },
      ];
      if (type.type == 0 && values.project == '0') {
        params[0].data[0].pay_dep_id = Number(values.pay_dep_id);
      }
      onOk(params);

      //将分类设为空，避免再次打开时有项目选单
      setType({});
      setSubType({});
      setShowDepSelect(false);
      form.resetFields();
    });
  };
  //同为将分类设为空
  const handleCancel = () => {
    setType({});
    setSubType({});
    setShowDepSelect(false);
    form.resetFields();
    onCancel();
  };
  const onChangeType = (value) => {
    let item = typeList.find((t) => t.id == value);
    form.setFieldsValue({
      project: null,
      subType: null,
    });
    setType(item);
    setSubType({});
    setShowDepSelect(false);
    dispatch({
      type: 'workload/save',
      payload: { subTypeList: [] },
    });
    if (!item.type) {
      dispatch({
        type: 'workload/queryProject',
        payload: { stage: value },
      });
    } else {
      dispatch({
        type: 'workload/querySubType',
        payload: { parent_id: item.id },
        callback: (subTypeList) => {
          if (value == 33) {
            form.setFieldsValue({
              project: null,
              subType: subTypeList[0].id + '',
            });
            setSubType(subTypeList[0]);
          }
        },
      });
    }
  };
  const onChangeSubType = (value) => {
    let item = subTypeList.find((t) => t.id == value);
    setSubType(item);
  };

  //售前支持更改项目时与子类选单联动
  const onChangeProject = (value) => {
    form.setFieldsValue({ subType: '' });
    dispatch({
      type: 'workload/querySubType',
      payload: { parent_id: type.id, project_id: value },
      callback: (subTypeList) => {
        if (type.id == 35) {
          form.setFieldsValue({ subType: subTypeList[0].id + '' });
          setSubType(subTypeList[0]);
          setShowDepSelect(false);
        }
        if (type.id == 2) {
          if (value == '0') {
            form.setFieldsValue({ subType: subTypeList[0].id + '' });
            setSubType(subTypeList[0]);
            setShowDepSelect(true);
          } else {
            form.setFieldsValue({ subType: subTypeList[1].id + '' });
            setSubType(subTypeList[1]);
            setShowDepSelect(false);
          }
        }
      },
    });
  };

  //分类选单
  const renderType = () => {
    return (
      <Form.Item
        label="分类"
        name="type"
        rules={[{ required: true, message: '请选择分类' }]}
      >
        <Select onChange={onChangeType} placeholder="请选择分类">
          {typeList.map((item) => (
            <Option key={String(item.id)}>{item.name}</Option>
          ))}
        </Select>
      </Form.Item>
    );
  };

  //项目选单
  const renderProject = () => {
    return (
      <Form.Item
        label="项目"
        name="project"
        rules={[{ required: true, message: '请选择项目' }]}
      >
        {/* 售前支持特殊判断，增加“无项目”，选择项目时与子类联动 */}
        <Select
          showSearch
          onChange={onChangeProject}
          placeholder="请选择项目"
          optionFilterProp="children"
          filterOption={(input, option) =>
            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >=
            0
          }
        >
          {type.id === 2 && <Option key={'0'}>售前支持(10100)</Option>}
          {project.map((item) => (
            <Option
              key={String(item.ID)}
            >{`${item.Name}(${item.Code})`}</Option>
          ))}
        </Select>
      </Form.Item>
    );
  };

  //子类选单
  const renderSubType = () => {
    return (
      <Form.Item
        label="子类"
        name="subType"
        rules={[{ required: true, message: '请选择子类' }]}
      >
        {/* 售前支持特殊判断，子类不可选 */}
        <Select
          disabled={type.id === 2}
          onChange={onChangeSubType}
          placeholder={type.id === 2 ? null : '请选择子类'}
        >
          {(subTypeList || []).map((item) => (
            <Option
              key={String(item.id)}
            >{`${item.name}(${item.code})`}</Option>
          ))}
        </Select>
      </Form.Item>
    );
  };

  //部门选择
  const renderDepSelect = () => {
    return (
      <Form.Item
        label="部门"
        name="pay_dep_id"
        rules={[{ required: true, message: '请选择部门' }]}
      >
        <TreeSelect
          showSearch
          allowClear
          // style={{ width: 240 }}
          placeholder="请选择部门"
          multiple={false}
          treeData={depUserTree}
          filterTreeNode={(input, option) => {
            return option.props.title === input;
          }}
        />
      </Form.Item>
    );
  };

  return (
    <Modal
      title="工时"
      open={visible}
      confirmLoading={loading}
      onCancel={handleCancel}
      maskClosable={false}
      onOk={handleOk}
      destroyOnClose
    >
      <Form labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} form={form}>
        {renderType()}
        {type.type == 0 && renderProject()}
        {showDepSelect && renderDepSelect()}
        {renderSubType()}
        <Form.Item label="时间">{time}</Form.Item>
      </Form>
    </Modal>
  );
}

export default connect(({ workload }) => ({
  project: workload.project,
  subTypeList: workload.subTypeList,
}))(AddModal);
