import React, { useState, useEffect} from 'react';
import { Form, Input, Button, Table, Select, Space, Menu, Dropdown, Modal, message, Row, Col } from 'antd';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import AddUser from './addUser'
import '@common/common.less';
import { useSelector } from 'react-redux'
import apiObj from '@api/index';
import UserContext from './user-context';
import { getValueFromEvent } from '@utils/index'
const { post, api, xPost } = apiObj;
const { Option } = Select;
function UserManager() {
  useEffect(() => {
    getUserPage();
  }, []);
  const [userList, setUserList] = useState([]);
  const [title, setTitle] = useState("");
  const [visible, setVisible] = useState(false);
  const [userId, setUserId] = useState("");
  const [msvisible, setMsvisible] = useState(false);
  const [modalType, setModalType] = useState("");
  const [type, setType] = useState("");
  const [formData, setFormData] = useState(null);
  const [roleList, setRoleList] = useState([]);
  const [size, setSize] = useState(15);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [params, setParams] = useState({
    pages: 1,
    current: 1,
    size: 15
  });
  const [form] = Form.useForm();
  const tipText = {
    1: '确定要删除该用户？',
    2: '禁用后该用户将无法登录，确定要禁用该用户?',
    3: '确定要重置该用户密码？',
  };
  const staticInfo = useSelector(state => {
    return state.staticInfo;
  });
  let list = []
  let listName = []
  let data = {
    pages: 1,
    current: 1,
    size: size
  }
  const { statusList } = staticInfo;
  //新增弹窗
  const showModal = (name, flag, userId) => {
    setTitle(name);
    setType(flag)
    setUserId(userId)
    if (flag == 1) {
      setFormData({
        status: '1'
      })
    }
    if (flag == 3 || flag == 2) {
      getUserById(userId)
    }
    setVisible(true);
  }
  //表格数据
  function getUserPage(param) {
    post(api.getUserPage, param || params).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
        setUserList(data.records);
        setTotal(data.total)
      }
    })
  }
  //查看用户
  function getUserById(userId) {
    xPost(api.getUserById, { userId: userId }).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
        let roles = []
        data.roles.forEach(item => {
          roles.push(item.roleId)
        })
        const arr = {
          username: data.username,
          mobilePhone: data.mobilePhone,
          password: data.password,
          againpassword: data.password,
          name: data.name,
          idcard: data.idcard,
          addHospitalTreeVO: getHospitals(data.hospitals),
          titleId: data.titleId,
          jobNo: data.jobNo,
          roles: roles,
          orderNo: data.orderNo,
          status: data.status,
          hospitalName:getHospitalsName(data.hospitals)
        }
        setRoleList(data.roles)
        setFormData(arr)
      }
    })
  }
  // 处理组织结构数据回显
  function getHospitals(arr) {
    arr.forEach((item, i, array) => {
      item.value = item.hospitalId
      item.title = item.hospitalName
      if (!item.children && item.depts) {
        item.depts.forEach(it => {
          it.value = item.parentId + '-' + it.deptId
          if (it.relation == 1) {
            list.push(it.value)
          }
        })
      }
      if (item.type != 0 && item.relation == 1) {
        list.push(item.value)
      }
      if (item.children) {
        getHospitals(item.children)
      }
    })
    return list
  }
  // 处理组织结构数据回显
  function getHospitalsName(arr) {
    arr.forEach((item, i, array) => {
      if (!item.children && item.depts) {
        item.depts.forEach(it => {
          if (it.relation == 1) {
            listName.push(it.deptName)
          }
        })
      }
      if (item.type != 0 && item.relation == 1) {
        listName.push(item.hospitalName)
      }
      if (item.children) {
        getHospitalsName(item.children)
      }
    })
    return listName
  }
  // 禁用/启用接口
  function disableUser(userId, status) {
    const param = { userId: userId, status: status };
    xPost(api.disableUser, param).then((res) => {
      if (res.data.code === 200) {
        getUserPage();
        setMsvisible(false);
        message.success((status ? '启用' : '禁用') + "成功");
      } else {
        message.warning(res.data.message || '操作失败');
      }
    }).catch(() => {
      message.error("接口出错");
    });
  }
  //重置密码
  function onResetPsd(userId) {
    const param = { userId: userId };
    xPost(api.resetPasswordUser, param).then((res) => {
      if (res.data.code === 200) {
        getUserPage();
        message.success("重置成功");
      } else {
        message.warning(res.data.message || '操作失败');
      }
    }).catch(() => {
      message.error("接口出错");
    });
  }
  //删除
  function deleteUser() {
    const param = { userId: userId };
    xPost(api.deleteUser, param).then((res) => {
      if (res.data.code === 200) {
        getUserPage();
        setMsvisible(false);
        message.success("删除成功");
      } else {
        message.warning(res.data.message || '操作失败');
      }
    }).catch(() => {
      message.error("接口出错");
    });
  }
  function onSizeChange(current, pageSize) {
    params.current = current
    params.size = pageSize
    setSize(pageSize)
    setCurrent(current)
    setParams(params)
    getUserPage()
  }
  function changePage(page, pageSize) {
    params.current = page
    params.size = pageSize
    setCurrent(page)
    setParams(params)
    getUserPage()
  }
  const onFinish = (value) => {
    const param = {
      ...data,
      ...value
    }
    setCurrent(1)
    setParams(param)
    getUserPage(param);
  };
  const onReset = () => {
    setCurrent(1)
    setParams(data)
    form.resetFields();
    getUserPage(data);
  };
  const messageBox = (type, id) => {
    setMsvisible(true)
    setUserId(id)
    setModalType(type)
  }

  //提示框确认事件
  function handleOk() {
    if (modalType == 1) {
      deleteUser(userId)
    } else if (modalType == 2) {
      disableUser(userId, 0)
    } else if (modalType == 3) {
      onResetPsd(userId);
    }
  }
  //提示框取消
  function handleCancel() {
    setMsvisible(false);
  }
  function cancel() {
    setVisible(false)
    setFormData(null)
  }
  function userChange() {
    setVisible(false)
    setFormData(null)
    getUserPage();
  }
  const columns = [
    { title: '用户名', dataIndex: 'username', key: 'index' },
    { title: '姓名', dataIndex: 'name', key: 'index' },
    { title: '所属组织', dataIndex: 'hospitalName', key: 'index' },
    { title: '工号', dataIndex: 'jobNo', key: 'index' },
    {
      title: '状态', dataIndex: 'status', key: 'status', render: (text, record) => (
        <Space size="middle">
          {record.status == 1 ?
            <span className="Enable">启用</span>
            :
            <span className="Disable">禁用</span>
          }
        </Space>
      )
    },
    {
      title: '操作', dataIndex: 'key', render: (text, record) => (
        <Space size="middle">
          <a onClick={e => showModal('查看用户', 3, record.userId)}>查看</a>
          <a onClick={e => showModal('修改用户', 2, record.userId)} >修改</a>
          <Dropdown overlay={menu.bind(this, record)} record={record}>
            <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
              更多 <DownOutlined />
            </a>
          </Dropdown>
        </Space>
      )
    }
  ]
  const menu = (record) => {
    return (
      <Menu>
        <Menu.Item key="0" className="menuItem" >
          <a onClick={() => messageBox(3, record.userId)}>
            重置密码
          </a>
        </Menu.Item>
        <Menu.Item key="1" className="menuItem" >
          {record.status === '1' ? (<a onClick={() => messageBox(2, record.userId)}>禁用</a>) : (<a  onClick={() => disableUser(record.userId, 1)}>启用</a>)}
        </Menu.Item>
        <Menu.Item key="2" className="menuItem" >
          <a  onClick={() => messageBox(1, record.userId)}>
            删除
          </a>
        </Menu.Item>
      </Menu>
    )
  }
  return (
    <div className="wrapper">
      <div className="filter-box">
        <Form
          form={form}
          name="normal_login"
          onFinish={onFinish}
          initialValues={{ status: '' }}
        >
          <Row gutter={24}>
            <Col span={5} key={0}>
              <Form.Item label="用户名" name="username" getValueFromEvent={getValueFromEvent}>
                <Input placeholder="用户名" autoComplete='off'/>
              </Form.Item>
            </Col>
            <Col span={5} key={1}>
              <Form.Item label="姓名" name="name" getValueFromEvent={getValueFromEvent}>
                <Input placeholder="姓名" autoComplete='off'/>
              </Form.Item>
            </Col>
            <Col span={5} key={2}>
              <Form.Item name="status" label="当前状态">
                <Select
                  allowClear
                >
                  {statusList.map((item) => {
                    return (
                      <Option value={item.name} key={item.name}>{item.val}</Option>
                    )
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6} key={3}>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button onClick={onReset}>
                  重置
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>

      <div className="table">
        <div className="table-header">
          <h2 className="table-title">用户管理</h2>
          <Button type="primary" icon={<PlusOutlined />} onClick={e => showModal('新增用户', 1)}>新增用户</Button>
        </div>

        <Table
          columns={columns}
          scroll={{ y: 'calc(100vh - 360px)' }}
          dataSource={userList}
          rowKey={record => record.userId + record.hospitalName}
          pagination={{
            current: current,
            pageSize: size,
            size: 'small',
            showSizeChanger: true,
            pageSizeOptions: ['15', '30', '60', '120'],
            showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条数据`,
            onShowSizeChange: (current, pageSize) => onSizeChange(current, pageSize), // 改变每页数量时更新显示
            onChange: (page, pageSize) => changePage(page, pageSize),//点击页码事件
            total: total
          }} />
      </div>
      {visible && formData ?
        <Modal
          title={title}
          okText='确定'
          cancelText='取消'
          width={500}
          visible={visible}
          onCancel={cancel}
          footer={null}
          forceRender={true}
        >
          <UserContext.Provider value={{ userId, type, formData, roleList }}>
            <AddUser userChange={userChange} cancel={cancel} />
          </UserContext.Provider>

        </Modal>
        : ''}
      <Modal
        title="提示"
        okText='确定'
        cancelText='取消'
        width={400}
        visible={msvisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>{tipText[modalType]}</p>
      </Modal>
    </div >
  )
}

export default UserManager;