/*
 * Create:      柿子
 * CreateDate:  2022/10/11 
 * Describe：   FastReport打印模板维护 
 * */
import React, { Component } from 'react';
import { Card, Row, Col, Button, message, Input, Icon, Divider, Popconfirm, Select, Tooltip } from 'antd';
import { Util } from 'tools';
import { $fastReportTemplate } from './Common/FastReportPrint';
import store from 'store';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import iconListvisits from 'assets/images/icon_listvisits.png';

class FastReportPrintTemplate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      code: undefined,
      descripts: undefined,
      page: 1,
      pageSize: 20,
      total: 0,
      rowID: '',
      loading: false,
      tableData: [],
      totalWidth: 700,
      columns: [],
      rowData: {},
      formData: [],
      detailPage: 1,
      detailPageSize: 20,
      detailTotal: 0,
      detailLoading: false,
      detailTableData: [],
      detailTotalWidth: 700,
      detailColumns: [],
      detailRowID: '',
      hospID: undefined,
      hospSelectData: [],
      detailRowData: {},
      detailFormData: [],
      detailData: {}
    };

    // 表格的表头数据
    this.staticColumns = [{
      key: '1',
      title: '代码',
      dataIndex: 'code',
      width: '200px',
      align: 'center'
    }, {
      key: '2',
      title: '描述',
      dataIndex: 'desc',
      width: '200px',
      align: 'center'
    }];

    // 表格的表头数据
    this.staticDetailColumns = [{
      key: 'hospDesc',
      title: '医院',
      dataIndex: 'hospDesc',
      width: '250px',
      align: 'center',
      render: (text, record) => {
        return (
          <Tooltip title={text}>
            <span className='ellipsis' style={{ width: '100%', display: 'block' }}>{text}</span>
          </Tooltip>
        );
      },
    }, {
      key: 'code',
      title: '代码',
      dataIndex: 'code',
      width: '100px',
      align: 'center',
      render: (text, record) => {
        return (
          <Tooltip title={text}>
            <span className='ellipsis' style={{ width: '100%', display: 'block' }}>{text}</span>
          </Tooltip>
        );
      },
    }, {
      key: 'desc',
      title: '描述',
      dataIndex: 'desc',
      width: '150px',
      align: 'center',
      render: (text, record) => {
        return (
          <Tooltip title={text}>
            <span className='ellipsis' style={{ width: '100%', display: 'block' }}>{text}</span>
          </Tooltip>
        );
      },
    }];
  }

  componentDidMount() {
    this.getHostSelectData();
    this.getTableData();
    this.getTableColumns();
    this.getDetailTableColumns();
  }

  //获取下拉框信息
  getHostSelectData = async () => {
    try {
      let res = await React.$asyncPost(this, '02010008');
      this.setState({ hospSelectData: res.hospital }, () => {
        this.getDetailTableColumns();
      });
    } catch (error) {
      this.setState({ hospSelectData: [] }, () => {
        this.getDetailTableColumns();
      });
    }
  }

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'FastReportPrintTemplate',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
      if (columns && columns.length > 0) {
        columns = columns.map(item => {
          return {
            ...item,
            render: (text, record) => {
              return (
                <Tooltip title={text}>
                  <span className='ellipsis' style={{ width: '100%', display: 'block' }}>{text}</span>
                </Tooltip>
              );
            },
          }
        })
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
      // 表单操作数据
      let formData = res.result && res.result.formData && res.result.formData.length > 0 ? res.result.formData : [];
      this.setState({ formData });
    } catch (error) {
      console.log(error)
    }
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1 }, () => {
      this.getTableData();
    })
  }

  // 请求列表数据
  getTableData = async () => {
    try {
      let { code, descripts, pageSize, page } = this.state;
      this.setState({ loading: true })
      let data = {
        params: [{
          code,
          desc: descripts
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, '01040300', data);
      let tableData = Util.addKeyValueToDataSource(res.result && 'rows' in res.result ? res.result.rows : (Array.isArray(res.result) ? res.result : []));
      this.setState({ tableData, total: res.result?.total || tableData.length, loading: false }, () => {
        this.handleClearSelectData();
      });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false }, () => {
        this.handleClearSelectData();
      });
    }
  }

  // 清除操作数据
  handleClearSelectData = () => {
    this.setState({ rowID: '', detailTableData: [] })
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.ID))) {
          this.setState({ rowID: record.ID }, () => {
            this.handleDetailQuery();
          });
        } else {
          this.setState({ rowID: '', detailTableData: [], detailTotal: 0 });
        }
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    return record.ID === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 新增
  handleAdd = () => {
    let { rowData } = this.state;
    if (rowData && 'ID' in rowData && rowData.ID) {
      this.setState({ rowData: {} })
    }
    this.modalRef && this.modalRef.modifyVisible(true);
  }

  // 编辑
  handleCompile = (record, e) => {
    this.handleStopPropagation(e);
    this.setState({ rowData: record }, () => {
      this.modalRef && this.modalRef.modifyVisible(true);
    })
  }

  // 保存
  handleSave = async (values) => {
    try {
      const { rowData } = this.state;
      let data = {
        params: [{
          ...values,
          ID: rowData?.ID
        }]
      }
      let res = await React.$asyncPost(this, '01040301', data);
      message.success(res?.errorMessage || '保存成功');
      this.modalRef && this.modalRef.modifyVisible(false, 'Y');
      this.setState({ rowData: {} });
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  }

  // 另存
  handleSaveAs = (record, e) => {
    this.handleStopPropagation(e);

  }

  // 删除
  handleDelete = async (record, e) => {
    try {
      this.handleStopPropagation(e);
      let data = {
        params: [{
          ID: record?.ID
        }]
      }
      let res = await React.$asyncPost(this, '01040080', data);
      message.success(res.errorMessage || '删除成功');
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  }

  // 点击input框时阻止事件冒泡
  handleStopPropagation = (e) => {
    e.stopPropagation();
  }

  // 获取列表表头数据
  getDetailTableColumns = async () => {
    try {
      const { hospSelectData } = this.state;
      let data = {
        params: [{
          compontName: 'FastReportPrintTemplateDetail',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let detailColumns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
      if (detailColumns && detailColumns.length > 0) {
        detailColumns = detailColumns.map(item => {
          return {
            ...item,
            render: (text, record) => {
              return (
                <Tooltip title={text}>
                  <span className='ellipsis' style={{ width: '100%', display: 'block' }}>{text}</span>
                </Tooltip>
              );
            },
          }
        })
        this.setState({
          detailColumns,
          dtailTotalWidth: res.totalWidth
        })
      }
      // 表单操作数据
      let detailFormData = res.result && res.result.formData && res.result.formData.length > 0 ? res.result.formData : [];
      if (detailFormData && detailFormData.length > 0) {
        for (var i = 0; i < detailFormData.length; i++) {
          if (detailFormData[i].dataIndex === 'hospID') {
            detailFormData[i].detailItem = hospSelectData;
          }
          if (detailFormData[i].typeCode === 'Switch' && 'default' in detailFormData[i] && detailFormData[i].default) {
            detailFormData[i].defaultValue = detailFormData[i].default;
          }
        }
      }
      this.setState({ detailFormData });
    } catch (error) {
      console.log(error)
    }
  }

  // 明细查询
  handleDetailQuery = () => {
    this.setState({ detailPage: 1, detailRowID: "" }, () => {
      this.getDetailTableData();
    })
  }

  // 获取明细列表数据
  getDetailTableData = async () => {
    try {
      let { hospID, rowID, detailPage, detailPageSize } = this.state;
      this.setState({ detailLoading: true })
      let data = {
        params: [{
          fastReportID: rowID,
          hospID
        }],
        pagination: [{
          pageSize: detailPageSize,
          currentPage: detailPage
        }]
      }
      let res = await React.$asyncPost(this, '01040302', data);
      let detailTableData = Util.addKeyValueToDataSource(res.result && 'rows' in res.result ? res.result.rows : (Array.isArray(res.result) ? res.result : []));
      this.setState({ detailTableData, detailTotal: res.result?.total || tableData.length, detailLoading: false });
    } catch (error) {
      this.setState({ detailTableData: [], detailTotal: 0, detailLoading: false });
    }
  }

  // 明细列表分页操作
  compileDetailPage = (page, pageSize) => {
    this.setState({ detailPage: page, detailPageSize: pageSize }, () => {
      this.getDetailTableData();
    })
  }

  // 操作行
  handleDetailClickRow = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.detailRowID === '' || (this.state.detailRowID && (this.state.detailRowID !== record.templateID))) {
          this.setState({ detailRowID: record.templateID, detailData: record });
        } else {
          this.setState({ detailRowID: '', detailData: {} });
        }
      }
    }
  }

  // 选中行操作
  handleDetailSetRowClassName = (record) => {
    return record.templateID === this.state.detailRowID ? 'clickRowStyle' : '';
  }

  // 记录表单的值
  recordformInput = record => {
    this.setState({ rowData: { ...this.state.rowData, ...record } })
  }

  // 新增明细
  handleDetailAdd = () => {
    let { detailRowData } = this.state;
    this.handleModifyDetailFormData('N');
    if (detailRowData && 'templateID' in detailRowData && detailRowData.templateID) {
      this.setState({ detailRowData: {} })
    }
    this.detailModalRef && this.detailModalRef.modifyVisible(true);
  }

  // 编辑医院打印信息
  handleDetailCompile = (record, e) => {
    this.handleStopPropagation(e);
    this.handleModifyDetailFormData('Y');
    this.setState({ detailRowData: record }, () => {
      this.detailModalRef && this.detailModalRef.modifyVisible(true);
    })
  }

  // 修改明细表单医院下拉操作状态
  handleModifyDetailFormData = (status) => {
    let { detailFormData } = this.state;
    for (var i = 0; i < detailFormData.length; i++) {
      if (detailFormData[i] && detailFormData[i].dataIndex === 'hospID') {
        detailFormData[i].disabled = status;
        break;
      }
    }
    this.setState({ detailFormData });
  }

  // 删除模板
  handleDetailDelete = async (record, e) => {
    try {
      this.handleStopPropagation(e);
      let data = {
        params: [{
          templateID: record?.templateID
        }]
      }
      let res = await React.$asyncPost(this, '01040305', data);
      message.success(res.errorMessage || '删除成功');
      this.getDetailTableData();
    } catch (error) {
      console.log(error)
    }
  }

  // 导入
  handleImport = (record, e) => {
    this.handleStopPropagation(e);
  }

  // 导出
  handleExport = (record, e) => {
    this.handleStopPropagation(e);
  }

  // 另存为医院模板
  handleSaveAsHospTemplate = async () => {
    try {
      const { hospID, detailRowID } = this.state;
      if (!detailRowID) {
        message.error('请先选择记录再做另存操作!');
        return;
      }
      if (!hospID) {
        message.error('请先选择医院再做另存操作!');
        return;
      }
      let data = {
        params: [{
          templateID: detailRowID,
          hospID,
        }]
      }
      let res = await React.$asyncPost(this, '01040304', data);
      message.success(res.errorMessage || '保存成功');
      this.getDetailTableData();
    } catch (error) {
      console.log(error)
    }
  }
  // 编辑模板信息
  handleSaveHospTemplate = async () => {
    try {
      const { hospID, detailRowID, detailData } = this.state;

      if (!detailRowID) {
        message.error('请先选择记录再做编辑模板信息!');
        return;
      }
      let dataResult = {    //此数据为打印数据dataResult必需为{} 不能是[]  data1,data2 可以随意命名但必需为[] 不能为{}
        "data1": [{ "name": "sdsds1", "name2": "12323221" }, { "name": "sdsds1", "name2": "12323221" }],
        "data2": [{ "name5": "sdsds2", "name6": "12323222" }, { "name5": "sdsds2", "name6": "12323222" }],
      }
      //async function run() {
      //  for (let i = 0; i < 1; i++) {
      let returndata = await $fastReportTemplate(detailData.code, hospID, dataResult, "", "Y", detailRowID);
      console.log(returndata)
      //  }
      //}
      //run().then((res) => {
      //  alert('打印完成！')
      //})
    } catch (error) {
      console.log(error)
    }
  }
  // 调用DLL fastReport工具
  dllClassPut = async (values) => {
    try {
      const { hospID, detailRowID } = this.state;
      let data = {
        params: [{
          templateID: detailRowID,
          hospID,
        }]
      }
      /*
      let dllparams = {
        params:[
          {
            "dataResult":"",
            "dataParams":"",
            "reportTemplateDate":{
              "reportTemplate":(values)
            }
          }
        ]
      }*/
      let dllparams = {
        params: [
          {
            "dataResult": {    //此数据为打印数据dataResult必需为{} 不能是[]  data1,data2 可以随意命名但必需为[] 不能为{}

              "data1": [{ "name": "sdsds", "name2": "1232322" }, { "name": "sdsds", "name2": "1232322" }],
              "data2": [{ "name5": "sdsds", "name6": "1232322" }, { "name5": "sdsds", "name6": "1232322" }],

            },
            "dataParams": {    //当数据量大不能在前端传入 此参数是直接调用后端取 dataResult

              "params": [{
                "userID": "292",
                "userCode": "1020",
                "currentLocFlag": "Y",
                "language": "CN"
              }],
              "code": "01040043"

            },
            "reportTemplateDate": {
              "reportTemplate": (values)
            }
          }
        ]
      }

      let cancleSetlRtn = await dllUtil.dllClassName("FastReport", dllparams, "FastReport/FastReportFrom.dll", 'FastReportFrom.FastReportDll');
      let res = JSON.parse(cancleSetlRtn);
      if (res.errorCode == '0') {
        message.success(res.errorMessage || '保存成功');
      }
      else {
        message.error(res.errorMessage || '失败');
      }
      this.getDetailTableData();
    } catch (error) {
      console.log(error)
    }
  }
  recordDetailformInput = record => {
    this.setState({ detailRowData: { ...this.state.detailRowData, ...record } })
  }

  // 明细保存
  handleDetailSave = async (values) => {
    try {
      const { detailRowData, rowID } = this.state;
      let data = {
        params: [{
          ...values,
          templateID: detailRowData?.templateID,
          fastReportID: rowID, //主表ID
        }]
      }
      let res = await React.$asyncPost(this, '01040303', data);
      message.success(res?.errorMessage || '保存成功');
      this.detailModalRef && this.detailModalRef.modifyVisible(false, 'Y');
      this.setState({ detailRowData: {} });
      this.getDetailTableData();
    } catch (error) {
      console.log(error)
    }
  }

  render() {
    const { code, page, total, loading, tableData, totalWidth, columns, formData, rowData, detailPage, detailTotal, detailLoading, detailTableData, detailTotalWidth, detailColumns, hospID, hospSelectData,
      detailRowData, detailFormData, rowID
    } = this.state;
    // 明细列表行操作
    const operationDetailObj = {
      width: 200,
      title: '操作',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <span>
          <span className="span" onClick={(e) => this.handleImport(record, e)}>导入</span>
          <Divider type="vertical" />
          <span className="span" onClick={(e) => this.handleExport(record, e)}>导出</span>
          <Divider type="vertical" />
          <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
          <span className="span" onClick={(e) => this.handleDetailCompile(record, e)}>编辑</span>
          <Divider type="vertical" />
          <Icon type="delete" className="common-record-delete-span"></Icon>
          <Popconfirm
            title="删除后不可恢复，确定要删除吗?"
            onClick={this.handleStopPropagation}
            onCancel={this.handleStopPropagation}
            onConfirm={(e) => this.handleDetailDelete(record, e)}
          >
            <span className="span common-record-delete-span">删除</span>
          </Popconfirm>
        </span>
      ),
    };
    return (
      <div>
        <Row className="fast-report-print-template">
          <Col span={8}>
            <div style={{ paddingRight: '6px', position: 'relative', height: '100%' }}>
              <Card
                size="small"
                bordered={false}
                className="table-body-height"
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListvisits} alt="" />
                    打印类型
                  </div>
                )}
              >
                <div className="flex-between-center" style={{ marginBottom: 12 }}>
                  <div className="flex-align-items">
                    别名：<Input
                      value={code}
                      placeholder="输入代码/描述（Enter）"
                      className="common-query-input"
                      style={{ marginRight: '12px', width: '200px' }}
                      onPressEnter={this.handleQuery}
                      onChange={Util.commonInputChange.bind(this, 'code')}
                    />
                    <Button onClick={this.handleQuery}>查询</Button>
                  </div>
                  <Button
                    icon="plus"
                    className="add-btn add-btn-nohover"
                    onClick={this.handleAdd}
                  >
                    新增
                  </Button>
                </div>
                <PubilcTablePagination
                  param={{
                    page,
                    total,
                    loading,
                    pageSize: '20',
                    componentName: 'FastReportPrintTemplate',
                    data: tableData, // 表格数据
                    x: totalWidth, // 表格的宽度
                    y: store.getState().tableHeight.y + 50,
                    height: store.getState().tableHeight.y + 100 + 'px',
                    columns: columns && columns.length > 0 ? [...columns] : [...this.staticColumns], // 表头配置
                  }}
                  compilePage={this.compilePage}
                  getColumns={this.getTableColumns}
                  onClickRowPublic={this.onClickRowPublic}
                  setRowClassNamePublic={this.setRowClassNamePublic}
                />
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={16}>
            <Card
              size="small"
              bordered={false}
              className="table-body-height"
              title={(
                <div className="card-title-left-img">
                  <img src={iconListvisits} alt="" />
                  模板维护
                </div>
              )}
            >
              <div className="flex-between-center" style={{ marginBottom: 12 }}>
                <div className="flex-align-items">
                  医院：<Select
                    allowClear
                    showSearch
                    value={hospID}
                    placeholder="请选择"
                    optionFilterProp="seachprop"
                    className="common-query-input"
                    style={{ width: '260px', marginRight: 12 }}
                    onChange={Util.handleSelectChange.bind(this, 'hospID')}
                  >
                    {React.$SelectOptions(hospSelectData)}
                  </Select>
                  <Button style={{ marginRight: '12px' }} onClick={this.handleDetailQuery}>查询</Button>
                  <Button ghost type="primary" onClick={this.handleSaveAsHospTemplate}>另存为医院模板</Button>
                </div>
                <div className="flex-align-items">
                  <Button ghost type="primary" onClick={this.handleSaveHospTemplate}>编辑模板</Button>
                  <Button
                    icon="plus"
                    className={rowID ? "add-btn add-btn-nohover" : ''}
                    onClick={this.handleDetailAdd}
                    style={{ marginLeft: 12 }}
                    disabled={!rowID}
                  >
                    新增
                  </Button>
                </div>
              </div>
              <PubilcTablePagination
                param={{
                  pageSize: '20',
                  page: detailPage,
                  total: detailTotal,
                  loading: detailLoading,
                  data: detailTableData, // 表格数据
                  x: detailTotalWidth, // 表格的宽度
                  y: store.getState().tableHeight.y + 50,
                  height: store.getState().tableHeight.y + 100 + 'px',
                  componentName: 'FastReportPrintTemplateDetail',
                  columns: detailColumns && detailColumns.length > 0 ? [...detailColumns, operationDetailObj] : [...this.staticDetailColumns, operationDetailObj], // 表头配置
                }}
                getColumns={this.getDetailTableColumns}
                compilePage={this.compileDetailPage}
                onClickRowPublic={this.handleDetailClickRow}
                setRowClassNamePublic={this.handleDetailSetRowClassName}
              />
            </Card>
          </Col>
        </Row>

        {/* 主表新增弹窗 */}
        <PublicModalFormHooks
          idField="ID"
          rowData={rowData}
          formData={formData}
          onRef={ref => this.modalRef = ref}
          formItemCol={{ labelCol: 5, wrapperCol: 16, col: 24 }}
          recordFormInput={this.recordformInput}
          handleSave={this.handleSave}
        />

        {/* 明细表新增弹窗 */}
        <PublicModalFormHooks
          idField="templateID"
          rowData={detailRowData}
          formData={detailFormData}
          onRef={ref => this.detailModalRef = ref}
          formItemCol={{ labelCol: 5, wrapperCol: 16, col: 24 }}
          recordFormInput={this.recordDetailformInput}
          handleSave={this.handleDetailSave}
        />
      </div>
    )
  }
};

export default FastReportPrintTemplate;