/*
 * Creator:     ML
 * CreatDate:   2019-09-12
 * descripts：  门诊医生医嘱录入 申请单打印
*/
import React from 'react';
import { Tabs, Row, Col, Icon, Divider, Modal, Button, Checkbox, message } from 'antd';
import { $http } from 'containers/config/https';
import AcBarcode from 'ac-barcode';
import store from '../../../store';
import { $loadTemplate } from '../../lodop/Common/Print.js';
import { Util } from 'bizcharts';

const CheckboxGroup = Checkbox.Group;

class PrintingApplication extends React.Component {
  constructor(porps) {
    super(porps);
    this.state = {
      baseInfo: [],//处方打印信息
      newData: [],
      appLicaID: "",
      checkFlag: false,
    }

  }
  componentDidMount() {
    this.getPrescription()
  }
  //国际化
  setMessage(name, message) {
    return this.props.localeProvider ? this.props.localeProvider[name][message] : ''
  }
  getPrescription = () => {
    let data = {}
    let newDatas = []
    data = {
      params: [{
        admID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).admID : "",
        hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : {}
      }],
    }
    $http.post('urlS', this, {
      code: '03050141',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          // console.log("baseInfo",res.result.length)
          res.result && res.result.map((item) => {
            item["checkAll"] = item && item.orderList && item.orderList.length > 0 ? true : false;
            item["indeterminate"] = false;
            item["checkedList"] = item && item.orderList && item.orderList.length > 0 ? this.getCheckedList(item.orderList) : [];
            if (item.printFlag == 'Y') {
              item["checked"] = (item.printFlag == 'Y') ? true : false
              newDatas.push(item.id)
            } else {
              item["checked"] = (item.printFlag == 'Y') ? true : false
            }
          })
          this.setState({
            baseInfo: res.result,
            newData: newDatas
          }, () => {
            var selectAll = ''
            if (!Util.isEmpty(this.state.baseInfo)) {
              var baseInfo = this.state.baseInfo;
              for (var i = 0; i < baseInfo.length; i++) {
                if (baseInfo[i].printFlag !== 'Y') {
                  selectAll = true;
                  break;
                } else {
                  selectAll = false
                }
              }
              this.setState({ selectAll: selectAll })
            }
          })
        }
      },
    })
  }
  getCheckArr = (no,) => {
    const { baseInfo } = this.state
    return baseInfo.prescInfo.filter(item => item.No === no);
  }
  //选中打印
  handleCheck = (e, appLicaID) => {
    const { baseInfo, newData } = this.state
    let newDatas = this.state.newData
    let data = baseInfo
    data.map((item, i) => {
      if (item.id === appLicaID) {
        item.checked = e.target.checked
      }
    })
    this.setState({
      appLicaID: "",
      baseInfo: data
    })
    if (e.target.checked) {
      this.setState({
        appLicaID,
      })
      data.map((item, i) => {
        if (item.id === appLicaID) {
          newDatas.push(item.id)
          this.setState({
            newData: newDatas
          })
        }
      })
    } else {
      this.setState({
        appLicaID: ""
      })
      newData && newData.map((item, i) => {
        if (item === appLicaID) {
          newDatas.splice(i, 1)
          this.setState({
            newData: newDatas
          })
        }
      })
    }
  }

  // 获取检查项目勾选数据
  getOrderCheckedList = () => {
    let {baseInfo, newData} = this.state;
    let orderCheckedList = [];
    for (var i = 0; i < baseInfo.length; i++) {
      // 查找出baseInfo对应的勾选数据，并将检查项目勾选数据存在一个数组中返回出去
      if (newData.indexOf(baseInfo[i].id) !== -1) {
        orderCheckedList = orderCheckedList.concat(baseInfo[i].checkedList);
      }
    }
    return orderCheckedList;
  }

  //点击打印
  handlePrit = () => {
    if (this.state.newData && this.state.newData.length == 0) {
      message.warning("请选择需要打印的申请单")
      return
    }
    let data = {}
    data = {
      params: [{
        admID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).admID : "",
        userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
        hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
        groupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : "",
        appItemID: this.state.newData || "",
        orderCheckedList: this.getOrderCheckedList()
      }],
    }
    $http.post('urlS', this, {
      code: '03050129',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          if (res.result && res.result.length > 0) {
            res.result.map((item, i) => {
              $loadTemplate(item.template, item.printStr);
            })
          }
          this.getPrescription()
        }
      },
    })
  }

  //全选、取消全选
  handleChangeCheckbox() {
    var { baseInfo } = this.state;
    this.state.newData = []
    if (!Util.isEmpty(baseInfo)) {
      for (var i = 0; i < baseInfo.length; i++) {
        if (this.state.selectAll) {
          baseInfo[i]['checked'] = true
          this.state.newData.push(baseInfo[i].id)
          this.setState({ selectAll: false })
        } else {
          baseInfo[i]['checked'] = false
          this.setState({ selectAll: true, newData: [] })
        }
      }
    }
  }

  getCheckedList = (orderList) => {
    let checkedList = [];
    for (var i = 0; i < orderList.length; i++) {
      checkedList.push(orderList[i].ordID);
    }
    return checkedList;
  }

  // 检查项目全选
  onCheckAllChange = (orderList, e, index) => {
    let { baseInfo } = this.state;
    baseInfo[index].checkedList = e.target.checked ? this.getCheckedList(orderList) : [];
    baseInfo[index].checkAll = e.target.checked;
    baseInfo[index].indeterminate = false,
    this.setState({
      baseInfo
    });
  };

  handleCheckboxGroupChange = (orderList, checkedList, index) => {
    let { baseInfo } = this.state;
    baseInfo[index].checkedList = checkedList;
    baseInfo[index].indeterminate = !!checkedList.length && checkedList.length < orderList.length,
    baseInfo[index].checkAll = checkedList.length === orderList.length
    this.setState({
      baseInfo
    });
  };

  render() {
    const { baseInfo } = this.state
    console.log("this.props.localeProvider", this.props.localeProvider)
    const conent = {
      height: "70px",
      overflow: "auto"
    }
    const marginT = {
      margin: "6px 0"
    }
    let tabsHeight = store.getState().tableHeight.y + 54 + 'px'
    return (
      <div className="userInfoDom" style={{ width: "100% !important", position: "relative" }}>
        <div style={{ position: "absolute", right: "5px", top: "2px" }}>
          <Button style={{ marginRight: 10 }} onClick={this.handleChangeCheckbox.bind(this)}>{this.state.selectAll == true ? '全选' : '取消全选'}</Button>
          <Button type="primary" style={{ display: (baseInfo && baseInfo.length == 0 ? "none" : "inline-block") }} disabled={this.state.appLicaID && this.state.appLicaID.length == 0} onClick={this.handlePrit}>{this.props.localeProvider && this.props.localeProvider.PrintButtonPrint ? this.setMessage('PrintButtonPrint', 'descripts') : "打印"}</Button>
        </div>
        <p style={{ margin: "0", display: (baseInfo && baseInfo.length != 0 ? "none" : "inline-block") }}>
          {this.props.localeProvider && this.props.localeProvider.PrintApplicationTips ? this.setMessage('PrintApplicationTips', 'descripts') : "暂无可打印申请单"}
        </p>
        <div style={{ display: "flex", width: "100%", flexWrap: "wrap", justifyContent: "space-between", position: "relative", top: "40px", height: tabsHeight, overflow: "auto" }}>
          {
            baseInfo && baseInfo.map((item, i) => {
              return (
                <div style={{ width: "675px", margin: "0 40px 10px 0" }}>
                  <div style={{ border: "1px solid #cfcfcf", padding: "8px", position: "relative" }}>
                    <Row className="title">
                      <span style={{ fontSize: "24px", fontWeight: "600" }}>{item && item.hospDesc ? item.hospDesc + (this.props.localeProvider && this.props.localeProvider.PrintToCheckApplication ? this.setMessage('PrintToCheckApplication', 'descripts') : "检查申请单") : "--"}</span>
                    </Row>
                    <div style={{ position: "absolute", left: "5px", top: "0" }} >
                      <AcBarcode value={item.patNo} width={1.2 - ((20 - 10) / 20)} height={30} fontSize={10} margin={3} />
                    </div>
                    <div style={{ color: "#0099FF", position: "absolute", right: "4px", top: "14px" }}>
                      <Checkbox className="printingCheck" checked={item.checked} onChange={(e,) => this.handleCheck(e, item.id)}>{this.props.localeProvider && this.props.localeProvider.PrintButtonPrint ? this.setMessage('PrintButtonPrint', 'descripts') : "打印"}</Checkbox>
                    </div>
                    <Row style={marginT}>
                      <Col span={6}>
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintRegistrationNumber ? this.setMessage('PrintRegistrationNumber', 'descripts') : "登记号："}
                          {item && item.patNo ? item.patNo : "--"}
                        </span>
                      </Col>
                      <Col span={6}>
                        <span >
                          {this.props.localeProvider && this.props.localeProvider.PrintName ? this.setMessage('PrintName', 'descripts') : "姓名："}
                          {item && item.patName ? item.patName : "--"}
                        </span>
                      </Col>
                      <Col span={6}>
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintAge ? this.setMessage('PrintAge', 'descripts') : "年龄："}
                          {item && item.patAge ? item.patAge : "--"}
                        </span>
                      </Col>
                      <Col span={6}>
                        <span> {this.props.localeProvider && this.props.localeProvider.PrintFabe ? this.setMessage('PrintFabe', 'descripts') : "费别："}{item.admReason && item.admReason ? item.admReason : "--"}</span>
                      </Col>
                    </Row>
                    <Row style={marginT}>
                      <Col span={6}>
                        <span >
                          {this.props.localeProvider && this.props.localeProvider.PrintVisitType ? this.setMessage('PrintVisitType', 'descripts') : "就诊类型："}
                          {item && item.admType ? item.admType : "--"}
                        </span>
                      </Col>
                      <Col span={6}>
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintGender ? this.setMessage('PrintGender', 'descripts') : "性别："}
                          {item && item.patSexDesc ? item.patSexDesc : "--"}
                        </span>
                      </Col>
                      <Col span={6}>
                        <span>{this.props.localeProvider && this.props.localeProvider.PrintReceptionSection ? this.setMessage('PrintReceptionSection', 'descripts') : "接收科室："}{item.recLocDesc && item.recLocDesc ? item.recLocDesc : "--"}</span>
                      </Col>
                    </Row>
                    <Row style={marginT}>
                      <Col span={24}>
                        <span>
                          {this.props.localeProvider && this.props.localeProvider.PrintVisitingDepartment ? this.setMessage('PrintVisitingDepartment', 'descripts') : "就诊科室："}
                          {item && item.locDesc ? item.locDesc : "--"}
                        </span>
                      </Col>
                    </Row>
                    <div style={{ border: "1px solid #333333", padding: "4px 8px" }}>
                      {/* <div>
                        <Row style={conent}>
                          <Col span={24}>
                            {item.medicalRecord}
                          </Col>
                        </Row>
                       </div> */}
                      <div >
                        {/* <Row>
                          <Col span={24}>{this.props.localeProvider&&this.props.localeProvider.PrintCurrentHistory?this.setMessage('PrintCurrentHistory', 'descripts'):"现病史："}</Col>
                        </Row>
                        <Row style={conent}>
                          <Col span={24}>
                            {item.special}
                          </Col>
                        </Row> */}
                      </div>
                      {/* <div >
                        <Row>
                          <Col span={24}>{this.props.localeProvider&&this.props.localeProvider.PrintSigns?this.setMessage('PrintSigns', 'descripts'):"体征："}</Col>
                        </Row>
                        <Row style={conent}>
                          <Col span={24}>
                            {item.sign}
                          </Col>
                        </Row>
                       </div>   */}
                      <div >
                        <Row>
                          <Col span={24} style={{fontSize: "16px", color: "#333"}}>
                            {this.props.localeProvider && this.props.localeProvider.PrintClinicalDiagnosis ? this.setMessage('PrintClinicalDiagnosis', 'descripts') : "临床诊断："}
                          </Col>
                        </Row>
                        <Row style={conent}>
                          <Col span={24}>
                            {item.admDiag}
                          </Col>
                        </Row>
                      </div>
                      <div >
                        <Row>
                          <Col span={24}>
                            <Checkbox
                              onChange={(e) => this.onCheckAllChange(item.orderList, e, i)}
                              indeterminate={item.indeterminate}
                              checked={item.checkAll}
                            >
                              <span style={{fontSize: "16px", color: "#333"}}>{this.props.localeProvider && this.props.localeProvider.PrintCheckItem ? this.setMessage('PrintCheckItem', 'descripts') : "检查项目："}</span>
                            </Checkbox>
                          </Col>
                        </Row>
                        <Row>
                          <Col span={24}>
                            {/* {item.order} */}
                            <CheckboxGroup
                              value={item.checkedList}
                              onChange={(e) => this.handleCheckboxGroupChange(item.orderList, e, i)}
                            >
                              {item && item.orderList && item.orderList.map((checkItem, checkIndex) => {
                                return (
                                  <Row key={checkIndex}>
                                    <Checkbox value={checkItem.ordID}>{checkItem.ordDesc}</Checkbox>
                                  </Row>
                                )
                              })}
                            </CheckboxGroup>
                          </Col>
                        </Row>
                      </div>
                      {/* <div >
                        <Row>
                          <Col span={24}>{this.props.localeProvider&&this.props.localeProvider.PrintPurposeOfInspection?this.setMessage('PrintPurposeOfInspection', 'descripts'):"检查目的："}</Col>
                        </Row>
                        <Row style={conent}>
                          <Col span={24}>
                            {item.purpose}
                          </Col>
                        </Row>
                       </div> */}
                      <Row>
                        <Col span={12} className="smallTitle">
                          <span>{this.props.localeProvider && this.props.localeProvider.PrintBillingDoctor ? this.setMessage('PrintBillingDoctor', 'descripts') : "开单医生："}{item.doctorName ? item.doctorName : "--"}</span>
                        </Col>
                        <Col span={12} className="smallTitle">
                          <span>{this.props.localeProvider && this.props.localeProvider.PrintApplicationTime ? this.setMessage('PrintApplicationTime', 'descripts') : "申请时间："}{item.appDate ? item.appDate : "--"}</span>
                        </Col>
                      </Row>
                    </div>
                    <Row>
                      <Col span={24}>{this.props.localeProvider && this.props.localeProvider.PrintCheckLocation ? this.setMessage('PrintCheckLocation', 'descripts') : "检查地点："}{item.address ? item.address : "--"}</Col>
                    </Row>
                    <Row>
                      <Col span={24}>{this.props.localeProvider && this.props.localeProvider.PrintTips ? this.setMessage('PrintTips', 'descripts') : "温馨提示："}<span style={{ margin: "0 4px" }}>{this.props.localeProvider && this.props.localeProvider.PrintAmountApplication ? this.setMessage('PrintAmountApplication', 'descripts') : "此申请单金额："}</span>{item.totalPrice ? "￥" + item.totalPrice : "--"}</Col>
                    </Row>
                    <Row>
                      <Col span={24}>{this.props.localeProvider && this.props.localeProvider.PrintPrecautions ? this.setMessage('PrintPrecautions', 'descripts') : "注意事项："}{item.precaution ? item.precaution : "--"}</Col>
                    </Row>
                  </div>
                </div>
              )
            })
          }

        </div>
      </div>
    )
  }
}
export default PrintingApplication