// 诊断查询
import React, { Component } from 'react';
import { Card, Row, Col, Input, Select, Button, Table, DatePicker, message, Icon, Divider, Popconfirm } from 'antd';
import { $http } from 'containers/config/https';
import store from 'store';
import Moment from 'moment';
import iconListvisits from 'assets/images/icon_listvisits.png';
import RequestForm from './DiagnosticQueryPopu';
import CommonPagination from '../../components/pagination';

class DiagnosticQuery extends Component {
  constructor(props) {
    super(props);
    this.state = {
      diagnosisDesc: undefined,
      startDate: Moment(),
      endDate: undefined,
      basicHeight: 0,
      tableData: [],
      page: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      insuType: '',
      medicalType: [],
      visible: false,
      userInfo: JSON.parse(window.sessionStorage.userData),
      proData: {},
      insObj: {},
      ICDObj: {}
    };

    this.columns = [
      {
        title: '医保类型',
        dataIndex: 'typeDesc',
        width: 120,
        align: 'center'
      },
      {
        title: '诊断代码',
        dataIndex: 'code',
        width: 120,
        align: 'center'
      },
      {
        title: '诊断内容',
        dataIndex: 'descripts',
        width: 220,
        align: 'center'
      },
      {
        title: 'ICD10诊断代码',
        dataIndex: 'ICDCode',
        width: 120,
        align: 'center'
      },
      {
        title: 'ICD10诊断描述',
        dataIndex: 'ICDDesc',
        width: 120,
        align: 'center'
      },
      {
        title: '生效日期',
        dataIndex: 'startDate',
        width: 120,
        align: 'center'
      },
      {
        title: '失效日期',
        dataIndex: 'stopDate',
        width: 120,
        align: 'center'
      },
      {
        title: '操作',
        align: "center",
        width: 100,
        fixed: 'right',
        render: (text, record) => (
          <span>
            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
            <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
            <Divider type="vertical"></Divider>
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleCompile(record, "2")} >
              <span className='span' style={{ color: "red" }}>删除</span>
            </Popconfirm>
          </span>
        ),
      }

    ]
  }

  componentDidMount() {
    this.setState({ basicHeight: document.getElementById("diagnostic-query").clientHeight }, () => {
      this.loadMedicalType();
      this.handleQuery()
      // setTimeout(() => {
      //   this.myRef1.current.focus();
      // }, 300)
    });
  }

  // 诊断名称
  handleDiagnosisDescChange = e => {
    this.setState({ diagnosisDesc: e.target.value })
  }
  handleChangeSelect = e => {
    this.setState({ insuType: e })
  }
  // 开始日期
  handleStartDateChange = e => {
    this.setState({ startDate: e })
  }

  // 开始日期
  handleEndDateChange = e => {
    this.setState({ endDate: e })
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1, loading: true }, () => {
      this.getTableData();
    })
  }
  // 重置表单
  resetFields = () => {
    this.props.form.resetFields(); //清空所有
    this.setState({
      proData: '',
      insObj: {},
      ICDObj: {}
    })

  };
  // 编辑
  handleCompile = (record, num) => {
    if (num == "2") {
      console.log("record", record)
      if (record.ID === "") {
        return;
      }
      let { userInfo } = this.state
      let data = {
        params: [{
          proKID: record.ID,
          updateUserID: userInfo.userID
        }],
      }
      $http.post("urlS", this, {
        code: "05100114",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            message.success("删除成功")
            this.resetFields();
            this.handleQuery();
          }
        }
      })
    }
    else {
      var insObj = { code: record.code, descripts: record.descripts }
      var ICDObj = { code: record.ICDCode, descripts: record.ICDDesc }
      this.setState({ proData: record, insObj: insObj, ICDObj: ICDObj }, () => {
        this.showPopu();
      });

    }
  }
  loadMedicalType() {
    var params = {
      params: [{}]
    }
    $http.post('urlDeault', this, {
      code: "05100389",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          this.setState({
            medicalType: res.result,
          })
        }
      }
    });
  }

  /**
   * @ByYQL:分页功能
   * 添加分页功能
   * Create 2021-11-30
   */
  // 条数改变的回调
  handleShowSizeChange = (current, size) => {
    this.setState({ page: current, pageSize: size, loading: true }, () => {
      this.getTableData();
    });
  }

  //页码改变的回调
  handlePageChange = (page, pageSize) => {
    this.setState({ page: page, pageSize, loading: true }, () => {
      this.getTableData();
    });
  }

  // 获取列表数据
  getTableData = () => {
    let { diagnosisDesc, insuType, startDate, endDate, page, pageSize } = this.state
    console.log("startDate", startDate)
    var params = {
      params: [{
        diagnosisDesc: diagnosisDesc || '',
        insuType: insuType || '',
        startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : Moment(new Date()).format('YYYY-MM-DD'),
        endDate: endDate || '',
      }],
      pagination: [{
        pageSize,
        currentPage: page
      }]
    }
    $http.post('urlDeault', this, {
      code: "05100390",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          this.setState({
            tableData: res.rows,
            total: res.total,
            loading: false
          })
        } else {
          message.warning(res.errorMessage)
          this.setState({
            loading: false
          })
        }
      }
    });
  }
  //弹框
  showPopu = () => {
    let { proData, insObj, ICDObj } = this.state
    // console.log("insObj11111111111111",insObj)
    // console.log("ICDObj22222222222222",ICDObj)
    this.childSelect.showModal(proData, insObj, ICDObj);
  };
  addNew = () => {
    this.childSelect.showModal();
  }
  onSelectRef = (ref) => {
    this.childSelect = ref;
  };
  render() {
    let { diagnosisDesc, startDate, endDate, basicHeight, tableData, page, pageSize, total, loading } = this.state;
    let medicalTypeOption = []
    this.state.medicalType && this.state.medicalType.map((item, index) => {
      medicalTypeOption.push(<Option key={index} value={item.code} code={item.descripts}
        name={item.descriptsSPCode}>{item.descripts}</Option>)
    })
    return (
      <div className="diagnostic-query">
        <Row id="diagnostic-query" className="common-query-header">
          <Col span={20}>
            诊断名称：
            <Input
              className="common-query-input"
              placeholder="请输入"
              allowClear
              onChange={this.handleDiagnosisDescChange} value={diagnosisDesc}
              onPressEnter={this.diagnosisDescOnPressEnter} id="diagnosisDesc"
            />
            医保类型：
            <Select
              allowClear
              className="common-query-input"
              onChange={this.handleChangeSelect}
            >
              {medicalTypeOption}
            </Select>
            生效日期：<DatePicker
              className="common-query-input"
              format="YYYY-MM-DD"
              placeholder="请选择生效日期"
              value={startDate}
              allowClear
              onChange={this.handleStartDateChange}
            />
            失效日期：<DatePicker
              className="common-query-input"
              format="YYYY-MM-DD"
              placeholder="请选择失效日期"
              value={endDate}
              allowClear
              onChange={this.handleEndDateChange}
            />
            <Button style={{ marginTop: '8px' }} onClick={this.handleQuery}>查询</Button>
          </Col>
          <Col span={4} style={{ textAlign: 'right' }}>
            <Button
              icon="plus"
              className="add-btn add-btn-nohover"
              onClick={this.addNew}
            >
              新增
            </Button>
          </Col>
        </Row>
        <div className="common-query-split-line" style={{ height: 8 }}></div>
        <Card
          size="small"
          bordered={false}
          title={(
            <div className="card-title-left-img">
              <img src={iconListvisits} alt="" />
              诊断列表
            </div>
          )}
        >
          <div>
            <Table
              columns={this.columns}
              dataSource={tableData}
              style={{ height: store.getState().tableHeight.y + 92 - basicHeight + 'px', }}
              scroll={{ x: 480, y: store.getState().tableHeight.y + 42 - basicHeight }}
              // rowSelection={rowSelection}
              onRow={this.onClickRowPublic}
              rowClassName={this.setRowClassNamePublic}
              // onHeaderRow={() => {
              //   return {
              //     onDoubleClick: () => {
              //       this.columnRef.onOpenModel()
              //     },
              //   };
              // }}
              bordered
              rowKey={(data) => {
                return data.key
              }}
              loading={loading}
              pagination={false}
              className="table-body-height" />

            {/*新增分页功能*/}
            <CommonPagination current={page} total={total} search="search" pageSize={pageSize}
              onShowSizeChange={this.handleShowSizeChange} complete={true} dataSource={tableData} size='small'
              loading={loading} onChange={this.handlePageChange} />
          </div>
        </Card>
        <RequestForm onRef={this.onSelectRef} handleThis={this} />
      </div>
    );
  }
}

export default DiagnosticQuery;
