import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Table, Select, Space, Modal, message, Row, Col, Tooltip } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import '@common/common.less';
import AddInpa from './addInpa'
import apiObj from '@api/index';
import { useSelector } from 'react-redux'
import InpaContext from './inpa-context';
import { getValueFromEvent } from '@utils/index'
const { post, api, xPost } = apiObj;
const { Option } = Select;
function InpaManager() {
  useEffect(() => {
    getRegion();
    // getDeptList()
  }, []);
  const [form] = Form.useForm();
  const [userList, setUserList] = useState([]);
  const [title, setTitle] = useState("");
  const [visible, setVisible] = useState(false);
  const [id, setId] = useState("");
  const [msvisible, setMsvisible] = useState(false);
  const [modalType, setModalType] = useState("");
  const [type, setType] = useState("");
  const [formData, setFormData] = useState(null);
  const [total, setTotal] = useState(0);
  const [size, setSize] = useState(15);
  const [current, setCurrent] = useState(1);
  const [params, setParams] = useState({
    pages: 1,
    current: 1,
    size: 15
  });
  const { user } = useSelector((state) => {
    return state.userInfo;
  });
  let data = {
    pages: 1,
    current: 1,
    size: size
  }
  const tipText = {
    1: '确定要删除该病区？',
    2: '确定要禁用该病区?',
  };
  const staticInfo = useSelector(state => {
    return state.staticInfo;
  });
  const { statusList } = staticInfo;
  //新增弹窗
  const showModal = (name, type, flag, id) => {
    setVisible(type);
    setTitle(name);
    setType(flag)
    setId(id)
    if (flag == 1) {
      setFormData({
        hospitalName: user.name,
        station: '病区',
        status: 1
      })
    }
    if (flag == 2) {
      getRegionById(id)
    }
  }
  //表格数据
  function getRegion(param) {
    post(api.getRegion, param || params).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
        setUserList(data.records);
        setTotal(data.total)
      }
    })
  }
  //科室列表
  // function getDeptList(param = {}) {
  //   post(api.getDeptList, param).then((res) => {
  //     if (res.data.code === 200) {
  //       const data = res.data.data;
  //       setDeptList(data);
  //     }
  //   })
  // }
  //查看用户
  function getRegionById(id) {
    post(api.updateRegion, { mark: 1, id: id }).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data.records[0];
        console.log(data)
        const arr = {
          hospitalName: data.hospitalName,
          name: data.name,
          code: data.code,
          liaison: data.liaison,
          phoneNumber: data.phoneNumber,
          station: '病区',
          orderNo: data.orderNo,
          status: data.status == '启用' ? '1' : '0',
        }
        setFormData(arr)
      }
    })
  }
  // 禁用/启用接口
  function checkSolveRegion(id, mark) {
    console.log(id)
    const param = { id: id, mark: mark };
    post(api.checkSolveRegion, param).then((res) => {
      if (res.data.code === 200) {
        getRegion();
        setMsvisible(false);
        message.success((mark == 2 ? '启用' : '禁用') + "成功");
      } else {
        message.warning(res.data.message || '操作失败');
      }
    }).catch(() => {
      message.error("接口出错");
    });
  }
  //删除
  function deleteRegion() {
    const param = { id: id };
    xPost(api.deleteRegion, param).then((res) => {
      if (res.data.code === 200) {
        getRegion();
        setMsvisible(false)
        message.success("删除成功");
      } else {
        message.warning(res.data.message || '操作失败');
      }
    }).catch(() => {
      message.error("接口出错");
    });
  }
  const onFinish = (value) => {
    const param = {
      ...data,
      ...value
    }
    setCurrent(1)
    setParams(param)
    getRegion(param);
  };
  const onReset = () => {
    setCurrent(1)
    setParams(data)
    form.resetFields();
    getRegion(data);
  };
  const messageBox = (type, id) => {
    setMsvisible(true)
    setId(id)
    setModalType(type)
    console.log(type)
  };
  //提示框确认事件
  function handleOk() {
    if (modalType == 1) {
      deleteRegion(id)
    } else if (modalType == 2) {
      checkSolveRegion(id, 1)
    }
  }
  //提示框取消
  function handleCancel() {
    setMsvisible(false);
  }
  function cancel() {
    setVisible(false)
    setFormData(null)
  }
  function userChange() {
    setVisible(false)
    getRegion()
  }
  // function onSearch(val) {
  //   getDeptList({ deptName: val })
  // }
  function onSizeChange(current, pageSize) {
    params.current = current
    params.size = pageSize
    setSize(pageSize)
    setCurrent(current)
    setParams(params)
    getRegion()
  }
  function changePage(page, pageSize) {
    params.current = page
    params.size = pageSize
    setCurrent(page)
    setParams(params)
    getRegion()
  }
  const columns = [
    { title: '病区名称', dataIndex: 'name', key: 'index' },
    {
      title: '所属病区', dataIndex: 'hospitalName', key: 'index',
      onCell: () => {
        return {
          style: {
            maxWidth: 150,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer'
          }
        }
      },
      render: (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>
    },
    // { title: '关联科室', dataIndex: 'deptName', key: 'index' },
    {
      title: '状态', dataIndex: 'status', key: 'status', render: (text, record) => (
        <Space size="middle">
          {record.status == '启用' ?
            <span className="Enable">启用</span>
            :
            <span className="Disable">禁用</span>
          }
        </Space>
      )
    },
    { title: '创建时间', dataIndex: 'gmtCreate', key: 'index' },
    {
      title: '操作', dataIndex: 'key', render: (text, record) => (
        <Space size="middle">
          <a onClick={e => showModal('修改用户', true, 2, record.id)} >修改</a>
          {record.status === '启用' ? (<a onClick={() => messageBox(2, record.id)}>禁用</a>) : (<a onClick={() => checkSolveRegion(record.id, 2)}>启用</a>)}
          <a target="_blank" onClick={() => messageBox(1, record.id)}>删除</a>
        </Space>
      )
    }
  ]

  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="name" getValueFromEvent={getValueFromEvent}>
                <Input placeholder="病区名称" autoComplete="off"/>
              </Form.Item>
            </Col>
            {/* <Col span={5} key={1}>
              <Form.Item label="关联科室" name="deptName">
                <Select
                  allowClear
                  showSearch
                  placeholder="请选择"
                  onSearch={onSearch}
                  filterOption={(input, option) =>
                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {deptList.map(item => {
                    return (
                      <Option value={item.id} key={item.id}>{item.name}</Option>
                    )
                  })}
                </Select>
              </Form.Item>
            </Col> */}
            <Col span={5} key={2}>
              <Form.Item name="status" label="当前状态">
                <Select
                  allowClear
                >
                  {statusList.map((item, index) => {
                    return (
                      <Option value={item.name} key={index}>{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('新增病区', true, 1)}>新增病区</Button>
        </div>

        <Table
          columns={columns}
          scroll={{ y: 'calc(100vh - 320px)' }}
          dataSource={userList}
          rowKey={record => record.id}
          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={'35%'}
          visible={visible}
          onCancel={cancel}
          footer={null}
          forceRender={true}
        >
          <InpaContext.Provider value={{ id: id, type: type, formData: formData }}>
            <AddInpa userChange={userChange} />
          </InpaContext.Provider>
        </Modal>
        : ''}
      <Modal
        title="提示"
        okText='确定'
        cancelText='取消'
        width={400}
        visible={msvisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>{tipText[modalType]}</p>
      </Modal>
    </div >
  )
}

export default InpaManager;