/*
 * Create:      柿子
 * CreateDate:  2023/11/28
 * Describe：   非定制产品库存盘点
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Button, Input, message, Popconfirm } from 'antd';
import { Util } from 'tools';
import { handleExcel } from 'tools/handleExcel';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import PublicModalQueryTable from 'pages/common/PublicModalQueryTable';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import iconListVisits from 'assets/images/icon_listvisits.png';
import './style/index.less';

class SolutionInventoryCount extends Component {
  constructor(props) {
    super(props);
    this.state = {
      categoryData: {},
      selectData: {},
      page: 1,
      pageSize: 50,
      total: 0,
      loading: false,
      tableData: [],
      rowID: '',
      rowData: {},
      totalWidth: 0,
      columns: [],
      queryFormData: [],
      detailPage: 1,
      detailPageSize: 50,
      detailTotal: 0,
      detailLoading: false,
      detailColumns: [],
      detailTableData: [],
      detailTotalWidth: 0,
      inputDesc: undefined,
      exportLoading: false,
      detailColumnsObj: {}, // 明细表头数据暂存
    }
  }

  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('SolutionInventoryCount', newCategory, false);
      } else { // 头菜单刷新界面时获取类别
        newCategory = React.$getSessionData('SolutionInventoryCount', false);
      }
    }
    let categoryData = Util.getObjByUrlStr(newCategory);
    console.log("SolutionInventoryCount", categoryData);
    this.setState({ categoryData }, () => {
      this.getSelectData();
      this.getTableColumns();
      this.getDetailTableColumns();
    });
  };

  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
  };

  // 获取下拉数据
  getSelectData = async () => {
    try {
      let data = {
        params: [{}]
      }
      let res = await React.$asyncPost(this, '17060198', data);
      this.setState({ selectData: res?.result || {} }, () => {
        setTimeout(() => {
          this.getTableData();
        }, 300)
      });
    } catch (error) {
      console.log(error);
    }
  };

  // 获取表头数据
  getTableColumns = async () => {
    try {
      const { categoryData } = this.state;
      let data = {
        params: [{
          compontName: categoryData?.interfaceType === 'enter' ? 'SolutionInventoryCount' : 'SolutionInventoryCountCompleted',
          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 || [];
      if (queryFormData && queryFormData.length > 0) {
        for (let i = 0; i < queryFormData.length; i++) {
          if (queryFormData[i].dataIndex === 'queryBtn') { // 查询
            queryFormData[i].onClick = this.handleQuery
          }
        }
        this.setState({ queryFormData });
      }
    } catch (error) {
      console.log(error)
    }
  };

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

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

  // 获取明细列表数据
  getTableData = async (isClear) => {
    try {
      let values = await this.queryFormRef.handleSave();
      if (values.error) {
        message.error('请完善必填信息!');
        return;
      }
      isClear !== 'N' && this.setState({ loading: true });
      const { page, pageSize } = this.state;
      let data = {
        params: [{
          ...values
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
        }]
      }
      let res = await React.$asyncPost(this, '17060201', data);
      let tableData = Util.addKeyValueToDataSource(res?.result?.rows || []);
      this.setState({ tableData, total: res?.result?.total || 0, loading: false }, () => {
        isClear !== 'N' ? this.handleResetFields() : this.getDetailTableData('N');
      });
    } catch (error) {
      console.log(error);
      this.setState({ loading: false });
    }
  };

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

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

  handleResetFields = () => {
    this.setState({ rowID: '', rowData: {}, detailTableData: [], detailTotal: 0 });
  };

  // 获取明细表头数据
  getDetailTableColumns = async () => {
    try {
      const { rowData, detailColumnsObj } = this.state;
      let componentName = rowData?.methods === 'B' ? 'SolutionInventoryCountDetailBatch' : 'SolutionInventoryCountDetail';
      // 暂存表头数据
      if (detailColumnsObj && componentName in detailColumnsObj && detailColumnsObj[componentName] && Array.isArray(detailColumnsObj[componentName]) && detailColumnsObj[componentName].length > 0) {
        let copyDetailColumns = detailColumnsObj[componentName];
        let copyDetailTotalWidth = detailColumnsObj[componentName + 'TotalWidth']
        this.handleFilterDetailColumns(copyDetailColumns, copyDetailTotalWidth);
        return;
      }
      let data = {
        params: [{
          compontName: componentName,
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.state.detailColumnsObj[componentName] = columns;
        this.state.detailColumnsObj[componentName + 'TotalWidth'] = res.totalWidth;
        let detailColumns = columns;
        let detailTotalWidth = res.totalWidth
        this.handleFilterDetailColumns(detailColumns, detailTotalWidth);
      }
      // 表单操作数据
      let detailQueryFormData = res.result?.formData || [];
      if (detailQueryFormData && detailQueryFormData.length > 0) {
        this.setState({ detailQueryFormData });
      }
    } catch (error) {
      console.log(error)
    }
  };

  handleFilterDetailColumns = (columns, totalWidth) => {
    const { categoryData } = this.state;
    if (categoryData?.interfaceType === 'enter') {
      for (let i = 0; i < columns.length; i++) {
        columns[i].render = (text, record, index) => this.handleRenderInput(text, record, index, columns[i])
      }
    }
    this.setState({ detailColumns: columns, detailTotalWidth: totalWidth });
  }

  handleRenderInput = (text, record, index, colItem) => {
    const { rowData } = this.state;
    let dataIndex = colItem?.dataIndex || '';
    if (colItem?.linkMethod === 'Input') {
      return (
        <Input
          allowClear
          style={{ width: '90%' }}
          placeholder="请输入"
          disabled={!(rowData?.statusID === '10')}
          value={record && dataIndex in record ? record[dataIndex] : undefined}
          ref={ref => this[dataIndex + index] = ref}
          onChange={(e) => this.handleInputChange(e.target.value, record, dataIndex)}
          onKeyDown={(e) => this.handleKeyDown(dataIndex, index, colItem, e)}
        />
      )
    } else if (colItem?.linkMethod === 'InputNumber') {
      return (
        <Input
          allowClear
          type="number"
          className="input-number"
          placeholder="请输入"
          style={{ width: '90%' }}
          disabled={!(rowData?.statusID === '10')}
          value={record && dataIndex in record ? record[dataIndex] : undefined}
          ref={ref => this[dataIndex + index] = ref}
          onChange={(e) => this.handleInputChange(e.target.value, record, dataIndex)}
          onKeyDown={(e) => this.handleKeyDown(dataIndex, index, colItem, e)}
        />
      )
    } else {
      return text;
    }
  };

  // 修改输入域的值
  handleInputChange = (val, record, dataIndex) => {
    record[dataIndex] = val;
    this.setState({});
  };

  //列跳转设置
  handleKeyDown = (dataIndex, index, item, e) => {
    if (e.keyCode == '13' || e.keyCode == '40') { // 回车和右箭头 
      e?.preventDefault();
      this.getNextJumpAbleRowSubscript(index, item, 'next', e);
    } else if (e.keyCode == '38') { // 光标上移
      e?.preventDefault();
      this.getNextJumpAbleRowSubscript(index, item, 'prev', e);
    }
  };

  // 获取下一个可跳转的行下标并跳转
  getNextJumpAbleRowSubscript = (index, item, type, e) => {
    const { detailTableData } = this.state;
    if ((index < 0 && type === 'prev') || (detailTableData.length < index && type === 'next')) {
      return;
    }
    if (type === 'prev') {
      index = index - 1;
    } else {
      index = index + 1;
    }
    let nextDataIndex = item?.dataIndex || 'qty';
    if (nextDataIndex) {
      let currentDataIndex = nextDataIndex + index;
      nextDataIndex && this[currentDataIndex] && this[currentDataIndex].focus ? this[currentDataIndex].focus() : '';
    }
  };

  handleDetailRowClassName = (record) => {
    let ret = '';
    if (record?.qty !== undefined && record?.qty !== '' && record?.qty !== null) { // 【盘点数量】存在的时候才显示相关盘点状态
      if (parseInt(record?.difQty || 0) > 0) {
        ret = 'inventory-profit'
      } else if (parseInt(record?.difQty || 0) < 0) {
        ret = 'inventory-loss'
      }
    }
    return ret;
  };

  handleCompileDetailPage = (page, pageSize) => {
    this.setState({ detailPage: page, detailPageSize: pageSize }, () => {
      this.getDetailTableData();
    })
  };

  handleDetailQuery = () => {
    this.setState({ detailPage: 1 }, () => {
      this.getDetailTableData();
    })
  };

  // 获取明细列表数据
  getDetailTableData = async (isLoading) => {
    try {
      const { rowID, inputDesc, detailPageSize, detailPage } = this.state;
      isLoading !== 'N' && this.setState({ detailLoading: true });
      let data = {
        params: [{
          metStkTakeID: rowID,
          inputDesc
        }],
        pagination: [{
          pageSize: detailPageSize,
          currentPage: detailPage,
        }]
      }
      let res = await React.$asyncPost(this, '17060202', data);
      let detailTableData = Util.addKeyValueToDataSource(res?.result?.rows || []);
      this.setState({ detailTableData, detailTotal: res?.result?.total || 0, detailLoading: false });
    } catch (error) {
      console.log(error);
      this.setState({ detailLoading: false });
    }
  };

  // 保存
  handleSave = async () => {
    try {
      const { rowID, detailTableData } = this.state;
      let detailArr = detailTableData && detailTableData.map(item => {
        return {
          detailID: item?.detailID || '',
          qty: item && 'qty' in item ? item.qty : ''
        }
      });
      let data = {
        params: [{
          metStkTakeID: rowID,
          detailArr
        }]
      }
      let res = await React.$asyncPost(this, '17060203', data);
      message.success(res?.errorMessage || '保存成功');
      this.getTableData('N');
    } catch (error) {
      console.log(error);
    }
  };

  // 新增
  handleAdd = () => {
    const { selectData } = this.state;
    this.addInventoryListRef && this.addInventoryListRef.modifyVisible(true, { selectData });
  };

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

  // 填充方式
  handleFillStyle = async (mode) => {
    try {
      const { rowID } = this.state;
      let data = {
        params: [{
          metStkTakeID: rowID,
          defualtType: mode
        }]
      }
      let res = await React.$asyncPost(this, '17060209', data);
      message.success(res?.errorMessage || '填充成功');
      this.getTableData('N');
    } catch (error) {
      console.log(error);
    }
  };

  // 保存盘点单
  handleInventoryListSave = async (tableList, queryVal) => {
    try {
      let data = {
        params: [{
          ...queryVal
        }]
      }
      let res = await React.$asyncPost(this, '17060200', data);
      message.success(res?.errorMessage || '保存成功');
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  }

  // 调整库存
  handleAdjustingInventory = async () => {
    try {
      const { rowID } = this.state;
      let data = {
        params: [{
          metStkTakeID: rowID,
        }]
      }
      let res = await React.$asyncPost(this, '17060207', data);
      message.success(res?.errorMessage || '调整成功');
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  }

  // 完成 | 取消完成
  handleComplete = async (code) => {
    try {
      const { rowID } = this.state;
      let data = {
        params: [{
          metStkTakeID: rowID,
        }]
      }
      let res = await React.$asyncPost(this, code, data);
      message.success(res?.errorMessage || '操作成功');
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  }

  // 导出
  handleExport = async () => {
    try {
      this.setState({ exportLoading: true });
      const { rowID, inputDesc, detailPageSize, detailPage } = this.state;
      let data = {
        params: [{
          metStkTakeID: rowID,
          inputDesc
        }],
        pagination: [{
          pageSize: detailPageSize,
          currentPage: detailPage,
        }]
      }
      let res = await React.$asyncPost(this, '17060208', data);
      handleExcel.downloadExcel(res.result);
      this.setState({ exportLoading: false });
    } catch (error) {
      this.setState({ exportLoading: false });
    }
  }

  render() {
    const { queryFormData, selectData, rowID, rowData, page, total, loading, tableData, totalWidth, columns, detailPage, detailTotal, detailLoading, detailColumns, detailTableData, detailTotalWidth, inputDesc, exportLoading,
      categoryData
    } = this.state;

    return (
      <div className="solution-inventory-count dynamic-component">
        <Row style={{ paddingTop: '14px' }}>
          <Col span={18}>
            <DynamicRenderingForm
              className="dynamic-component-form"
              rowData={{}}
              selectData={selectData}
              formData={queryFormData}
              onRef={ref => this.queryFormRef = ref}
            />
          </Col>
          <Col span={6} style={{ textAlign: 'right', paddingRight: '12px' }}>
            {categoryData?.interfaceType === 'enter' ? ( // 生产与录入
              <>
                <Button icon="plus" className="add-btn add-btn-noHover" onClick={this.handleAdd}>新增</Button>
                <Button type="primary" style={{ margin: '0 20px' }} disabled={!(rowID && rowData?.statusID === '10')} onClick={this.handleSave}>保存</Button>
                <Popconfirm
                  placement="bottomRight"
                  title="删除不可恢复，你确定要删除吗?"
                  disabled={!rowID && rowData?.statusID === '10'}
                  onConfirm={this.handleDelete}
                >
                  <Button ghost type="danger" disabled={!(rowID && rowData?.statusID === '10')}>删除</Button>
                </Popconfirm>
              </>
            ) : ( // 完成与汇总
              <>
                <Button type="primary" disabled={!(rowID && rowData?.statusID === '20')} onClick={this.handleAdjustingInventory}>调整库存</Button>
                <Button type="primary" style={{ margin: '0 20px' }} disabled={!(rowID && rowData?.statusID === '10')} onClick={() => this.handleComplete('17060204')}>完成</Button>
                <Popconfirm
                  placement="bottomRight"
                  title="你确定要取消完成吗?"
                  disabled={!(rowID && rowData?.statusID === '20')}
                  onConfirm={() => this.handleComplete('17060205')}
                >
                  <Button ghost type="danger" disabled={!(rowID && rowData?.statusID === '20')}>取消完成</Button>
                </Popconfirm>
                <Popconfirm
                  placement="bottomRight"
                  title="删除不可恢复，你确定要删除吗?"
                  disabled={!(rowID && rowData?.statusID === '10')}
                  onConfirm={this.handleDelete}
                >
                  <Button ghost type="danger" style={{ margin: '0 20px' }} disabled={!(rowID && rowData?.statusID === '10')}>删除</Button>
                </Popconfirm>
                <Button ghost type="primary" disabled={!rowID} loading={exportLoading} onClick={this.handleExport}>导出</Button>
              </>
            )}
          </Col>
        </Row>
        <div className="common-query-split-line" style={{ height: 8 }}></div>
        <Row>
          <Col span={8}>
            <div
              style={{ paddingRight: '6px', position: 'relative', height: '100%' }}
            >
              <Card
                size="small"
                bordered={false}
                bodyStyle={{ padding: 0 }}
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListVisits} alt="" />
                    盘点单据
                  </div>
                )}
              >
                <div style={{ padding: '12px' }} className="table-body-height">
                  <PublicTablePagination
                    param={{
                      size: 'large',
                      page,
                      total,
                      loading,
                      columns,
                      data: tableData, // 表格数据
                      x: totalWidth, // 表格的宽度
                      y: store.getState().tableHeight.y + 24,
                      componentName: categoryData?.interfaceType === 'enter' ? 'SolutionInventoryCount' : 'SolutionInventoryCountCompleted',
                      height: store.getState().tableHeight.y + 74 + 'px',
                    }}
                    compilePage={this.compilePage}
                    getColumns={this.getTableColumns}
                    onClickRowPublic={this.onClickRowPublic}
                    setRowClassNamePublic={this.setRowClassNamePublic}
                  />
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={16}>
            <Card
              size="small"
              bordered={false}
              title={(
                <div className="card-title-left-img">
                  <img src={iconListVisits} alt="" />
                  盘点单明细
                </div>
              )}
              extra={(
                <span style={{ color: '#999', fontSize: '12px', fontWeight: 'normal' }}>
                  <span style={{ backgroundColor: 'rgba(0, 255, 42, 0.23)' }} className="common-record-color-notes-rect"></span>
                  盘盈
                  <span style={{ backgroundColor: 'rgba(255, 0, 0, 0.38)', marginLeft: '20px' }} className="common-record-color-notes-rect"></span>
                  盘亏
                </span>
              )}
            >
              <div>
                {categoryData?.interfaceType === 'enter' ? (
                  <div style={{ marginBottom: '12px' }}>
                    {rowID && (
                      <span style={{ marginRight: '48px' }}>
                        当前单据录入方式：{rowData?.methodsDesc || ''}
                      </span>
                    )}
                    <Button
                      style={{ marginRight: '12px', width: '120px' }}
                      disabled={!(rowID && rowData?.statusID === '10')}
                      onClick={() => this.handleFillStyle('1')}
                    >
                      以冻结数填充
                    </Button>
                    <Button
                      style={{ marginRight: '48px', width: '120px' }}
                      disabled={!(rowID && rowData?.statusID === '10')}
                      onClick={() => this.handleFillStyle('0')}
                    >
                      以0填充
                    </Button>
                    别名：
                    <Input
                      style={{ width: '250px' }}
                      placeholder="输入库存项代码/描述检索"
                      value={inputDesc}
                      onChange={Util.commonInputChange.bind(this, 'inputDesc')}
                      onPressEnter={this.handleDetailQuery}
                    />
                  </div>
                ) : ''}
                <div className="table-body-height">
                  <PublicTablePagination
                    param={{
                      size: 'large',
                      page: detailPage,
                      total: detailTotal,
                      loading: detailLoading,
                      columns: detailColumns,
                      data: detailTableData, // 表格数据
                      x: detailTotalWidth, // 表格的宽度
                      y: store.getState().tableHeight.y - (categoryData?.interfaceType === 'enter' ? 22 : -24),
                      componentName: rowData?.methods === 'B' ? 'SolutionInventoryCountDetailBatch' : 'SolutionInventoryCountDetail',
                      height: store.getState().tableHeight.y + (categoryData?.interfaceType === 'enter' ? 28 : 74) + 'px',
                    }}
                    compilePage={this.handleCompileDetailPage}
                    getColumns={this.getDetailTableColumns}
                    setRowClassNamePublic={this.handleDetailRowClassName}
                  />
                </div>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 新增盘点单 */}
        <PublicModalQueryTable
          okText="保存"
          title="新增盘点单"
          queryCode="17060199"
          autoQueryFlag="N"
          width="70vw"
          paginationFlag="Y"
          doubleRecordFlag="N"
          tableHeight={store.getState().tableHeight.y - 148}
          componentName="SolutionInventoryCountAddModal"
          onRef={ref => this.addInventoryListRef = ref}
          handleOk={this.handleInventoryListSave}
        />
      </div>
    );
  }
};

export default SolutionInventoryCount;