/*
 * Create:      柿子
 * CreateDate:  2023/08/29
 * Describe：   汇总打印 - 销售单打印
 * */
import React, { Component } from 'react';
import { Button } from 'antd';
import { Util } from 'tools';
import { $loadTemplate } from 'pages/lodop/Common/Print.js';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination';

class SalesOrderPrinting extends Component {
  constructor(props) {
    super(props);
    let currentPatData = React.$getSessionData('titleData');
    this.state = {
      currentPatData,
      categoryData: {},
      totalStatistics: '', // 合计统计
      columns: [],
      totalWidth: 1000,
      tableData: [],
      selectedRows: [],
      selectedRowKeys: [],
    }
  }

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

  // 获取表头数据
  getColumnsData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'SalesOrderPrinting',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res?.result?.C || [];
      if (columns && columns.length > 0) {
        for (let i = 0; i < columns.length; i++) {
          if (columns[i]?.dataIndex === 'printDesc') {
            columns[i].render = (text, record) => {
              return (
                <span style={{ color: record?.print !== 'Y' ? 'red' : '' }}>{text}</span>
              )
            }
          }
        }
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  getTableData = async () => {
    try {
      let { currentPatData } = this.state;
      let data = {
        params: [{
          admID: currentPatData?.admID || ''
        }]
      }
      let res = await React.$asyncPost(this, '17030092', data);
      let tableData = Util.addKeyValueToDataSource(res?.result?.ordArr || [], 'orderDetailID');
      let selectedRows = [], selectedRowKeys = [];
      for (let i = 0; i < tableData.length; i++) {
        tableData[i].seqNo = i + 1;
        if (tableData[i]?.print !== 'Y') {
          selectedRows.push(tableData[i]);
          selectedRowKeys.push(tableData[i]?.orderDetailID || (i + 1));
        }
      }
      this.setState({
        tableData,
        selectedRows,
        selectedRowKeys
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 打印
  handlePrint = async () => {
    try {
      const { currentPatData, selectedRowKeys } = this.state;
      let data = {
        params: [{
          admID: currentPatData?.admID || '',
          orderDetailIDArr: selectedRowKeys,
        }]
      }
      let res = await React.$asyncPost(this, '17030093', data);
      let dataArr = res?.result || [];
      dataArr && dataArr.map((item, i) => {
        $loadTemplate(item.template, item.printStr);
      });
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  }

  // 列表选择操作
  handleSelectedRowKeysChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRows,
      selectedRowKeys,
    })
  }

  render() {
    const { totalStatistics, categoryData, columns, totalWidth, tableData, selectedRowKeys } = this.state;
    return (
      <div className="optometry-sheet sales-order-printing">
        <div style={{ marginBottom: '6px' }} className="flex-between-center">
          {totalStatistics && Array.isArray(totalStatistics) ? (
            <div style={{ color: '#666' }} className="flex-align-items">
              {totalStatistics.map((item, index) => {
                return (
                  <div key={index}>
                    {item.title}
                    {item?.firstSplit || '; '}
                    <span style={{ marginRight: index === 0 ? '12px' : '20px', color: categoryData?.statisticsValueColor || '#007AFF', fontWeight: '700', fontSize: '14px' }}>
                      {item.value}
                      {item?.lastSplit || ''}
                    </span>
                  </div>
                )
              })}
            </div>
          ) : <span>{totalStatistics}</span>}
          <Button disabled={!(selectedRowKeys && selectedRowKeys.length > 0)} type="primary" onClick={this.handlePrint}>打印</Button>
        </div>
        <div className="scroll-bar-style" style={{ height: store.getState().tableHeight.y + 70 + 'px', overflow: 'auto' }}>
          <PublicTablePagination
            param={{
              y: 'N',
              height: 'auto',
              columns,
              x: totalWidth,
              data: tableData,
              componentName: 'SalesOrderPrinting',
            }}
            rowSelectionPublic={{
              selectedRowKeys,
              onChange: this.handleSelectedRowKeysChange,
            }}
            getColumns={this.getColumnsData}
          />
        </div>
      </div>
    )
  }
};

export default SalesOrderPrinting;