import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select } from 'antd';

import { dispatch } from '../../../model';

const GroupsSelect = ({value = {}, data, onChange}) => {
  const handleChange = (newValue) => {
    if (newValue) {
      const findGroup = data?.find(group => group.id === newValue);
      if (findGroup) {
        onChange?.({
          groupId: findGroup.id,
          groupName: findGroup.name,
          groupDisplayName: findGroup.desc,
        });
      }
    } else {
      onChange?.(null);
    }
  }

  return (
    <Select
      value={value?.groupId}
      onChange={handleChange}
      allowClear
    >
    {
      data?.map((group, index) => <Select.Option key={index} value={group.id}>{group.desc??group.name}</Select.Option>)
    }
    </Select>
  )
}

const UsersSelect = ({value = {}, data, onChange}) => {
  const handleChange = (newValue) => {
    if (newValue) {
      const findUser = data?.find(user => user.id === newValue);
      if (findUser) {
        onChange?.({
          userId: findUser.id,
          userName: findUser.name,
          userDisplayName: findUser.dname,
        });
      }
    } else {
      onChange?.(null);
    }
  }

  return (
    <Select
      value={value?.userId}
      onChange={handleChange}
      allowClear
    >
    {
      data?.map((user, index) => <Select.Option key={index} value={user.id}>{user.dname??user.name}</Select.Option>)
    }
    </Select>
  )
}

const FC = (props) => {
  const { visible, onCancel, task, action = 'add' } = props;

  const [form] = Form.useForm();
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [groups, setGroups] = useState();
  const [users, setUsers] = useState();

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 20 },
    },
  };

  useEffect(() => {

    if (visible) {
      getGroups();
      if (action !== 'add') {
        form.setFieldsValue(task);
        if (task.department?.groupId) {
          getUsers(task.department?.groupId);
        }
      }
    }

    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible])

  const getGroups = () => {
    dispatch({
      type: 'user.userGroups',
      callback: (data) => {
        setGroups(data);
      }
    })
  }

  const getUsers = (gid) => {
    dispatch({
      type: 'user.getGroupUsers',
      payload: {
        id: gid
      },
      callback: (data) => {
        setUsers(data);
      }
    })
  }

  const handleOk = async () => {
    try {
      const values = await form.validateFields();

      let newTask = {};
      if (action === 'add') {
        newTask = {...values};
      } else {
        newTask = {...task, ...values};
      }
      
      setConfirmLoading(true);
      dispatch({
        type: 'assetmanage.saveTask',
        payload: {
          data: newTask
        },
        callback: data => {
          setConfirmLoading(false);
          reset();
          onCancel && onCancel(true);
        },
        error: () => {
          setConfirmLoading(false);
        }
      })
    } catch (errInfo) {

    }
  }

  const onValuesChange = (changedValues, allValues) => {
    if (changedValues.hasOwnProperty('department') ) {
      if (changedValues.department?.groupId) {
        getUsers(changedValues.department.groupId);
      } else {
        setUsers();
      }
    }
  }

  const reset = () => {
    setConfirmLoading(false);
    form.resetFields();
    setGroups();
    setUsers();
  }

  return (
    <Modal 
      visible={visible}
      title={action==='add'?'新增任务':'编辑任务'}
      width={1000}
      confirmLoading={confirmLoading}
      onCancel={() => {
        reset();
        onCancel && onCancel();
      }}
      onOk={handleOk}
    >
    <Form 
      {...formItemLayout}
      form={form}
      onValuesChange={onValuesChange}
    >
      <Form.Item 
        label="盘点任务标题" 
        name="title" 
        rules={[{ required: true, message: '请输入标题名称' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item 
        label="盘点任务说明" 
        name="comment" 
      >
        <Input />
      </Form.Item>
      <Form.Item 
        label="所属部门" 
        name="department" 
        rules={[{ required: true, message: '请选择所属部门' }]}
      >
        <GroupsSelect data={groups} />
      </Form.Item>
      <Form.Item 
        label="资产专员" 
        name="specialist" 
        rules={[{ required: true, message: '请选择资产专员' }]}
      >
        <UsersSelect data={users} />
      </Form.Item>
    </Form>
    </Modal>
  );
}

export default FC;