/*
 * Create:      柿子
 * CreateDate:  2023/06/01
 * Describe：   汇总打印 - 软镜处方打印
 * */
import React, { Component } from 'react';
import { Row, Col, Button, Checkbox, message } from 'antd';
import { $loadTemplate } from 'pages/lodop/Common/Print.js';
import store from 'store';
import AcBarcode from 'ac-barcode';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import './style/index.less';

class SoftMirrorPrescription extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    let currentPatData = React.$getSessionData('titleData');
    this.state = {
      userData,
      currentPatData,
      printData: [],
      totalWidth: 550,
      columns: [],
    };
  }

  componentDidMount() {
    this.getPrintData();
    this.getColumnsData();
  }

  // 获取验光单数据
  getPrintData = async () => {
    try {
      let { currentPatData } = this.state;
      let data = {
        params: [{
          admID: currentPatData?.admID || ''
        }]
      }
      let res = await React.$asyncPost(this, '17030086', data);
      let printData = res?.result || [];
      for (let i = 0; i < printData.length; i++) {
        printData[i].checked = true;
        let optometryObj = printData[i];
        printData[i].tableData = [{ // 屈光检查结果
          key: 1,
          eyePart: '右眼', // 眼别
          jh: optometryObj?.jhRight || '', // 基弧
          qj: optometryObj?.qjRight || '', // 球镜
          zj: optometryObj?.zjRight || '', // 柱镜
          zw: optometryObj?.zwRight || '', // 轴位
        }, {
          key: 2,
          eyePart: '左眼', // 眼别
          jh: optometryObj?.jhLeft || '', // 基弧
          qj: optometryObj?.qjLeft || '', // 球镜
          zj: optometryObj?.zjLeft || '', // 柱镜
          zw: optometryObj?.zwLeft || '', // 轴位
        }, {
          key: 3,
          eyePart: '备注', // 眼别
          jh: optometryObj?.remark || '', // 基弧
        }];
      }
      this.setState({ printData });
    } catch (error) {
      this.setState({ printData: [] });
    }
  }

  // 打印勾选
  handleCheckboxChange = (e, index) => {
    let { printData } = this.state;
    printData[index].checked = e.target.checked;
    this.setState({});
  }

  // 获取表头数据
  getColumnsData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'SoftMirrorPrescription',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res?.result?.C || [];
      if (columns && columns.length > 0) {
        const renderContent = (value, row, index) => {
          const obj = {
            children: value,
            props: {},
          };
          if (index === 2) {
            obj.props.colSpan = 0;
          }
          return obj;
        };
        for (let i = 1; i < columns.length; i++) {
          if (i === 1) {
            columns[i].render = (value, row, index) => {
              const obj = {
                children: value,
                props: {},
              };
              if (index === 2) {
                obj.props.colSpan = 4;
              }
              return obj;
            };
          } else {
            columns[i].render = renderContent;
          }
        }
        this.setState({
          columns: React.$obtainHeaderGroupingData(columns),
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 打印
  handlePrint = async () => {
    try {
      let { printData } = this.state;
      let recordDataIDArr = [];
      for (var i = 0; i < printData.length; i++) {
        if (printData[i].checked) {
          recordDataIDArr.push(printData[i].recordDataID);
        }
      }
      if (!(recordDataIDArr && recordDataIDArr.length > 0)) {
        message.error('请选择需要打印的数据');
        return;
      }
      let data = {
        params: [{
          recordDataIDArr
        }]
      }
      let res = await React.$asyncPost(this, '17030087', data);
      let dataArr = res?.result || [];
      dataArr && dataArr.map((item, i) => {
        $loadTemplate(item.template, item.printStr);
      });
    } catch (error) {
      console.log(error);
    }
  }

  render() {
    const { userData, printData, totalWidth, columns } = this.state;
    return (
      <div className="optometry-sheet soft-mirror-prescription">
        <div style={{ textAlign: 'right', marginBottom: 12 }}>
          <Button type="primary" onClick={this.handlePrint}>打印</Button>
        </div>
        <div className="scroll-bar-style" style={{ height: store.getState().tableHeight.y + 70 + 'px', overflow: 'auto', paddingRight: 100 }}>
          {printData && printData.map((item, index) => {
            return (
              <div key={index} className="os-print-item">
                <h1 style={{ fontWeight: 800, fontSize: '22px' }} className="os-hosp">{item?.hospDesc || userData?.hospDesc}</h1>
                <h2 style={{ borderBottom: 0, fontWeight: 500, marginBottom: 0 }} className="os-title">
                  软镜处方
                  <div className="os-title-print">
                    <Checkbox checked={item.checked} onChange={(e) => this.handleCheckboxChange(e, index, item)}>打印</Checkbox>
                  </div>
                </h2>
                <Row className="os-item-rows" style={{ textAlign: 'right' }}>
                  <span>单号：</span>{item?.prescNo || ''}
                </Row>
                <Row className="os-item-rows">
                  <Col span={6}>
                    <span>姓名：</span>{item?.patName || ''}
                  </Col>
                  <Col span={6}>
                    <span>性别：</span>{item?.patSexDesc || ''}
                  </Col>
                  <Col span={6}>
                    <span>出生年月：</span>{item?.patBirthdate || ''}
                  </Col>
                  <Col span={6}>
                    <span>年龄：</span>{item?.patAge || ''}
                  </Col>
                </Row>
                <Row className="os-item-rows">
                  <Col span={6}>
                    <span>处方医生：</span>{item?.docDesc || ''}
                  </Col>
                  <Col span={8}>
                    <span>处方时间：</span>{item?.dateTime || ''}
                  </Col>
                </Row>
                <div style={{ minHeight: '100px' }}>
                  <PublicTablePagination
                    param={{
                      y: 'N',
                      height: 'auto',
                      x: totalWidth,
                      columns,
                      data: item?.tableData || [],
                      componentName: 'SoftMirrorPrescription',
                    }}
                    getColumns={this.getColumnsData}
                  />
                </div>
                <div className="os-ac-bar-code">
                  {item.patNo ? <AcBarcode value={item.patNo} width={1.5} height={32} fontSize={14} margin={3} /> : ''}
                </div>
              </div>
            )
          })}
        </div>
      </div>
    )
  }
}

export default SoftMirrorPrescription;