/*
 * Create:      柿子
 * CreateDate:  2023/05/29
 * Describe：   硬镜月报
 * */
import React, { Component } from 'react';
import { Card, Button, Icon, Tooltip, Spin, Row, Col, message, Popconfirm, Select } 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 PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import OrderDetailsQuery from 'pages/optometry/component/OrderDetailsQuery';
import iconMessages from 'assets/images/icon_messages.png';
import iconListVisits from 'assets/images/icon_listvisits.png';
import 'pages/dynamicComponent/style/index.less';

class HardMirrorMonthlyReport extends Component {
  constructor(props) {
    super(props);
    this.state = {
      categoryData: {},
      userData: React.$getSessionData(),
      leftCardFlag: false,
      queryHeight: 64, // 查询栏高度
      queryFormData: [],
      selectData: {},
      loading: false,
      tableData: [],
      totalWidth: 0,
      columns: [],
      spinLoading: true,
      exportLoading: false,
      rowID: '',
      rowData: {},
      detailColumns: [],
      detailTotalWidth: 0,
      modalFormData: [],
      detailRowID: '',
      detailLoading: false,
      detailTableData: [],
      modalRowData: {},
      stkSubCatID: undefined,
      brandID: undefined
    }
  }

  componentDidMount() {
    let newCategory;
    if ('paras' in this.props && this.props.paras && this.props.paras.params) { // 侧菜单获取类别参数
      newCategory = this.props.paras.params;
    } else {
      if ('location' in this.props && this.props.location.state && this.props.location.state.params) { // 头菜单获取类别参数
        newCategory = this.props.location.state.params;
        React.$setSessionData('HardMirrorMonthlyReport', newCategory, false);
      } else { // 头菜单刷新界面时获取类别
        newCategory = React.$getSessionData('HardMirrorMonthlyReport', false);
      }
    }
    let categoryData = Util.getObjByUrlStr(newCategory);
    console.log("HardMirrorMonthlyReport", categoryData)
    this.setState({ categoryData }, () => {
      this.getSelectData();
      this.getTableColumns();
      this.getDetailColumns();
    });
  }

  getSelectData = async () => {
    try {
      let { userData, categoryData } = this.state;
      let data = {
        params: [{
          hospID: userData?.hospID || '',
        }]
      }
      let res = await React.$asyncPost(this, categoryData?.selectCode || '17060135', data);
      this.setState({ selectData: res.result });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      const { categoryData } = this.state;
      let data = {
        params: [{
          compontName: categoryData?.componentName || 'HardMirrorMonthlyReport',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
      // 表单操作数据
      let queryFormData = res.result?.formData || [];
      this.setState({ queryFormData }, () => {
        this.setState({ queryHeight: this.queryRef?.current?.clientHeight || 64 });
      });
    } catch (error) {
      console.log(error);
    }
    this.setState({ spinLoading: false }, () => {
      setTimeout(() => {
        this.getTableData();
      }, 300)
    });
  }

  // 获取明细表头数据
  getDetailColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'HardMirrorMonthlyReportDetail',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let detailColumns = res.result?.C || [];
      if (detailColumns && detailColumns.length > 0) {
        for (let i = 0; i < detailColumns.length; i++) {
          let currentDataIndex = detailColumns[i]?.dataIndex || '';
          if (currentDataIndex && currentDataIndex.indexOf('Qty') > -1) {
            detailColumns[i].render = (text, record, index) => {
              return (
                <span className="span" onClick={() => this.handleViewOrderList(record, currentDataIndex)}>{text}</span>
              )
            }
          }
        }
        this.setState({
          detailColumns: React.$obtainHeaderGroupingData(detailColumns),
          detailTotalWidth: res.totalWidth
        });
      }
      // 表单操作数据
      let modalFormData = res.result.formData || [];
      this.setState({ modalFormData });
    } catch (error) {
      console.log(error);
    }
  }

  // 查看订单列表
  handleViewOrderList = (record, dataIndex) => {
    const { categoryData, stkSubCatID, brandID } = this.state;
    if (!!(categoryData?.orderQueryModalCode)) {
      let values = this.queryFormRef && this.queryFormRef.getFieldsValue();
      this.orderQueryRef && this.orderQueryRef.modifyVisible(true, { ...values, record, dataIndex, stkSubCatID, brandID, queryCode: categoryData?.orderQueryModalCode || '' });
    }
  }

  // 请求列表数据
  getTableData = async () => {
    try {
      const { categoryData } = this.state;
      let values = await this.queryFormRef.handleSave();
      if (values.error) {
        message.error('请完善必填信息');
        return;
      }
      this.setState({ loading: true });
      let data = {
        params: [{
          ...values,
        }]
      }
      let res = await React.$asyncPost(this, categoryData?.queryCode || '17060137', 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) {
      console.log(error)
    }
  }

  // 导出
  handleExport = async () => {
    try {
      const { categoryData, rowID, stkSubCatID, brandID } = this.state;
      let idIndex = categoryData?.idIndex || 'key';
      this.setState({ exportLoading: true });
      let data = {
        params: [{
          [idIndex]: rowID,
          stkSubCatID,
          brandID
        }]
      }
      let res = await React.$asyncPost(this, categoryData?.exportCode || '17060140', data);
      handleExcel.downloadExcel(res?.result || res?.FileURL || '');
      this.setState({ exportLoading: false });
    } catch (error) {
      console.log(error);
      this.setState({ exportLoading: false });
    }
  }

  // 控制左侧card显隐
  handleChangeLeftCardFlag = () => {
    this.setState({
      leftCardFlag: !this.state.leftCardFlag
    })
  }

  // 操作行
  onClickRowPublic = (record) => {
    const { categoryData } = this.state;
    let idIndex = categoryData?.idIndex || 'key';
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record[idIndex]))) {
          this.setState({ rowID: record[idIndex], rowData: record }, () => {
            this.queryRowDataByID();
          });
        } else {
          this.handleClearSelectData();
        }
      }
    }
  }

  handleClearSelectData = () => {
    this.setState({ rowID: '', rowData: {}, detailTableData: [], detailRowID: '' })
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    const { categoryData } = this.state;
    let idIndex = categoryData?.idIndex || 'key';
    return record[idIndex] === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 根据行ID获取明细数据
  queryRowDataByID = async () => {
    try {
      const { categoryData, rowID, rowData, stkSubCatID, brandID } = this.state;
      let idIndex = categoryData?.idIndex || 'key';
      let queryDetailCode = categoryData?.queryDetailCode || '17060138';
      if (!queryDetailCode) {
        this.setState({ detailTableData: [rowData] })
        return;
      };
      this.setState({ detailLoading: true });
      let data = {
        params: [{
          [idIndex]: rowID,
          stkSubCatID,
          brandID
        }]
      }
      let res = await React.$asyncPost(this, queryDetailCode, data);
      this.setState({
        detailTableData: Util.addKeyValueToDataSource(res.result?.rows || res.result?.detailInfo || []),
        detailLoading: false
      });
    } catch (error) {
      console.log(error);
      this.setState({ detailLoading: false });
    }
  }

  // 明细行操作
  handleDetailRowClick = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.detailRowID === '' || (this.state.detailRowID && (this.state.detailRowID !== record.key))) {
          this.setState({ detailRowID: record.key });
        } else {
          this.setState({ detailRowID: '' });
        }
      }
    }
  }

  handleDetailRowClassName = (record) => {
    return record.key === this.state.detailRowID ? 'clickRowStyle' : '';
  }

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

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

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

  // 删除
  handleDelete = async (record, e) => {
    try {
      React.$stopPropagation(e);
      const { categoryData } = this.state;
      let idIndex = categoryData?.idIndex || 'id';
      let deleteCode = categoryData?.deleteCode || '02060128';
      let data = {
        params: [{
          [idIndex]: record[idIndex] || '',
        }]
      }
      let res = await React.$asyncPost(this, deleteCode, data);
      message.success(res.errorMessage || '删除成功');
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  }

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

  handleInputChange = (e, dataIndex) => {
    this.state[dataIndex] = e;
    this.setState({}, () => {
      this.queryRowDataByID();
    })
  }

  render() {
    const { categoryData, queryFormData, selectData, loading, tableData, totalWidth, columns, spinLoading, exportLoading, leftCardFlag, queryHeight, modalFormData, detailLoading, detailTableData, detailTotalWidth,
      detailColumns, modalRowData, rowID, stkSubCatID, brandID
    } = this.state;
    let operationObj = {
      width: 80,
      title: '操作',
      fixed: 'right',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <>
          <Icon type="delete" className="common-record-delete-span"></Icon>
          <Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handlePopconfirm} onClick={this.handlePopconfirm} onConfirm={(e) => this.handleDelete(record, e)} >
            <span className="span common-record-delete-span">删除</span>
          </Popconfirm>
        </>
      ),
    }

    let nQueryFormData = queryFormData && queryFormData.length > 0 ? [...queryFormData, {
      col: 2,
      title: '查询',
      typeCode: 'Button',
      type: 'primary',
      marginBottom: 12,
      onClick: this.getTableData,
    }] : [];
    return (
      <Spin tip="正在初始化界面数据……" spinning={spinLoading}>
        <div className="dynamic-component common-voucher-preparation">
          <div ref={this.queryRef} className="cvp-left-card-query">
            <Row style={{ padding: '14px 12px 0 0' }}>
              <Col span={20}>
                <DynamicRenderingForm
                  className="dynamic-component-form"
                  onRef={ref => this.queryFormRef = ref}
                  rowData={{}}
                  selectData={selectData}
                  formData={nQueryFormData && nQueryFormData.map((item => {
                    return {
                      ...item,
                      onPressEnter: this.getTableData
                    }
                  }))}
                />
              </Col>
              <Col span={4} style={{ textAlign: 'right' }}>
                <Button
                  icon="plus"
                  className="add-btn add-btn-nohover"
                  onClick={this.handleAdd}
                >
                  库存报表
                </Button>
              </Col>
            </Row>
          </div>
          <div className="common-query-split-line" style={{ height: 8 }}></div>
          <div style={{ height: store.getState().tableHeight.y + 239 - queryHeight + 'px' }} className="flex">
            {!leftCardFlag ? (
              <Card
                size="small"
                bordered={false}
                className="table-body-height"
                style={{ width: '420px' }}
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListVisits} alt="" />
                    {categoryData?.cardTitle || '库存列表'}
                  </div>
                )}
                extra={(
                  <div onClick={this.handleChangeLeftCardFlag}>
                    <Tooltip title={'隐藏' + (categoryData?.cardTitle || '库存列表')}>
                      <Icon type="double-left" className="cvp-card-hide-icon" />
                    </Tooltip>
                  </div>
                )}
              >
                <PubilcTablePagination
                  param={{
                    loading,
                    columns: columns && columns.length > 0 && categoryData?.deleteCode !== 'none' ? [...columns, operationObj] : columns, // 表头配置
                    componentName: categoryData?.componentName || 'HardMirrorMonthlyReport',
                    pageSize: '20',
                    data: tableData, // 表格数据
                    x: totalWidth, // 表格的宽度
                    y: store.getState().tableHeight.y + 116 - queryHeight,
                    height: store.getState().tableHeight.y + 166 - queryHeight + 'px',
                  }}
                  getColumns={this.getTableColumns}
                  onClickRowPublic={this.onClickRowPublic}
                  setRowClassNamePublic={this.setRowClassNamePublic}
                />
              </Card>
            ) : (
              <Card
                bordered={false}
                style={{ width: '48px', cursor: 'pointer', height: '100%' }}
                className="cvp-hide-modal"
                onClick={this.handleChangeLeftCardFlag}
                title={(
                  <Tooltip title={'展开' + (categoryData?.cardTitle || '库存列表')}>
                    <Icon
                      type="double-right"
                      className="cvp-card-hide-icon cvp-card-show-icon"
                      onClick={this.handleChangeLeftCardFlag}
                    />
                  </Tooltip>
                )}>
                <span>展开{categoryData?.cardTitle || '库存列表'}</span>
              </Card>
            )}
            <div className="common-query-split-line" style={{ width: 8, height: '100%' }}></div>
            <div
              className="common-voucher-preparation-right-card"
              style={{ width: !leftCardFlag ? 'calc(100% - 428px)' : 'calc(100% - 56px)' }}
            >
              <Card
                size="small"
                className="table-body-height"
                bordered={false}
                title={(
                  <div className="flex-align-items">
                    <div style={{ marginRight: '56px' }} className="card-title-left-img">
                      <img src={iconMessages} alt="" />
                      {categoryData?.detailCardTitle || '库存明细'}
                    </div>
                    库存子类：<Select
                      size="small"
                      allowClear
                      showSearch
                      value={stkSubCatID}
                      disabled={!rowID}
                      placeholder="请选择"
                      optionFilterProp="seachprop"
                      className="common-query-input"
                      onChange={(e) => this.handleInputChange(e, 'stkSubCatID')}
                    >
                      {React.$SelectOptions(selectData?.stkSubCat || [])}
                    </Select>
                    品牌：<Select
                      size="small"
                      allowClear
                      showSearch
                      value={brandID}
                      disabled={!rowID}
                      placeholder="请选择"
                      optionFilterProp="seachprop"
                      className="common-query-input"
                      onChange={(e) => this.handleInputChange(e, 'brandID')}
                    >
                      {React.$SelectOptions(selectData?.productBrand || [])}
                    </Select>
                    <Button
                      size="small"
                      type="primary"
                      disabled={!rowID}
                      onClick={this.queryRowDataByID}
                    >
                      查询明细
                    </Button>
                    <Button
                      ghost
                      size="small"
                      type="primary"
                      loading={exportLoading}
                      disabled={!rowID}
                      style={{ marginLeft: '12px' }}
                      onClick={this.handleExport}
                    >
                      {categoryData?.exportBtnTitle || '明细导出'}
                    </Button>
                  </div>
                )}
              >
                <PubilcTablePagination
                  param={{
                    _key: 'HardMirrorMonthlyReportDetail',
                    loading: detailLoading,
                    data: detailTableData, // 表格数据
                    x: detailTotalWidth, // 表格的宽度
                    y: store.getState().tableHeight.y + 116 - queryHeight,
                    height: store.getState().tableHeight.y + 166 - queryHeight + 'px',
                    componentName: 'HardMirrorMonthlyReportDetail',
                    columns: detailColumns, // 表头配置
                  }}
                  getColumns={this.getDetailColumns}
                  onClickRowPublic={this.handleDetailRowClick}
                  setRowClassNamePublic={this.handleDetailRowClassName}
                />
              </Card>
            </div>
          </div>

          {/* 新增弹窗 */}
          <PublicModalFormHooks
            title="新增库存统计报表"
            selectData={selectData}
            rowData={modalRowData}
            formData={modalFormData}
            onRef={ref => this.modalRef = ref}
            recordFormInput={this.recordFormInput}
            handleSave={this.handleSave}
          />

          {/* 订单查询 */}
          <OrderDetailsQuery onRef={ref => this.orderQueryRef = ref} />
        </div>
      </Spin>
    )
  }
};

export default HardMirrorMonthlyReport