/*
 * Create:      柿子
 * CreateDate:  2022/08/23
 * Describe：   库房 - 医院视光产品目录/本院产品目录（视光）
 * */
import React, { Component } from 'react';
import { Tabs, Row, Col, Card, Button, Input, Select, message } from 'antd';
import { Util } from 'tools';
import { handleExcel } from 'tools/handleExcel';
import store from 'store';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import iconListvisits from 'assets/images/icon_listvisits.png';
import './style/index.less';

const { TabPane } = Tabs;

class EssentialInformationHosp extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      userData,
      columns: [],
      totalWidth: 850,
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 10,
      loading: false,
      selectData: {},
      productInfo: undefined,
      stkSubCatID: undefined,
      statusID: '',
      rowID: '',
      rowData: {},
      baseInfoFormData: [], // 基本信息表单数据
      chargesFormData: [], // 收费信息表单数据
      hospInfoFormData: [], // 医院信息表单数据
      exportLoading: false, // 导出loading
      saveLoading: false, // 保存loading
      tabActiveKey: 'N', // 当前选中的tabs
      selectedRows: [],
      selectedRowKeys: [],
    };

    this.staticColumns = [{
      key: 1,
      title: '产品代码',
      dataIndex: 'medCode',
      align: 'center',
      width: 150
    }, {
      key: 2,
      title: '产品名称(医嘱项描述)',
      dataIndex: 'medDesc',
      align: 'center',
      width: 300
    }, {
      key: 3,
      title: '库存子类',
      dataIndex: 'stkSubCatDesc',
      align: 'center',
      width: 100
    }, {
      key: 4,
      title: '入库单位',
      dataIndex: 'medUnitDesc',
      align: 'center',
      width: 100
    }, {
      key: 5,
      title: '状态',
      dataIndex: 'activeStatus',
      align: 'center',
      width: 100
    }, {
      key: 6,
      title: '是否本院',
      dataIndex: 'hosStatus',
      align: 'center',
      width: 100
    }];

    this.staticHospInfoFormData = [{
      dataIndex: 'startDate',
      title: '启用效期',
      typeCode: 'Date',
      required: 'Y',
      col: 8
    }, {
      dataIndex: 'stopDate',
      title: '结束日期',
      typeCode: 'Date',
      col: 8
    }];
  }

  componentDidMount() {
    this.getSelectData();
    this.getTableColumns();
    this.getHospInfoFormData();
  }

  // 获取下拉数据
  getSelectData = async () => {
    try {
      let { userData } = this.state;
      let data = {
        params: [{
          hospID: userData?.hospID || ''
        }]
      }
      let res = await React.$asyncPost(this, '17060007', data);
      this.setState({ selectData: res.result, statusID: res.result?.defaultValue?.defaultStatusID || '' }, () => {
        this.getTableData();
      });
    } catch (error) {
      this.setState({ selectData: {} });
    }
  }

  // 获取表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'EssentialInformationHosp',
          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) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
      // 表单操作数据
      let baseInfoFormData = res.result?.formData || [];
      if (baseInfoFormData && baseInfoFormData.length > 0) {
        this.setState({ baseInfoFormData });
      }
    } catch (error) {
      console.log(error)
    }
  }

  getHospInfoFormData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'EssentialInformationHospOther',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      // 表单操作数据
      let hospInfoFormData = res.result?.formData || [];
      if (hospInfoFormData && hospInfoFormData.length > 0) {
        this.setState({ hospInfoFormData });
      }
    } catch (error) {
      console.log(error)
    }
  }


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

  // 请求列表数据
  getTableData = async (isReset) => {
    try {
      this.setState({ loading: true })
      let { stkSubCatID, statusID, productInfo, tabActiveKey, pageSize, page } = this.state;
      let data = {
        params: [{
          desc: productInfo,
          stkSubCatID,
          statusID,
          hospFlag: tabActiveKey,
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, '17060008', data);
      let dataIndex = tabActiveKey === 'Y' ? 'hosStockID' : 'stockID';
      let tableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows, dataIndex) : [];
      this.setState({ tableData, total: res.result.total, loading: false }, () => {
        isReset === 'Y' ? this.handleResetFields() : '';
      });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false })
    }
  }

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

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.stockID))) {
          this.setState({ rowID: record.stockID }, () => {
            this.queryRowDataByID();
          })
        } else {
          this.setState({ rowID: '' }, () => {
            this.handleResetFields();
          })
        }
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    let { tabActiveKey } = this.state;
    return tabActiveKey === 'N' && record.hosFlag === 'Y' ? (record.stockID === this.state.rowID ? 'elh-table-no-editable clickRowStyle' : 'elh-table-no-editable') : (record.stockID === this.state.rowID ? 'clickRowStyle' : '');
  }

  // 查询明细数据
  queryRowDataByID = async () => {
    try {
      let { rowID } = this.state;
      let data = {
        params: [{
          stockID: rowID
        }]
      }
      let res = await React.$asyncPost(this, '17060009', data);
      // let tip = res.result?.tip || '';
      let tipFlag = res.result?.tipFlag || ''; // 供应商标志 - 没维护需提示让集团去维护
      this.setState({ rowData: res.result });
      // tip && message.warning(tip);
      tipFlag === 'Y' && message.warning(res.result?.vendorDesc || '暂未维护供应商，如需使用，请联系集团维护。');
    } catch (error) {
      this.handleResetFields();
    }
  }

  // 重置操作数据
  handleResetFields = () => {
    this.setState({ rowID: '', rowData: {}, selectedRowKeys: [] });
    this.hospInfoFormRef && this.hospInfoFormRef.resetFields();
  }

  // tabs切换
  handleTabsChange = key => {
    this.setState({ tabActiveKey: key }, () => {
      this.handleQuery();
    })
  }

  // 导出
  handleExport = async () => {
    try {
      this.setState({ exportLoading: true });
      let { stkSubCatID, statusID, productInfo } = this.state;
      let data = {
        params: [{
          desc: productInfo,
          stkSubCatID,
          statusID,
        }]
      }
      let res = await React.$asyncPost(this, '17060006', data);
      handleExcel.downloadExcel(res.result);
      this.setState({ exportLoading: false });
    } catch (error) {
      this.setState({ exportLoading: false });
    }
  }

  // 保存
  handleSave = Util.debounce(async () => {
    try {
      let hospInfoVal = await this.hospInfoFormRef.handleSave();
      if (hospInfoVal && hospInfoVal.error) {
        message.error('请先完善医院信息。');
        return;
      }
      this.setState({ saveLoading: true });
      let { rowData } = this.state;
      let data = {
        params: [{
          ...rowData,
          ...hospInfoVal
        }]
      }
      let res = await React.$asyncPost(this, '17060012', data);
      message.success(res.errorMessage || '保存成功');
      this.setState({ saveLoading: false });
      this.getTableData();
    } catch (error) {
      this.setState({ saveLoading: false });
    }
  })

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

  // 保存到本院
  handleOurHospitalSave = async () => {
    try {
      let { selectedRowKeys } = this.state;
      let data = {
        params: [{
          stockIDArr: selectedRowKeys
        }]
      }
      let res = await React.$asyncPost(this, '17060010', data);
      message.success(res.errorMessage || '保存成功');
      this.getTableData('Y');
    } catch (error) {
      console.log(error)
    }
  }

  // 从本院目录移除
  handlereOurHospitalMove = async () => {
    try {
      let { selectedRowKeys } = this.state;
      let data = {
        params: [{
          hosStockIDArr: selectedRowKeys
        }]
      }
      let res = await React.$asyncPost(this, '17060011', data);
      message.success(res.errorMessage || '移除成功');
      this.getTableData('Y');
    } catch (error) {
      console.log(error)
    }
  }

  // 录入顺序
  handleEntrySequence = (componentName) => {
    this.hospInfoFormRef && this.hospInfoFormRef.showFromMaintenanceModal(componentName);
  }

  render() {
    let { columns, totalWidth, tableData, page, total, loading, selectData, productInfo, stkSubCatID, statusID, rowData, baseInfoFormData, hospInfoFormData, saveLoading,
      tabActiveKey, selectedRowKeys,
    } = this.state;

    let rowSelection = {
      selectedRowKeys,
      onChange: this.handleSelectedRowKeysChange,
      getCheckboxProps: record => ({
        disabled: tabActiveKey === 'N' && record.hosFlag === 'Y' ? true : false,
      }),
    };
    return (
      <div className="essential-information essential-information-hosp">
        <Row>
          <Col span={12}>
            <div
              style={{ paddingRight: '6px', position: 'relative', height: '100%' }}
            >
              <Card
                size="small"
                className="ei-card ei-left-card"
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListvisits} alt="" />
                    产品列表
                  </div>
                )}
              >
                <div>
                  <div className="eih-left-header">
                    <div className="flex-align-items">
                      <span className="common-input-label">产品信息：</span>
                      <Input
                        title="请输入代码/名称回车检索"
                        placeholder="输入代码/名称查询"
                        className="common-query-input"
                        style={{ width: '200px' }}
                        value={productInfo}
                        onChange={Util.commonInputChange.bind(this, 'productInfo')}
                        onPressEnter={this.handleQuery}
                      />
                      <span className="common-input-label">产品子类：</span>
                      <Select
                        allowClear
                        showSearch
                        optionFilterProp="seachprop"
                        placeholder="请选择"
                        className="common-query-input"
                        value={stkSubCatID}
                        onChange={Util.handleSelectChange.bind(this, 'stkSubCatID')}
                      >
                        {selectData && selectData.stkSubCat ? React.$SelectOptions(selectData.stkSubCat) : ''}
                      </Select>
                      <span className="common-input-label">产品状态：</span>
                      <Select
                        allowClear
                        showSearch
                        optionFilterProp="seachprop"
                        placeholder="请选择"
                        className="common-query-input"
                        value={statusID}
                        disabled={tabActiveKey === 'N'}
                        onChange={Util.handleSelectChange.bind(this, 'statusID')}
                      >
                        {selectData && selectData.status ? React.$SelectOptions(selectData.status) : ''}
                      </Select>
                      <Button type="primary" style={{ marginRight: 12 }} onClick={this.handleQuery}>查询</Button>
                      {/* <Button
                        ghost
                        type="primary"
                        loading={exportLoading}
                        onClick={this.handleExport}
                      >
                        {exportLoading ? '导出中……' : '导出'}
                      </Button> */}
                    </div>
                  </div>
                  <div className="common-query-split-line" style={{ height: 8 }}></div>
                  <div style={{ position: 'relative', padding: '0 12px' }}>
                    <Tabs className="eih-tabs" activeKey={tabActiveKey} onChange={this.handleTabsChange}>
                      <TabPane tab="本院目录" key="Y"></TabPane>
                      <TabPane tab="全部目录" key="N"></TabPane>
                    </Tabs>
                    <div className="eih-tabs-btn">
                      {tabActiveKey === 'N' ? (
                        <Button
                          size="small"
                          type="primary"
                          disabled={!(selectedRowKeys && selectedRowKeys.length > 0)}
                          onClick={this.handleOurHospitalSave}
                        >
                          保存到本院
                        </Button>
                      ) : (
                        <Button
                          size="small"
                          type="danger"
                          disabled={!(selectedRowKeys && selectedRowKeys.length > 0)}
                          onClick={this.handlereOurHospitalMove}
                        >
                          从本院移除
                        </Button>
                      )}
                    </div>
                  </div>
                  <div className="eih-table table-body-height">
                    <PubilcTablePagination
                      param={{
                        page,
                        total,
                        loading,
                        data: tableData, // 表格数据
                        x: totalWidth, // 表格的宽度
                        y: store.getState().tableHeight.y - 14,
                        componentName: 'EssentialInformationHosp',
                        height: store.getState().tableHeight.y + 36 + 'px',
                        columns: columns && columns.length > 0 ? columns : this.staticColumns, // 表头配置
                      }}
                      rowSelectionPublic={rowSelection}
                      compilePage={this.compilePage}
                      getColumns={this.getTableColumns}
                      onClickRowPublic={this.onClickRowPublic}
                      setRowClassNamePublic={this.setRowClassNamePublic}
                    />
                  </div>
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={12}>
            <Card
              size="small"
              className="ei-card ei-right-card"
              title={(
                <div className="card-title-left-img">
                  <img src={iconListvisits} alt="" />
                  查看产品详情
                </div>
              )}
            >
              <div className="ei-right-card-content scroll-bar-style" style={{ height: store.getState().tableHeight.y + 136 }}>
                <Card
                  type="inner"
                  size="small"
                  title="基本信息"
                >
                  <DynamicRenderingForm
                    formItemCol={{ labelCol: 11, wrapperCol: 13, col: 8 }}
                    rowData={rowData}
                    formData={baseInfoFormData}
                  />
                </Card>
                <Card
                  type="inner"
                  size="small"
                  title="医院供应商"
                  style={{ margin: '12px 0' }}
                >
                  <span style={{ color: rowData?.tipFlag === 'Y' ? 'red' : '' }}>{rowData?.vendorDesc || '暂无授权信息'}</span>
                </Card>
                <Card
                  type="inner"
                  size="small"
                  title="其他"
                  style={{ display: rowData && rowData.hospFlag === 'Y' ? 'block' : 'none' }}
                  extra={(
                    <Button
                      size="small"
                      onClick={() => this.handleEntrySequence('EssentialInformationHospOther')}
                    >
                      录入顺序
                    </Button>
                  )}
                >
                  <DynamicRenderingForm
                    formItemCol={{ labelCol: 9, wrapperCol: 15 }}
                    rowData={rowData}
                    formData={hospInfoFormData && hospInfoFormData.length > 0 ? hospInfoFormData : this.staticHospInfoFormData}
                    onRef={ref => this.hospInfoFormRef = ref}
                  />
                </Card>
              </div>
              <div className="ei-right-card-footer" style={{ display: rowData && rowData.hospFlag === 'Y' ? 'block' : 'none' }}>
                <div className="ei-right-card-footer-content flex-center">
                  <Button className='ndi-btn-margin' onClick={this.handleResetFields}>取消修改</Button>
                  <Button
                    type="primary"
                    loading={saveLoading}
                    style={{ marginLeft: 12 }}
                    onClick={this.handleSave}
                  >
                    确认修改
                  </Button>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
      </div>
    )
  }
};

export default EssentialInformationHosp;