/*
 * Creater:     柿子
 * CreateDate:  2023/05/23
 * Describe：   弹窗查询列表【table单击行勾选示例】
 * */
import React, { Component } from 'react';
import { Modal, Button, Popconfirm, Input, Select } from 'antd';
import { Util } from 'tools';
import DynamicRenderingForm from './DynamicRenderingForm';
import PublicTablePagination from './PubilcTablePagination';
import ColorPickup from 'pages/emr/component/ColorPickup';
// import 'pages/dynamicComponent/style/index.less';

class PublicModalQueryTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      queryFormData: [],
      queryFormFlag: 'Y', // 表单是否显示，Y：显示 N：不显示
      page: 1,
      pageSize: props?.defaultPageSize || 20,
      total: 0,
      loading: false,
      dynamicParams: {},
      tableData: [],
      copyTableData: [],
      totalWidth: 0,
      columns: [],
      rowID: '',
      rowData: {},
      selectData: {},
      selectedRows: [],
      selectedRowKeys: [],
      isColorPickup: false,
      pickupTop: 0,
      pickupLeft: 0,
    };
  };

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

  // 修改弹窗状态
  modifyVisible = (visible, params = {}) => {
    const { columns } = this.state;
    this.setState({ visible, ...params, queryFormFlag: params?.queryFormFlag || 'Y' }, () => {
      if (visible && !(columns && columns.length > 0) && params?.getColumnsFlag !== 'N') {
        this.getTableColumns();
      }
      setTimeout(() => {
        visible && this.props.autoQueryFlag !== 'N' && params?.autoQueryFlag !== 'N' && this.getTableData();
      }, 300)
    })
  };

  // 获取列表表头数据
  getTableColumns = async () => {
    try {
      const { componentName } = this.props;
      if (!componentName) 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) {
        const { selectData } = this.state;
        columns = columns.map(item => {
          let dataIndex = item?.dataIndex || '';
          return {
            ...item,
            render: (text, record, index) => {
              if (item?.linkMethod === 'Input') {
                return (
                  <Input
                    allowClear
                    placeholder="请输入"
                    style={{ width: '96%' }}
                    value={record && dataIndex in record ? record[dataIndex] : undefined}
                    onChange={(e) => this.handleInputChange(index, e.target.value, item, record, e)}
                    onClick={(e) => React.$stopPropagation(e)}
                  />
                );
              } else if (item?.linkMethod === 'Select' || item?.linkMethod === 'SelectBox') {
                let selectAttr = { // 下拉框属性
                  allowClear: true,
                  showSearch: true,
                  style: { width: '96%' },
                  placeholder: '请选择',
                  optionFilterProp: 'search',
                  value: record && dataIndex in record ? record[dataIndex] : undefined,
                  mode: item?.linkMethod === 'SelectBox' ? 'multiple' : (item && item.mode ? item.mode : null), // mode="multiple" 多选
                  onChange: (e) => this.handleInputChange(index, e, item, record, e),
                  onClick: (e) => React.$stopPropagation(e)
                };
                let selectOption = item && item.linkService && selectData[item.linkService] && Array.isArray(selectData[item.linkService]) ? React.$SelectOptions(selectData[item.linkService]) : '';
                return (
                  <Select {...selectAttr}>
                    {selectOption}
                  </Select>
                );
              } else if (item?.linkMethod === 'ColorPickup') {
                return (
                  <div style={{ height: '100%', width: '100%' }} className="flex-center">
                    <span
                      style={{ width: '18px', height: '18px', backgroundColor: text }}
                      id={'pmqt-color-pickup-' + index}
                      className="common-record-color-notes"
                      onClick={(e) => this.handleShowColorTemplate('pmqt-color-pickup-' + index, { ...item, recordData: record, recordIndex: index }, e)}
                    ></span>
                  </div>
                );
              } else {
                return text;
              }
            },
          }
        })
        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]?.className === 'staticFilter') { // 本地过滤列表数据
            queryFormData[i].onPressEnter = this.handleQuery
          }
        }
        this.setState({ queryFormData });
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 修改入参
  handleInputChange = (index, val, item, record, e) => {
    React.$stopPropagation(e)
    let dataIndex = item?.dataIndex || '';
    record[dataIndex] = val;
    this.setState({});
  };

  getOperationObj = (dataIndex) => {
    // 列表操作
    const operationObj = {
      width: 80,
      key: 'operation',
      title: '操作',
      align: 'center',
      render: (text, record, index) => this.handleRenderMoveBtn(text, record, index, dataIndex)
    };
    return operationObj;
  };

  // 渲染移动按钮
  handleRenderMoveBtn = (text, record, index, dataIndex) => {
    const { moveUpDesc, moveDownDesc } = this.props;
    let tableLen = this.state[dataIndex]?.length || 0;
    return (
      <>
        <Button
          type="link"
          size="small"
          disabled={index === 0}
          onClick={(e) => this.handleMove(record, 'up', dataIndex, e)}
        >
          {moveUpDesc || '上移'}
        </Button>
        <Button
          type="link"
          size="small"
          disabled={index >= tableLen - 1}
          onClick={(e) => this.handleMove(record, 'down', dataIndex, e)}
        >
          {moveDownDesc || '下移'}
        </Button>
      </>
    )
  };

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

  handleMove = (record, direction, dataIndex, e) => {
    React.$stopPropagation(e);
    const { priorityIndex } = this.props;
    let tableData = this.state[dataIndex];
    const rowKey = record?.seqNo;
    const currentIndex = tableData.findIndex(item => item.seqNo === rowKey);
    if (direction === 'up' && currentIndex > 0) {
      [tableData[currentIndex - 1], tableData[currentIndex]] = [tableData[currentIndex], tableData[currentIndex - 1]];
      // 更新key值
      tableData[currentIndex].seqNo = currentIndex;
      tableData[currentIndex - 1].seqNo = currentIndex - 1;
    } else if (direction === 'down' && currentIndex < (tableData.length - 1)) {
      [tableData[currentIndex + 1], tableData[currentIndex]] = [tableData[currentIndex], tableData[currentIndex + 1]];
      // 更新key值
      tableData[currentIndex].seqNo = currentIndex;
      tableData[currentIndex + 1].seqNo = currentIndex + 1;
    }
    if (priorityIndex) { // 界面展示的序号【优先级序号】
      for (let i = 0; i < tableData.length; i++) {
        tableData[i][priorityIndex] = i + 1;
      }
    }
    this.state[dataIndex] = tableData;
    this.setState({});
  };

  // 请求列表数据
  getTableData = async () => {
    try {
      const { queryCode, staticParams, paginationFlag, idIndex = 'key', operationFlag } = this.props;
      let { queryFormData, pageSize, page, dynamicParams = {} } = this.state;
      let values = {};
      if (queryFormData && queryFormData.length > 0) {
        values = await this.queryFormRef.handleSave();
        if (values.error) {
          message.error('请完善必填信息');
          return;
        }
      }
      if (!queryCode) {
        message.error('请配置查询代码');
        return;
      };
      if (queryCode === 'staticFilter') { // 静态过滤
        let { copyTableData } = this.state;
        let tableData = [];
        for (let key in values) {
          if (values[key] !== undefined && values[key] !== false && values[key] !== null) {
            tableData = copyTableData.filter(item => item?.staticFilter.indexOf(values[key]) > -1);
          }
        }
        this.setState({ tableData });
        return;
      }
      this.setState({ loading: true });
      let data = {
        params: [{
          ...staticParams,
          ...dynamicParams,
          ...values,
        }]
      }
      if (paginationFlag === 'Y') {
        data.pagination = [{
          pageSize,
          currentPage: page
        }];
      }
      let res = await React.$asyncPost(this, queryCode, data);
      let tableData = Util.addKeyValueToDataSource(res.result?.rows || res.result?.detailInfo || res.result?.data || res.result?.Data || res?.result || [], idIndex);
      if (operationFlag === 'Y') {
        for (let i = 0; i < tableData.length; i++) {
          tableData[i].seqNo = i;
        }
      }
      this.setState({ tableData, total: res.result?.total || res.result?.totalCount || res.result?.TotalCount || tableData.length, loading: false, }, () => {
        this.handleClear();
      });
    } catch (error) {
      console.log('error', error);
      this.setState({ loading: false });
    }
  };

  // 关闭弹窗
  handleCancel = (isClear) => {
    this.modifyVisible(false);
    this.props.handleCancelCallback && this.props.handleCancelCallback();
    isClear === 'Y' && this.handleClear();
  };

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

  // 操作行
  onClickRowPublic = (record) => {
    const { idIndex = 'key', mutualExclusionFlag, rowClickFlag } = this.props;
    return {
      // 单击行选中
      onClick: () => {
        if (rowClickFlag !== 'N') {
          if (mutualExclusionFlag === 'Y') { // 多选选择一个标识
            if (this.state.rowID === '') {
              this.setState({
                rowID: record[idIndex],
                rowData: record,
              });
            } else {
              if (this.state.rowID !== record[idIndex]) {
                this.setState({
                  rowID: record[idIndex],
                  rowData: record,
                });
              } else {
                this.setState({
                  rowID: '',
                  rowData: {},
                });
              }
            }
          } else {
            let { selectedRowKeys, selectedRows } = this.state;
            let findFlag = false;
            let start = 0;
            if (selectedRowKeys) {
              selectedRowKeys.find(function (value, key) {
                if (value === record[idIndex]) {
                  findFlag = true;
                  start = key;
                }
              })
            }
            if (findFlag) {
              //再次点击移除选中
              selectedRowKeys.splice(start, 1);
              selectedRows.splice(start, 1);
            } else {
              //将点击的行添加到选中
              selectedRowKeys.push(record[idIndex]);
              selectedRows.push(record);
            }
            if (this.state.rowID === '') {
              this.setState({
                rowID: record[idIndex],
                rowData: record,
                selectedRowKeys,
                selectedRows
              });
            } else {
              if (this.state.rowID !== record[idIndex]) {
                this.setState({
                  rowID: record[idIndex],
                  rowData: record,
                  selectedRowKeys,
                  selectedRows
                });
              } else {
                this.handleClear();
              }
            }
          }
        }
      },
      onDoubleClick: () => {
        this.props?.doubleRecordFlag !== 'N' && this.handleOk(record, 'doubleClick')
      }
    }
  };

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

  handleOk = async (record, type) => {
    const { multipleFlag, idIndex = 'id', autoClose = 'Y' } = this.props;
    const { rowData, selectedRowKeys, queryFormData } = this.state;
    let queryVal = {};
    if (queryFormData && queryFormData.length > 0) {
      queryVal = await this.queryFormRef.handleSave();
    }
    autoClose !== 'N' && this.modifyVisible(false); // 点完成是否自动关闭弹窗
    let data = {};
    if (multipleFlag === 'Y') {
      let nSelectedRowKeys = type === 'doubleClick' ? [record[idIndex]] : selectedRowKeys;
      data[idIndex + 'Arr'] = nSelectedRowKeys;
      data.selectedRowKeys = nSelectedRowKeys;
      data.selectedRows = this.filterSelectRowData(nSelectedRowKeys);
      data.queryVal = queryVal;
    } else {
      data = type === 'doubleClick' ? record : rowData;
    }
    this.props.handleOk && this.props.handleOk(data, queryVal);
  };

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

  handleCheckChange = (record, selected) => {
    const { idIndex = 'key' } = this.props;
    if (selected) {
      let selectedRowKeys = [record && idIndex in record ? record[idIndex] : (record?.key || '')]
      this.setState({
        selectedRows: this.filterSelectRowData(selectedRowKeys),
        selectedRowKeys,
      })
    } else {
      this.setState({
        selectedRows: [],
        selectedRowKeys: [],
      })
    }
  }

  handleCheckAllChange = (selected, selectedRows) => {
    if (selected) {
      const { idIndex = 'key' } = this.props;
      let firstData = selectedRows && Array.isArray(selectedRows) && selectedRows.length > 0 ? selectedRows[0] : {};
      let selectedRowKeys = [firstData && idIndex in firstData ? firstData[idIndex] : (firstData?.key || '')]
      this.setState({
        selectedRows: this.filterSelectRowData(selectedRowKeys),
        selectedRowKeys,
      })
    } else {
      this.setState({
        selectedRows: [],
        selectedRowKeys: [],
      })
    }
  }

  // 根据选中的值获取最新的行数据
  filterSelectRowData = (keys) => {
    const { idIndex = 'key' } = this.props;
    const { tableData } = this.state;
    if (keys && Array.isArray(keys) && keys.length > 0) {
      let selectedRows = [];
      for (let i = 0; i < tableData.length; i++) {
        let item = tableData[i];
        let recordID = item && idIndex in item ? item[idIndex] : (item?.key || '');
        if (keys.indexOf(recordID) > -1) {
          selectedRows.push(item);
        }
      }
      return selectedRows;
    }
    return [];
  }

  handleClear = () => {
    this.setState({ rowID: '', rowData: {}, selectedRowKeys: [], selectedRows: [] });
  };

  handleShowColorTemplate = (id, formRecord, e) => {
    React.$stopPropagation(e)
    let top = document.getElementById(id).getBoundingClientRect().top + 26;
    let left = document.getElementById(id).getBoundingClientRect().left;
    if (top + 300 > window.innerWidth) {
      top -= 300;
    }
    if (top < 0) {
      top = 0;
    }
    // 检查是否超过屏幕高度
    if (left + 182 > window.innerHeight) {
      left -= 182;
    }
    if (left < 0) { // 头菜单高度不能超过菜单栏【侧菜单忽略】
      left = 0;
    }
    this.setState({ pickupTop: top + 'px', pickupLeft: left + 'px', isColorPickup: true, formRecord, currentColor: formRecord?.recordData[formRecord?.dataIndex || ''] || undefined });
  };

  // 选择颜色
  handleColorChange = (colorCode) => {
    let currentColor = colorCode?.hex || '';
    const { formRecord } = this.state;
    let dataIndex = formRecord?.dataIndex || '';
    this.state.tableData[formRecord?.recordIndex || formRecord?.recordData?.seqNo][dataIndex] = currentColor;
    this.setState({ currentColor });
  };

  // 关闭颜色选择器
  cancelColorPickup = () => {
    this.setState({ isColorPickup: false });
  };

  render() {
    const { title, okText, cancelText, width, isFooter, componentName, tableHeight = 400, paginationFlag, multipleFlag, size = 'small', defaultPageSize = '20', okBtnFlag = 'Y', handleCancel, cancelPopConfirmFlag,
      cancelPopConfirmTitle, operationFlag, mutualExclusionFlag } = this.props;
    const { visible, queryFormData, page, total, loading, tableData, totalWidth, columns, selectedRowKeys, selectData, pickupTop, pickupLeft, currentColor, isColorPickup, queryFormFlag } = this.state;
    return (
      <div>
        <Modal
          visible={visible}
          width={width || '1000px'}
          title={title || '查询列表'}
          footer={isFooter !== 'N' ? (
            <div>
              {cancelPopConfirmFlag === 'Y' ? (
                <Popconfirm
                  title={cancelPopConfirmTitle || '确认操作吗?'}
                  onConfirm={handleCancel ? handleCancel : this.handleCancel}
                >
                  <Button>
                    {cancelText || '取消'}
                  </Button>
                </Popconfirm>
              ) : (
                <Button onClick={handleCancel ? handleCancel : this.handleCancel}>
                  {cancelText || '取消'}
                </Button>
              )}
              {okBtnFlag !== 'N' && <Button style={{ marginLeft: '10px' }} type="primary" onClick={this.handleOk}>{okText || '确认'}</Button>}
            </ div>
          ) : null}
          onCancel={this.handleCancel}
        >
          <div className="dynamic-component table-body-height">
            <div style={{ display: !(queryFormData && queryFormData.length > 0) || queryFormFlag === 'N' ? 'none' : 'block' }}>
              <DynamicRenderingForm
                className="dynamic-component-form"
                rowData={{}}
                selectData={selectData}
                formData={queryFormData && queryFormData.length > 0 ? [...queryFormData, {
                  col: 2,
                  typeCode: 'Button',
                  type: 'primary',
                  title: '查询',
                  marginBottom: 12,
                  onClick: this.handleQuery
                }].map((item => {
                  return {
                    ...item,
                    onPressEnter: item.typeCode === 'Input' || item.typeCode === 'InputNumber' || item.typeCode === 'TextArea' ? this.handleQuery : ''
                  }
                })) : []}
                onRef={ref => this.queryFormRef = ref}
              />
            </div>
            <div style={{ position: 'relative' }}>
              <PublicTablePagination
                param={{
                  size,
                  page: paginationFlag === 'Y' ? page : false,
                  total: paginationFlag === 'Y' ? total : false,
                  loading,
                  pageSize: defaultPageSize,
                  data: tableData, // 表格数据
                  x: totalWidth, // 表格的宽度
                  y: tableHeight,
                  componentName,
                  height: tableHeight + 50 + 'px',
                  columns: operationFlag === 'Y' ? [...columns, this.getOperationObj('tableData')] : columns, // 表头配置
                }}
                rowSelectionPublic={multipleFlag === 'Y' ? {
                  selectedRowKeys,
                  onChange: mutualExclusionFlag === 'Y' ? null : this.handleSelectedRowKeysChange,
                  onSelect: mutualExclusionFlag === 'Y' ? this.handleCheckChange : null,
                  onSelectAll: mutualExclusionFlag === 'Y' ? this.handleCheckAllChange : null,
                  getCheckboxProps: record => ({
                    disabled: record?.disabledFlag === 'Y',
                  }),
                } : null}
                compilePage={paginationFlag === 'Y' ? this.compilePage : null}
                getColumns={this.getTableColumns}
                onClickRowPublic={this.onClickRowPublic}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </div>
          </div>
        </Modal>

        {/* 拾色器 */}
        {isColorPickup && (
          <ColorPickup
            // type="SwatchesPicker"
            top={pickupTop}
            left={pickupLeft}
            visible={isColorPickup}
            color={currentColor}
            onChange={this.handleColorChange}
            cancelColorPickup={this.cancelColorPickup} />
        )}
      </div>
    )
  }
};

export default PublicModalQueryTable;