import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { Empty,ConfigProvider,Form, Input, Button, Table, Select, Space, Modal, message, Row, Col } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import AddTerm from '../DiagManager/addDiag'
import '@common/common.less';
import apiObj from '@api/index';

const { post, api } = apiObj;
const { Option } = Select;
//获取列表
function SurgManager() {
  const { surgeryNum } = useSelector((state) => {
  	return state.userInfo;
  });
  useEffect(() => {
	  setSize(15)
	  setCurrent(1)
      form.resetFields();
      getSurgeryPage();
  }, [surgeryNum]);
  const [SurgList, setSurgList] = useState([]);//当前页列表数据
  const [Surgid, setSurgid] = useState([]);//当前操作行id
  const [title, setTitle] = useState("");//新增/修改的弹窗标题
  const [visible, setVisible] = useState(false);//新增修改 弹窗
  const [loading, setloading] = useState(true);//是否显示加载中
  const [flag, setFlag] = useState(false);//新增1或修改3
  const [delvisible, setDelvisible] = useState(false);//删除 弹窗
  const [formData, setFormData] = 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();

  let data = {
	pages: 1,
	current: 1,
	size: 15
  }
  //新增/修改 弹窗flag=1新增，3修改
  const showModal = (name, flag1, Surgrow) => {
	setVisible(true);
	setFlag(flag1)
	setTitle(name);console.log(flag)
	if (flag1 === 1) {
	  setFormData({
		status: 1,
		uniqueName:'',
		hisName:''
	  })
	}else if (flag1 === 3) {
	  console.log(33,Surgrow)
	  setFormData(Surgrow)
	}
  }
  //表格数据
  function getSurgeryPage(param) {  //type（必填）： 类型：1-化验、3-辅检、4-诊断、5-药品、6-手术和操作
  const hospitalId = localStorage.getItem('hospitalId')
  setloading(true)
  const hide = message.loading('加载中...',0);
	post(api.getTermPage, {...(param || params),type:6,hospitalId:hospitalId}).then((res) => {
	  hide()
	  if (res.data.code === 200) {
		const data = res.data.data;
		setSurgList(data.records);
		setTotal(data.total)
		setloading(false)
	  }
	})
  }
  function showDelModal(id){
	setDelvisible(true);
	setSurgid(id);
  }
  //删除
  function delSurgeryById() {
	post(api.deleteRecord, { id: Surgid }).then((res) => {
	  setDelvisible(false);
	  if (res.data.code === 200) {
		//刷新列表
		const totalPage = Math.ceil((total-1) / size);
		//将当前页码与删除数据之后的总页数进行比较，避免当前页码不存在
		const pagenum =
		    params.current > totalPage ? totalPage : params.current;
		//避免pagenum变为0
		params.current = pagenum < 1 ? 1 : pagenum;
		setParams(params)
		getSurgeryPage();
		setSurgid("");
		message.success("删除成功");
	  } else {
		message.warning(res.data.msg || '操作失败');
	  }
	}).catch(() => {
	  setDelvisible(false);
	  message.error("接口出错");
	});
  }
  //每页显示条数切换
  function onSizeChange(current, pageSize) {
	params.current = current
	params.size = pageSize
	setSize(pageSize)
	setCurrent(current)
	setParams(params)
  }
  //翻页
  function changePage(page, pageSize) {
	params.current = page
	params.size = pageSize
	setCurrent(page)
	setParams(params)
	getSurgeryPage()
  }
  //筛选查询
  const onFinish = (value) => {
	params.current = 1
	const param = {
	  ...params,
	  ...value
	}
	setCurrent(1)
	setParams(param)
	getSurgeryPage(param);
  };
  //重置
  const onReset = () => {
	setSize(15)
	setCurrent(1)
	setParams(data)
	form.resetFields();
	getSurgeryPage(data);
  };

  //删除 提示框取消或关闭
  function handleCancel() {
	setDelvisible(false);
  }

  //新增修改 取消或关闭
  function cancel() {
	setVisible(false)
	setFormData([])
  }

  function saveMatching(saveParams) {
	post(api.saveOrUpdateRecord, saveParams).then((res) => {
	  if (res.data.code === 200) {
		message.success("匹配成功");
		setVisible(false);
		setFormData([])
		getSurgeryPage();
	  } else {
		message.warning(res.data.message || "匹配失败，请重试");
	  }
	}).catch((error) => {
	  message.warning(error.message || "接口出错，请重试",);
	})
  }
  const renderEmpty = () => (
        <Empty
            imageStyle={{
                height: 0,
            }}
  		  description={<span></span>}
  		  >
        </Empty>
    )

  const columns = [
	{ title: '序号', dataIndex: 'index', render: (text, record, index) => (current - 1) * params.size + index + 1 },
	{ title: '操作时间', dataIndex: 'gmtModified', },
	{ title: '医院手术/操作名称', dataIndex: 'hisName', },
	{ title: '手术/操作代码', dataIndex: 'code', },
	{ title: '标准手术/操作名称', dataIndex: 'uniqueName', },
	{ title: '标准术语状态', dataIndex: 'status',render: (text, record) => {
		return record.status===1?'启用':record.status===0?'禁用':'';
	  }},
	{ title: '是否匹配', dataIndex: 'isMatch',render: (text, record) => {
		return record.isMatch===1?'已匹配':'未匹配';
	  }},
	{
	  title: '操作', dataIndex: 'key', render: (text, record) => (
		  <Space size="middle">
			<a onClick={e => showModal('修改手术/操作信息',3, record)}>修改</a>
			<a style={{color:"#FF4D4D"}} onClick={() => showDelModal(record.id)}>删除</a>
		  </Space>
	  )
	}
  ]
  return (
	  <div className="wrapper">
		<div className="filter-box">
		  <Form
			  form={form}
			  name="normal_login"
			  onFinish={onFinish}
		  >
			<Row gutter={24}>
			  <Col span={5} key={0}>
				<Form.Item label="医院手术/操作名称" name="hisName">
				  <Input placeholder="请输入" autoComplete='off' allowClear maxLength='30'/>
				</Form.Item>
			  </Col>
			  <Col span={5} key={1}>
				<Form.Item label="标准手术/操作名称" name="uniqueName">
				  <Input placeholder="请输入" autoComplete='off' allowClear maxLength='30'/>
				</Form.Item>
			  </Col>
			  <Col span={5} key={2}>
				<Form.Item id="groupTypeval" label="是否匹配" name="isMatch">
				  <Select
					  showSearch
					  optionFilterProp="children"
                      // onSearch={onSearch}
                      // onFocus={onFocus}
					  placeholder="全部"
				  >
					<Option value={''} key={-1}>全部</Option>
					<Option value={0} key={0}>未匹配</Option>
					<Option value={1} key={1}>已匹配</Option>
				  </Select>
				</Form.Item>
			  </Col>
			  <Col span={5} key={3}>
			  	<Form.Item  label="标准术语状态" name="status">
			  		<Select
			  		  showSearch
			  		  optionFilterProp="children"
			  		  placeholder="全部"
			  		>
			  		<Option value={''} key={-1}>全部</Option>
			  		<Option value={0} key={0}>禁用</Option>
			  		<Option value={1} key={1}>启用</Option>
			  		</Select>
			  	</Form.Item>
			  </Col>
			  <Col span={4} key={4}>
				<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>
			<Row gutter={12}>
			  <Col key={0}>
				<Button type="primary" icon={<PlusOutlined />} onClick={e => showModal('新增手术/操作信息',1)}>新增</Button>
			  </Col>
			</Row>
		  </div>
		<ConfigProvider renderEmpty={loading?renderEmpty:""}>
		  <Table
              /*rowSelection={{ type: 'checkbox', ...rowSelection, }}*/
			  columns={columns}
			  dataSource={SurgList}
			  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
			  }} />
			  </ConfigProvider>
		</div>
		  <AddTerm formData={formData}  termSType={6} termType={6} onOk={saveMatching} title={title} visible={visible} cancel={cancel}  flag={flag}/>
		<Modal
			maskClosable={false}
			title="删除手术/操作信息"
			okText='确定'
			cancelText='关闭'
			width={400}
			visible={delvisible}
			onOk={delSurgeryById}
			onCancel={handleCancel}
		>
		  <p>手术信息删除后将无法恢复，确认删除这条手术信息。</p>
		</Modal>
	  </div>
  )
}

export default SurgManager;