/*
 * Create:      柿子
 * CreateDate:  2023/11/27
 * Describe：   床位图设置(个人设置) - 公共个人设置【病区信息设置 | 搜索条件设置 | 鼠标右键设置 | 处理区设置】
 * */
import React, { Component } from 'react';
import { Button, Input, Select, Checkbox, Switch, message } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination.jsx';
import './style/index.less';

class BedChartPersonalCommonSetting extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userData: React.$getSessionData(),
      queryParams: {
        alias: undefined, // 名称
        useFlag: false, // 仅显示生效
      },
      loading: false,
      columns: [],
      tableData: [],
      totalWidth: 0,
      rowID: '',
      rowData: {},
      selectData: {},
    };
  };

  componentDidMount() {
    // this.getSelectData();
    this.getTableData();
    this.getTableColumns();
  };

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

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

  // 获取表头数据
  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) {
        for (let i = 0; i < columns.length; i++) {
          let colItem = columns[i];
          columns[i].render = (text, record, index) => this.handleRenderInput(text, record, index, colItem);
        }
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  };

  // 请求列表数据
  getTableData = async (isClear) => {
    try {
      this.setState({ tableData: [{ seqNo: 1, key: 1, id: 1 }, { seqNo: 2, key: 2, id: 2 }] });
      return;
      this.setState({ loading: true })
      let { queryParams } = this.state;
      let data = {
        params: [{
          ...queryParams,
          // Y - 启用; N - 查全部
          useFlag: queryParams.useFlag ? 'Y' : 'N',
          locID: this.props.locID || undefined, // 科室id
        }],
      }
      let res = await React.$asyncPost(this, '123', data);
      let tableData = Util.addKeyValueToDataSource(res?.result || [], '', 0);
      this.setState({ tableData, total: res.result?.total || 0, loading: false }, () => {
        isClear !== 'N' && this.handleClear();
      });
    } catch (error) {
      console.log(error);
      this.setState({ loading: false });
    }
  };

  // 修改操作框数据
  handleModifyInputValue = (e, dataIndex) => {
    this.state.queryParams[dataIndex] = e;
    this.setState({}, () => {
      if (dataIndex === 'useFlag') {
        this.getTableData();
      }
    })
  };

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

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

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

  handleMove = (record, direction, dataIndex, e) => {
    React.$stopPropagation(e);
    let tableData = this.state[dataIndex];
    const rowKey = record?.key;
    const currentIndex = tableData.findIndex(item => item.key === rowKey);
    if (direction === 'up' && currentIndex > 0) {
      [tableData[currentIndex - 1], tableData[currentIndex]] = [tableData[currentIndex], tableData[currentIndex - 1]];
      // 更新key值
      tableData[currentIndex].key = currentIndex;
      tableData[currentIndex - 1].key = currentIndex - 1;
    } else if (direction === 'down' && currentIndex < (tableData.length - 1)) {
      [tableData[currentIndex + 1], tableData[currentIndex]] = [tableData[currentIndex], tableData[currentIndex + 1]];
      // 更新key值
      tableData[currentIndex].key = currentIndex;
      tableData[currentIndex + 1].key = currentIndex + 1;
    }
    this.state[dataIndex] = tableData;
    this.setState({}, () => {
      dataIndex === 'tableData' && this.handleMoveSave();
    })
  };

  // 保存排序数据
  handleMoveSave = async () => {
    try {
      const { tableData } = this.state;
      let sortArr = tableData && tableData.map(item => item.id);
      let data = {
        params: [{
          sortArr
        }]
      }
      let res = await React.$asyncPost(this, '123', data);
      message.success(res?.errorMessage || '保存成功');
      this.getTableData('N');
    } catch (error) {
      console.log(error);
    }
  };

  handleRenderInput = (text, record, index, colItem) => {
    const { selectData } = this.state;
    let dataIndex = colItem?.dataIndex || '';
    let linkService = colItem?.linkService || '';
    let typeCode = colItem?.linkMethod || '';
    if (colItem?.linkMethod === 'Switch') {
      return (
        <Switch
          checkedChildren="是"
          unCheckedChildren="否"
          checked={record[dataIndex] === 'Y' ? true : false}
          onClick={e => React.$stopPropagation(e)}
          onChange={(e) => this.handleInputChange(index, dataIndex, e ? 'Y' : 'N')}
        />
      )
    } else if (colItem?.linkMethod === 'Checkbox') {
      return (
        <Checkbox
          checked={record[dataIndex] === 'Y' ? true : false}
          onClick={e => React.$stopPropagation(e)}
          onChange={(e) => this.handleInputChange(index, dataIndex, e.target.checked ? 'Y' : 'N', e)}
        />
      )
    } if (typeCode === 'Input') {
      return (
        <Input
          allowClear
          style={{ width: '90%' }}
          placeholder="请输入"
          value={record[dataIndex] || undefined}
          onClick={e => React.$stopPropagation(e)}
          onChange={(e) => this.handleInputChange(index, dataIndex, e.target.value, e)}
        />
      )
    } else if (typeCode === 'Select') {
      return (
        <Select
          allowClear
          showSearch
          style={{ width: '90%' }}
          placeholder="请选择"
          optionFilterProp="search"
          value={record[dataIndex] || undefined}
          onClick={e => React.$stopPropagation(e)}
          onChange={(e) => this.handleInputChange(index, dataIndex, e, e)}
        >
          {React.$SelectOptions(selectData && linkService in selectData && Array.isArray(selectData[linkService]) ? selectData[linkService] : [])}
        </Select>
      )
    } else {
      return text;
    }
  };

  handleInputChange = (index, dataIndex, val, e) => {
    React.$stopPropagation(e);
    this.state.tableData[index][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) => {
    let tableLen = this.state[dataIndex]?.length || 0;
    return (
      <>
        <Button
          type="link"
          size="small"
          disabled={index === 0}
          onClick={(e) => this.handleMove(record, 'up', dataIndex, e)}
        >
          上移
        </Button>
        <Button
          type="link"
          size="small"
          disabled={index >= tableLen - 1}
          onClick={(e) => this.handleMove(record, 'down', dataIndex, e)}
        >
          下移
        </Button>
        {record?.addFlag === 'Y' && (
          <span
            style={{ marginLeft: '8px' }}
            className="span common-record-delete-span"
            onClick={(e) => this.handleRecordDelete(record, index, e)}
          >
            删除
          </span>
        )}
      </>
    )
  };

  // 新增
  handleAdd = () => {
    let { tableData } = this.state;
    let key = tableData?.length || 0;
    tableData.push({
      key,
      seqNo: key + 1,
      addFlag: 'Y'
    });
    this.setState({});
  };

  // 删除
  handleRecordDelete = (record, indexToRemove, e) => {
    React.$stopPropagation(e);
    let { tableData } = this.state;
    const newArray = tableData.filter((d, index) => index !== indexToRemove);
    this.setState({ tableData: newArray });
  }

  // 保存
  handleSave = async (isValid) => {
    try {
      const { rowData } = this.state;
      let data = {
        params: [{
          id: rowData?.id || '',
          seqNo: rowData?.seqNo || '', // 序号
          saveType: this.props.locID ? 'W' : 'C', // 保存类型【C:公共 W:病区】
          locID: this.props.locID || undefined, // 病区ID
          comConfigID: rowData?.comConfigID || '', // 公共配置ID
          isValid: isValid || 'Y', // 是否生效
        }]
      }
      let res = await React.$asyncPost(this, '123', data);
      message.success(res?.errorMessage || '保存成功');
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  };

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

  render() {
    const { typeFlag, tabHeight, componentName } = this.props;
    const { queryParams, loading, columns, tableData, totalWidth, selectData } = this.state;

    return (
      <div className="bed-chart-setting">
        <div style={{ height: '100%', paddingBottom: '46px', overflow: 'auto' }} className="table-body-height">
          <div style={{ marginBottom: 12 }}>
            <span className="common-input-label">名称：</span>
            <Input
              title="输入内容后可回车检索"
              placeholder="请输入名称检索"
              className="common-query-input"
              value={queryParams?.alias}
              onChange={(e) => this.handleModifyInputValue(e.target.value, 'alias')}
              onPressEnter={this.getTableData}
            />
            {typeFlag === 'Y' && <>
              <span className="common-input-label">类型：</span>
              <Select
                placeholder="请选择"
                className="common-query-input"
                value={queryParams?.typeID}
                onChange={(e) => this.handleModifyInputValue(e, 'typeID')}
              >
                {React.$SelectOptions(selectData?.typeArr || [])}
              </Select>
            </>}
            <Checkbox checked={queryParams?.useFlag || false} onChange={(e) => this.handleModifyInputValue(e.target.checked, 'useFlag')}>仅查看显示</Checkbox>
            <Button type="primary" style={{ marginRight: 12 }} onClick={this.getTableData}>查询</Button>
            <span className="bed-chart-setting-explain">说明：上移图标靠前显示，下移图标靠后显示。</span>
          </div>
          <PublicTablePagination
            param={{
              loading,
              componentName,
              data: tableData, // 表格数据
              x: totalWidth, // 表格的宽度
              y: tabHeight ? tabHeight - 46 : store.getState().tableHeight.y + 40,
              height: tabHeight ? (tabHeight + 4 + 'px') : store.getState().tableHeight.y + 90 + 'px',
              columns: columns && columns.length > 0 ? [...columns, this.getOperationObj('tableData')] : [], // 表头配置
            }}
            getColumns={this.getTableColumns}
            onClickRowPublic={this.onClickRowPublic}
            setRowClassNamePublic={this.setRowClassNamePublic}
          />
        </div>
        <div className="bed-chart-setting-footer flex-center">
          <Button>恢复默认配置</Button>
          <Button style={{ marginLeft: '12px' }} type="primary">保存</Button>
        </div>
      </div >
    )
  }
};

export default BedChartPersonalCommonSetting;