/*
 * Create:      柿子
 * CreateDate:  2022/11/22
 * Describe：   从品牌库选择
 * */
import React, { Component } from 'react';
import { Modal, Input, Tooltip, Button, message, Select } from 'antd';
import { Util } from 'tools';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import '../style/index.less';

class SelectFromBrandLibrary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      selectData: {},
      loading: false,
      tableData: [],
      columns: [],
      totalWidth: 1200,
      page: 1,
      total: 0,
      vendorID: '',
      brandID: undefined,
      productNo: undefined,
      selectedRowKeys: [],
      selectedRows: []
    }
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
  }

  // 修改弹窗状态
  modifyVisible = (visible, vendorID, selectData, columns, totalWidth) => {
    if (visible) {
      if (columns && columns.length > 0) {
        this.setState({ columns, totalWidth })
      } else {
        this.getTableColumns();
      }
    }
    this.setState({ visible, vendorID, selectData }, () => {
      if (this.state.visible) {
        this.getTableData();
      }
    });
  }

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'SelectFromBrandLibrary',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result && Array.isArray(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 })
      }
    } catch (error) {
      console.log(error)
    }
  }

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

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

  // 获取列表数据
  getTableData = async () => {
    try {
      this.setState({ loading: true });
      const { vendorID, brandID, productNo } = this.state;
      let data = {
        params: [{
          brandID,
          vendorID,
          linkFlag: 'N', // 是否查询已关联的
          inputDesc: productNo,
        }]
      }
      let res = await React.$asyncPost(this, '17060027', data);
      let tableData = Util.addKeyValueToDataSource(res.result?.rows || [], 'stockID');
      this.setState({ tableData, total: res.result?.total || 0, loading: false, selectedRowKeys: [] })
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false, selectedRowKeys: [] })
    }
  }

  // 确定选择
  handleOk = async () => {
    try {
      const { selectedRowKeys, selectedRows } = this.state;
      if (!(selectedRowKeys && selectedRowKeys.length > 0)) {
        message.error('请选择需要关联的产品');
        return;
      }
      this.props.addProductData && this.props.addProductData(selectedRows);
      this.modifyVisible(false);
      this.setState({ selectedRowKeys: [], selectedRows: [] });
    } catch (error) {
      console.log(error);
    }
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      onDoubleClick: () => {
        this.setState({ selectedRowKeys: [record.stockID], selectedRows: [{ ...record }] }, () => {
          this.handleOk();
        })
      }
    }
  }

  render() {
    const { visible, loading, tableData, columns, totalWidth, brandID, productNo, selectData, selectedRowKeys } = this.state;
    // 列表多选操作
    let rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows,
          selectedRowKeys,
        })
      },
    };
    return (
      <Modal
        width="1200px"
        title="从产品库选择"
        className="select-from-brand-library"
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => this.modifyVisible(false)}
      >
        <div className="table-body-height">
          <div style={{ marginBottom: 12 }}>
            品牌：<Select
              allowClear
              showSearch
              placeholder="请选择"
              optionFilterProp="search"
              className="common-query-input"
              style={{ width: '200px' }}
              value={brandID}
              onChange={Util.handleSelectChange.bind(this, 'brandID')}
            >
              {React.$SelectOptions(selectData?.brand || [])}
            </Select>
            产品信息：<Input
              placeholder="输入代码/名称/描述查询"
              className="common-query-input"
              style={{ width: '200px' }}
              value={productNo}
              onPressEnter={this.handleQuery}
              onChange={Util.commonInputChange.bind(this, 'productNo')}
            />
            <Button type="primary" onClick={this.handleQuery}>查询</Button>
          </div>
          <PubilcTablePagination
            param={{
              // page,
              // total,
              loading,
              // pageSize: '20',
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              y: 350,
              height: 400,
              componentName: 'SelectFromBrandLibrary',
              columns: columns && columns.length > 0 ? columns : [], // 表头配置
            }}
            rowSelectionPublic={rowSelection}
            // compilePage={this.compilePage}
            getColumns={this.getTableColumns}
            onClickRowPublic={this.onClickRowPublic}
          />
        </div>
      </Modal>
    )
  }
};

export default SelectFromBrandLibrary;