/*
 * Creater:     shizi
 * CreateDate:  2022/05/24
 * Describe：   通用医嘱项目维护 / 医院收费项维护
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Input, Select, Button, Popconfirm, Divider, message } from 'antd';
import store from 'store';
import { Util } from 'tools';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import AddOrderItem from './orderItemComponent/AddOrderItem'; // 新增医嘱项
import AddChargItem from './orderItemComponent/AddChargItem'; // 新增收费项
import PublicModalTable from 'pages/common/PublicModalTable';
import iconListvisits from 'assets/images/icon_listvisits.png';
import './style/new-drug.less';

class OrderItemMaintenance extends Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      category: '', // 类别
      selectData: {}, // 下拉数据
      medAlias: undefined, // 代码/名称
      pcInput: undefined, // 物价代码/名称
      ordTypeCode: '', // 医嘱类型
      linkNumCode: '', // 关联收费项数
      chargeTCID: undefined, // 收费子类
      contrastStatus: undefined, // 对照状态
      statusID: undefined, // 状态
      columns: [], // 表头数据
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 20,
      totalwidth: 420,
      loading: false,
      rowID: '',
      rowData: {},
      userOrganizationCloumns: [], // 使用医院
      userOrganizationTableData: [],
      allPatData: '',
      exportLoading: false,//导出请求
    };
  }

  componentDidMount() {
    // orderItem - 医嘱项 
    // chargeItem - 收费项
    let category;
    if ('paras' in this.props && this.props.paras.type) { // 侧菜单获取类别参数
      category = this.props.paras.type;
    } else {
      if ('location' in this.props && this.props.location.state && this.props.location.state.type) { // 头菜单获取类别参数
        category = this.props.location.state.type;
        React.$setSessionData('OrderItemMaintenance', category, false);
      } else { // 头菜单刷新界面时获取类别
        category = React.$getSessionData('OrderItemMaintenance', false);
      }
    }
    this.setState({ category, loading: true, statusID: 'U' }, () => {
      this.getTableColumns();
      this.getSelectData();
      if (category === 'orderItem') {
        this.handleQuery();
      } else {
        // 收费项默认先不查，查全部比较卡
        this.setState({ loading: false });
      }
      this.getUserOrganizationCloumns();
    });
  }

  // 获取下拉列表数据
  getSelectData = async () => {
    let selectData = await React.$asyncPost(this, '02020383');
    this.setState({ selectData })
  }

  // 获取列表columns
  getTableColumns = async () => {
    let { category } = this.state;
    let operation = {
      title: '操作',
      dataIndex: 'operation',
      fixed: 'right',
      align: 'center',
      width: 110,
      render: (text, record) => (
        <span>
          {record?.statusCode === 'U' ? (
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handlePopconfirm} onClick={this.handlePopconfirm} onConfirm={(e) => this.handleDelete(record, e)} >
              <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
            </Popconfirm>
          ) : record?.statusCode === 'S' ? (
            <span className='span' onClick={(e) => this.handleDelete(record, e)}>还原</span>
          ) : ''}
          <Divider type="vertical" />
          <span className='span' onClick={(e) => this.handleCopy(e, record)}>另存为</span>
        </span>
      ),
    }
    try {
      let data = {
        params: [{
          type: 'C',
          compontName: category === 'orderItem' ? 'OrderItemMaintenance' : 'HospChargeItemMaintenance',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result && 'C' in res.result && Array.isArray(res.result.C) ? res.result.C.map((item, index) => {
        return {
          ...item,
          index,
          render: (text, record) => {
            if (item.dataIndex === 'hospCount') { // 使用医院
              return (
                <span className="span" style={{ padding: '0 6px' }} onClick={(e) => this.handleUsedCountClick(record, e)}>{text}</span>
              );
            }
            return text;
          }
        }
      }) : [];
      if (columns && columns.length > 0) {
        columns.push(operation);
      }
      this.setState({
        columns,
        widthTotal: res.totalWidth
      })
    } catch (error) {
      let staticColumns = [];
      if (category === 'orderItem') {
        staticColumns = [{
          key: 1,
          title: '代码',
          dataIndex: 'medCode',
          align: 'center',
          width: 150
        }, {
          key: 2,
          title: '名称',
          dataIndex: 'medDesc',
          align: 'center',
          width: 300
        }, {
          key: 3,
          title: '价格',
          dataIndex: 'price',
          align: 'center',
          width: 100
        }]
      } else {
        staticColumns = [{
          key: 1,
          title: '代码',
          dataIndex: 'chargeCode',
          align: 'center',
          width: 150
        }, {
          key: 2,
          title: '名称',
          dataIndex: 'chargeDesc',
          align: 'center',
          width: 300
        }, {
          key: 3,
          title: '价格',
          dataIndex: 'chargePrice',
          align: 'center',
          width: 100
        }, {
          key: 4,
          title: '单位',
          dataIndex: 'chargeUnitDesc',
          align: 'center',
          width: 100
        }, {
          key: 5,
          title: '费用归类',
          dataIndex: 'chargeCatDesc',
          align: 'center',
          width: 100
        }, {
          key: 6,
          title: '状态',
          dataIndex: 'status',
          align: 'center',
          width: 100
        }]
      }
      staticColumns.push(operation);
      this.setState({ columns: staticColumns })
    }
  }

  // 导出
  importQuery = () => {
    this.setState({ exportLoading: true }, () => {
      this.exportData();
    })
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1, rowID: '', rowData: {}, loading: true }, () => {
      this.getTableData();
      this.handleResetFields();
    })
  }

  // 提供修改page和pageSize的回调函数
  compilePage = (page, pageSize) => {
    // 修改page，或者pageSize
    this.setState({ page: page, pageSize: pageSize, loading: true, rowID: '', rowData: {} }, () => {
      // 重新调用查询方法
      this.getTableData();
      this.handleResetFields();
    })
  }

  exportData = async (id) => {
    let { category } = this.state;
    let aliasName = category === 'orderItem' ? 'medAlias' : 'alias';
    try {
      let { category, medAlias, pcInput, ordTypeCode, linkNumCode, chargeTCID, contrastStatus, statusID, pageSize, page } = this.state;
      let data = {
        params: [{
          [aliasName]: medAlias,
          pcInput: pcInput, // 物价代码描述
          ordTypeCode: category === 'orderItem' ? ordTypeCode : undefined,
          linkNumCode: category === 'orderItem' ? linkNumCode : undefined,
          chargeTCID: category === 'chargeItem' ? chargeTCID : undefined,
          contrastStatus: category === 'chargeItem' ? contrastStatus : undefined, // 对照状态
          statusID
        }]
      }
      let code = category === 'orderItem' ? '02020399' : (category === 'chargeItem' ? '02020400' : '');
      let res = await React.$asyncPost(this, code, data);

      this.setState({
        allPatData: res.FileURL,
        exportLoading: false
      }, () => this.downloadFile())
    } catch (error) {
      this.setState({
        allPatData: '',
        exportLoading: false
      })
    }
  }

  downloadFile() {
    let windowHost = window.location && window.location.origin ? window.location.origin : (window.location && window.location.protocol ? (window.location.protocol + '//' + window.location.hostname) : "");
    try {
      var elemIF = document.createElement('iframe');

      elemIF.src = windowHost + this.state.allPatData;
      elemIF.style.display = 'none';

      document.body.appendChild(elemIF);

      // 防止下载两次

      setTimeout(function () {

        document.body.removeChild(elemIF)

      }, 1000);

    } catch (e) {

      console.log(e);

    }
  }

  // 请求列表数据
  getTableData = async (id) => {
    let { category } = this.state;
    let aliasName = category === 'orderItem' ? 'medAlias' : 'alias';
    try {
      let { category, medAlias, pcInput, ordTypeCode, linkNumCode, chargeTCID, contrastStatus, statusID, pageSize, page } = this.state;
      let data = {
        params: [{
          [aliasName]: medAlias,
          pcInput: pcInput, // 物价代码描述
          ordTypeCode: category === 'orderItem' ? ordTypeCode : undefined,
          linkNumCode: category === 'orderItem' ? linkNumCode : undefined,
          chargeTCID: category === 'chargeItem' ? chargeTCID : undefined,
          contrastStatus: category === 'chargeItem' ? contrastStatus : undefined, // 对照状态
          statusID
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let code = category === 'orderItem' ? '02020384' : (category === 'chargeItem' ? '02020387' : '');
      let res = await React.$asyncPost(this, code, data);
      let tableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows) : [];
      this.setState({ tableData, total: res.result.total, loading: false }, () => {
        // if (id) { // 新增或编辑时列表不存在这条数据则清空操作
        //   let isReset = true;
        //   for (var i = 0; i < this.state.tableData.length; i++) {
        //     if (String(this.state.tableData[i].medID) === String(id)) {
        //       isReset = false;
        //       break;
        //     }
        //   }
        //   if (isReset && this.state.rowID) { // 重置
        //     this.handleAdd();
        //   } else {
        //     this.setState({ rowID: id }, () => {
        //       this.queryRowDataByID();
        //     }) // 选中行
        //   }
        // }
        id ? this.setState({ rowID: id }, () => {
          this.queryRowDataByID();
        }) : ''; // 选中行
      });
      this.commonChild.handleLoading();
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false })
    }
  }

  // 点击删除时阻止事件冒泡
  handlePopconfirm = (e) => {
    e.stopPropagation();
  };

  // 删除/还原
  handleDelete = async (record, e) => {
    e && e.stopPropagation && e.stopPropagation();
    try {
      let { category, rowID } = this.state;
      let data = {
        params: [{
          hospMedID: category === 'orderItem' ? (record?.hospMedID || '') : undefined,
          chargeHospID: category === 'orderItem' ? undefined : (record?.chargeItemHospID || ''),
          statusCode: record.statusCode === 'U' ? 'S' : 'U', // 更新医嘱状态
        }],
      }
      let res = await React.$asyncPost(this, category === 'orderItem' ? '02020397' : '02020398', data);
      message.success(res && res.errorMessage ? res.errorMessage : '操作成功')
      if (rowID === (category === 'orderItem' ? record.medID : record.chargeItemHospID)) {
        this.handleAdd();
      }
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  }

  // 另存
  handleCopy = (e, record) => {
    e.stopPropagation && e.stopPropagation();
    let { category } = this.state;
    let childName = category + 'Child';
    let rowID = category === 'orderItem' ? record.medID : record.chargeItemHospID;
    this.setState({ rowID: '', rowData: {} }, () => {
      this[childName] && this[childName] && this[childName].queryRowDataByID && this[childName].queryRowDataByID(rowID, true);
    });
  }

  handleOnRef = (ref) => {
    this.commonChild = ref
  }

  // 保存
  handleSave = () => {
    let { category } = this.state;
    let childName = category + 'Child';
    this[childName] && this[childName] && this[childName].handleSave && this[childName].handleSave();
  }

  // 新增医嘱项
  handleAdd = () => {
    this.setState({ rowID: '', rowData: {} });
    this.handleResetFields();
  }

  // 重置
  handleResetFields = () => {
    let { category } = this.state;
    let childName = category + 'Child';
    this[childName] && this[childName] && this[childName].resetFields && this[childName].resetFields();
  }

  // 操作行
  onClickRowPublic = (record) => {
    let { category } = this.state;
    return {
      // 单击行选中
      onClick: () => {
        let rowID = category === 'orderItem' ? record.medID : record.chargeItemHospID;
        if (this.state.rowID === '') {
          this.setState({ rowID, rowData: record }, () => {
            this.queryRowDataByID();
          })
        } else {
          if (this.state.rowID !== rowID) {
            this.setState({ rowID, rowData: record }, () => {
              this.queryRowDataByID();
            })
          } else {
            this.setState({ rowID: '', rowData: {} }, () => {
              this.handleResetFields();
            })
          }
        }
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    let { category } = this.state;
    let rowID = category === 'orderItem' ? record.medID : record.chargeItemHospID;
    return rowID === this.state.rowID ? 'clickRowStyle' : record?.updateFlag === 'N' ? 'oim-record-lose-efficacy' : '';
  }

  // 根据ID查询行数据
  queryRowDataByID = () => {
    let { rowID, category } = this.state;
    let childName = category + 'Child';
    this[childName] && this[childName] && this[childName].queryRowDataByID && this[childName].queryRowDataByID(rowID);
  }

  // 查看使用医院
  handleUsedCountClick = (record, e) => {
    e.stopPropagation();
    let userOrganizationTableData = record?.hospArr || [];
    if (userOrganizationTableData && userOrganizationTableData.length > 0) {
      this.setState({ userOrganizationTableData }, () => {
        this.modalRef && this.modalRef.showModal();
      })
    }
  }

  // 获取使用机构列表表头数据
  getUserOrganizationCloumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'EIGUserOrganization',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      this.setState({
        userOrganizationCloumns: columns
      })
    } catch (error) {
      console.log(error)
    }
  }

  render() {
    let { category, medAlias, pcInput, ordTypeCode, linkNumCode, chargeTCID, contrastStatus, statusID, columns, tableData, totalwidth, total, page, loading, selectData, rowID, rowData, userOrganizationCloumns, userOrganizationTableData } = this.state;
    let componentTitle = category === 'orderItem' ? '医嘱项' : (category === 'chargeItem' ? '收费项' : '');
    // 组件所需参数
    const param = {
      componentName: category === 'orderItem' ? 'OrderItemMaintenance' : 'HospChargeItemMaintenance',
      // 表头配置
      columns: columns,
      // 表格数据
      data: tableData,
      // 数据总条数
      total,
      // 当前页数
      page,
      pageSize: '20',
      loading,
      // 表格的宽度
      x: totalwidth,
      y: store.getState().tableHeight.y + 108 - 102,
      height: store.getState().tableHeight.y + 158 - 102 + 'px',
      isOnRow: true,
      rowClassName: true,
      compontName: category === 'orderItem' ? 'OrderItemMaintenance' : 'HospChargeItemMaintenance'
    };

    const modalParams = {
      isMask: 'Y',
      title: '使用医院列表',
      componentName: 'EIGUserOrganization',
      columns: userOrganizationCloumns, // 使用机构表头数据
      data: userOrganizationTableData,
    };
    return (
      <div className='new-drug-information'>
        <Row className='ndi-header'>
          <Col span={20}>
            代码/描述：<Input
              title="输入内容后可回车检索"
              placeholder="请输入检索条件"
              value={medAlias}
              onChange={Util.commonInputChange.bind(this, 'medAlias')}
              onPressEnter={this.handleQuery}
              style={{ width: '200px', marginRight: '12px' }}
            />
            {/* 通用医嘱项展示医嘱类型及关联收费项数 */}
            {category === 'orderItem' ? (
              <>
                医嘱类型：<Select
                  allowClear
                  showSearch
                  optionFilterProp="seachprop"
                  placeholder="请选择"
                  value={ordTypeCode}
                  onChange={Util.handleSelectChange.bind(this, 'ordTypeCode')}
                  style={{ width: '160px', marginRight: '12px' }}
                >
                  {selectData && selectData.ordType ? React.$SelectOptions(selectData.ordType) : ''}
                </Select>
                关联收费项数：<Select
                  allowClear
                  showSearch
                  optionFilterProp="seachprop"
                  placeholder="请选择"
                  value={linkNumCode}
                  onChange={Util.handleSelectChange.bind(this, 'linkNumCode')}
                  style={{ width: '160px', marginRight: '12px' }}
                >
                  {selectData && selectData.linkNum ? React.$SelectOptions(selectData.linkNum) : ''}
                </Select>
              </>
            ) : (
              <>
                物价信息：<Input
                  title="输入内容后可回车检索"
                  placeholder="输入物价代码/描述检索"
                  value={pcInput}
                  onChange={Util.commonInputChange.bind(this, 'pcInput')}
                  onPressEnter={this.handleQuery}
                  style={{ width: '200px', marginRight: '12px' }}
                />
                收费子类：<Select
                  allowClear
                  showSearch
                  optionFilterProp="seachprop"
                  placeholder="请选择"
                  value={chargeTCID}
                  onChange={Util.handleSelectChange.bind(this, 'chargeTCID')}
                  style={{ width: '160px', marginRight: '12px' }}
                >
                  {selectData && selectData.TC ? React.$SelectOptions(selectData.TC) : ''}
                </Select>
                对照状态：<Select
                  allowClear
                  showSearch
                  optionFilterProp="seachprop"
                  placeholder="请选择"
                  value={contrastStatus}
                  onChange={Util.handleSelectChange.bind(this, 'contrastStatus')}
                  style={{ width: '160px', marginRight: '12px' }}
                >
                  {selectData && selectData.contrastStatus ? React.$SelectOptions(selectData.contrastStatus) : ''}
                </Select>
              </>
            )}
            状态：<Select
              allowClear
              showSearch
              optionFilterProp="seachprop"
              placeholder="请选择"
              value={statusID}
              onChange={Util.handleSelectChange.bind(this, 'statusID')}
              style={{ width: '160px', marginRight: '12px' }}
            >
              {selectData && selectData.status ? React.$SelectOptions(selectData.status) : ''}
            </Select>
            <Button type="primary" onClick={this.handleQuery}>查询</Button>
            <Button type="primary" style={{ marginLeft: '30px' }} onClick={this.importQuery} loading={this.state.exportLoading} >导出</Button>
          </Col>
          <Col span={4} className='ndi-header-right'>
            {/* <Button type="primary" ghost>下载导入模板</Button>
            <Button type="primary" icon="download" ghost>导入</Button>
            <Button type="primary" icon="download" ghost>导出</Button>
            <Button style={{ background: 'rgba(247,128,93,1)', color: '#fff' }}>其他医院复制</Button> */}
          </Col>
        </Row>
        <div style={{ width: '100%', height: '10px', background: '#f0f2f5' }}></div>
        <Row className='ndi-content'>
          <Col span={8}>
            <div
              tabIndex={1}
              onKeyDown={this.handleOnKeydown}
              style={{ outline: 'none', paddingRight: '6px', position: 'relative', height: '100%' }}
            >
              <Card
                size="small"
                className="table-body-height"
                title={(
                  <div className="card-title-left-img ndir-card-heade">
                    <div className="flex-align-items">
                      <img src={iconListvisits} alt="" />{componentTitle}列表
                      <div className="oim-lose-efficacy flex-align-items">
                        【注释：
                        <span></span>
                        多医院使用】
                      </div>
                    </div>
                  </div>
                )}
                extra={(
                  <Button style={{ display: 'none' }} type="primary" ghost>从公共字典选择</Button>
                )}
              >
                {/* handelThis将夫组件的属性与方法给子组件访问 */}
                <PubilcTablePagination
                  param={param}
                  compilePage={this.compilePage}
                  onRef={this.handleOnRef}
                  onClickRowPublic={this.onClickRowPublic}
                  setRowClassNamePublic={this.setRowClassNamePublic}
                  getColumns={this.getTableColumns}
                />
              </Card>
              <div style={{ width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%' }}></div>
            </div>
          </Col>
          <Col span={16}>
            <Card
              size="small"
              title={<div className='card-title-left-img ndir-card-heade'>
                <div className="flex-align-items">
                  <img src={iconListvisits} alt="" />
                  <span style={{ fontWeight: 'bold', color: rowData && rowData.updateFlag === 'N' ? 'red' : '#1890ff' }}>
                    {rowData && rowData.updateFlag === 'N' ? ('【' + ((category === 'orderItem' ? rowData?.medDesc : rowData?.chargeDesc) || '') + '】被多加医院使用，不支持修改相关信息！') : ('正在' + (rowID ? '修改' : '添加') + componentTitle + '……')}
                  </span>
                </div>
                {rowID ? (
                  <Button
                    className="add-btn add-btn-nohover"
                    icon="plus"
                    onClick={this.handleAdd}
                  >新增{componentTitle}</Button>
                ) : ''}
              </div>}
              style={{ height: store.getState().tableHeight.y + 168 + 'px' }}
              className="ndi-card-content"
            >
              {category === 'orderItem' ? (
                <AddOrderItem
                  height={store.getState().tableHeight.y + 40}
                  selectData={selectData}
                  getTableData={this.getTableData}
                  resetFields={this.handleAdd}
                  onRef={ref => this.orderItemChild = ref}
                />
              ) : (
                category === 'chargeItem' ? (
                  <AddChargItem
                    height={store.getState().tableHeight.y + 40}
                    selectData={selectData}
                    getTableData={this.getTableData}
                    resetFields={this.handleAdd}
                    onRef={ref => this.chargeItemChild = ref}
                  />
                ) : ''
              )}

              < div className='ndi-content-footer'>
                {rowID ? (
                  rowData && rowData.updateFlag === 'N' ? (
                    <Popconfirm title="取消修改会导致表单清空，你确定要取消吗?" onConfirm={this.handleAdd} >
                      <Button className='ndi-btn-margin'>取消修改</Button>
                    </Popconfirm>
                  ) : (
                    <Button className='ndi-btn-margin' onClick={this.handleResetFields}>取消修改</Button>
                  )
                ) : (
                  <Button className='ndi-btn-margin' onClick={this.handleResetFields}>清空</Button>
                )}
                <Button disabled={!!(rowData && rowData.updateFlag === 'N')} type="primary" onClick={this.handleSave}>{rowID ? '确认修改' : '保存'}</Button>
              </div>
            </Card>
          </Col>
        </Row>
        <PublicModalTable
          param={modalParams}
          onRef={ref => this.modalRef = ref}
          getColumns={this.getUserOrganizationCloumns}
        />
      </div>
    )
  }
};

export default OrderItemMaintenance;
