/*
 * Create:      柿子
 * CreateDate:  2023/11/24
 * Describe：   右键菜单设置
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Button, Input, Select, Checkbox, Switch, message, Popconfirm } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination.jsx';
import iconListVisits from 'assets/images/icon_listvisits.png';
import './style/index.less';

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

  componentDidMount() {
    this.getSelectData();
  };

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

  // 获取下拉数据
  getSelectData = async () => {
    try {
      let data = {
        params: [{}]
      }
      let res = await React.$asyncPost(this, '04011033', data);
      let handleAreaArr = res?.result?.handleAreaArr || [];
      if (handleAreaArr && handleAreaArr.length > 0) {
        this.state.queryParams.handleAreaID = handleAreaArr[0]?.id || undefined;
      }
      this.setState({
        selectData: res?.result || []
      }, () => {
        this.getTableData();
        this.getTableColumns();
      });
    } catch (error) {
      console.log(error);
      this.getTableData();
      this.getTableColumns();
    }
  };

  // 获取表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: this.props.locID ? 'NSRightClickMenuSettings' : 'NSCommonRightClickMenuSettings',
          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({ 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, this.props.locID ? '04011029' : '04011030', 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, isQuery) => {
    this.state.queryParams[dataIndex] = e;
    this.setState({}, () => {
      isQuery === 'Y' && 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={linkService && linkService.indexOf('placeholder') > -1 ? Util.getValueByUrlStr(linkService, '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 () => {
    try {
      const { tableData, queryParams } = this.state;
      let data = {
        params: [{
          ...queryParams,
          saveType: this.props.locID ? 'W' : 'C', // 保存类型【C:公共 W:病区】
          locID: this.props.locID || undefined, // 病区ID
          tableData,
        }]
      }
      let res = await React.$asyncPost(this, '04011031', data);
      message.success(res?.errorMessage || '保存成功');
      this.getTableData();
    } catch (error) {
      console.log(error);
    }
  };

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

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

    return (
      <div className="ward-information-settings">
        <div
          style={{ paddingRight: '8px', position: 'relative', height: '100%' }}
        >
          <Card
            size="small"
            bordered={false}
            title={(
              <div className="card-title-left-img">
                <img src={iconListVisits} alt="" />
                右键菜单设置
              </div>
            )}
            extra={(
              <Checkbox checked={queryParams?.useFlag || false} onChange={(e) => this.handleModifyInputValue(e.target.checked, 'useFlag', 'Y')}>仅显示生效</Checkbox>
            )}
          >
            <div 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}
                />
                {selectData && 'handleAreaArr' in selectData && Array.isArray(selectData.handleAreaArr) && selectData.handleAreaArr.map((item, index) => {
                  return (
                    <Button
                      key={index}
                      style={{ marginRight: '8px' }}
                      ghost={item.id === queryParams?.handleAreaID ? true : false}
                      type={item.id === queryParams?.handleAreaID ? 'primary' : 'default'}
                      onClick={() => this.handleModifyInputValue(item.id, 'handleAreaID', 'Y')}
                    >
                      {item?.descripts || ''}
                    </Button>
                  )
                })}
                <div style={{ float: 'right' }}>
                  {/* {!this.props.locID && <Button icon="plus" className="add-btn add-btn-noHover" style={{ marginRight: '12px' }} onClick={this.handleAdd}>新增</Button>} */}
                  <Button type="primary" onClick={() => this.handleSave('Y')}>保存</Button>
                  {this.props.locID && (
                    <Popconfirm
                      title="确认恢复默认设置吗?"
                      onConfirm={this.handleDelete}
                    >
                      <Button style={{ marginLeft: '12px' }}>恢复默认设置</Button>
                    </Popconfirm>
                  )}
                </div>
              </div>
              <PublicTablePagination
                param={{
                  loading,
                  data: tableData, // 表格数据
                  x: totalWidth, // 表格的宽度
                  y: tabHeight ? tabHeight : store.getState().tableHeight.y + 86,
                  height: tabHeight ? (tabHeight + 50 + 'px') : store.getState().tableHeight.y + 136 + 'px',
                  componentName: this.props.locID ? 'NSRightClickMenuSettings' : 'NSCommonRightClickMenuSettings',
                  columns: columns && columns.length > 0 ? [...columns, this.getOperationObj('tableData')] : [], // 表头配置
                }}
                getColumns={this.getTableColumns}
                onClickRowPublic={this.props.locID ? this.onClickRowPublic : null}
                setRowClassNamePublic={this.props.locID ? this.setRowClassNamePublic : null}
              />
            </div>
          </Card>
        </div >
      </div >
    )
  }
};

export default RightClickMenuSettings;