/*
 * Create:      柿子
 * CreateDate:  2023/10/23
 * Describe：   病区信息设置
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Button, Input, Checkbox, Switch, message, Popconfirm } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination.jsx';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import CommonConfigCopy from './component/CommonConfigCopy';
import iconListVisits from 'assets/images/icon_listvisits.png';
import iconMessages from 'assets/images/icon_messages.png';
import './style/index.less';

class WardInformationSettings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userData: React.$getSessionData(),
      queryParams: {
        alias: undefined, // 名称
        useFlag: true, // 仅显示生效
      },
      loading: false,
      columns: [],
      tableData: [],
      totalWidth: 0,
      rowID: '',
      rowData: {},
      selectData: {},
      baseInfoFormData: [],
      displayColumns: [],
      displayTotalWidth: 0,
      otherFormData: [],
      displayTableData: [],
      displayLoading: false,
      displayRowID: '',
      monitoringColumns: [], // 检测内容表单数据
      monitoringTotalWidth: 0, // 检测内容
      monitoringLoading: false,
      monitoringTableData: [],
      spyCheckedData: [], // 监测内容选中数据
    };
  };

  componentDidMount() {
    this.getSelectData();
    this.getTableColumns();
    this.getDisplayTableColumns();
    this.getMonitoringColumns();
  };

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

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

  // 获取表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: this.props.locID ? 'WardInformationSettings' : 'WardInformationCommonSettings',
          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 baseInfoFormData = res.result?.formData || [];
      if (baseInfoFormData && baseInfoFormData.length > 0) {
        this.setState({ baseInfoFormData });
      }
    } catch (error) {
      console.log(error)
    }
  };

  // 检测方式切换
  handleMonitoringContentTypeChange = e => {
    console.log('e', e)
  };

  // 请求列表数据
  getTableData = async (isClear) => {
    try {
      this.setState({ loading: true })
      let { queryParams, userData } = 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 ? '04011005' : '04011010', data); // 04011010为公共界面 | 04011005为科室管理子界面
      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);
    }
  };

  // 修改操作框数据
  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,
            displayTableData: Util.addKeyValueToDataSource(record?.dspColData || [], '', 0),
            spyCheckedData: record?.spyData || [],
          })
        } else {
          this.handleClear();
        }
      }
    }
  };

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

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

  // 复制
  handleCopy = () => {
    this.copyRef && this.copyRef.modifyVisible(true);
  };

  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, '04011006', data);
      message.success(res?.errorMessage || '保存成功');
      this.getTableData('N');
    } catch (error) {
      console.log(error);
    }
  };

  getDisplayTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'WardInformationDisplaySettings',
          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({
          displayColumns: columns,
          displayTotalWidth: res.totalWidth
        })
      }
      // 表单操作数据
      let otherFormData = res.result?.formData || [];
      if (otherFormData && otherFormData.length > 0) {
        this.setState({ otherFormData });
      }
    } catch (error) {
      console.log(error)
    }
  };

  handleRenderInput = (text, record, index, colItem) => {
    let dataIndex = colItem?.dataIndex || '';
    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.target.checked ? 'Y' : 'N', e)}
        />
      )
    } 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)}
        />
      )
    } else {
      return text;
    }
  };

  handleInputChange = (index, dataIndex, val, e) => {
    React.$stopPropagation(e);
    this.state.displayTableData[index][dataIndex] = val;
    this.setState({});
  };

  // 操作行
  handleDisplayRowClick = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.displayRowID === '' || (this.state.displayRowID && (this.state.displayRowID !== record.key))) {
          this.setState({ displayRowID: record.key })
        } else {
          this.setState({ displayRowID: '' })
        }
      }
    }
  };

  // 选中行操作
  handleDisplaySetRowClassName = (record) => {
    return record.key === this.state.displayRowID ? 'clickRowStyle' : '';
  };

  getMonitoringColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'WardInformationMonitoring',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          monitoringColumns: columns,
          monitoringTotalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  };

  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}
          style={{ marginRight: '8px' }}
          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>
      </>
    )
  }

  // 处理许可证数据
  filterFormValues = (formVal, type, key) => {
    let nFormVal = {};
    for (let keys in formVal) {
      if (type === 'add') {
        nFormVal[keys + '_' + key] = formVal[keys];
      } else {
        let currentKey = keys.indexOf('_') > -1 ? keys.split('_')[0] : keys;
        nFormVal[currentKey] = formVal[keys];
      }
    }
    return nFormVal;
  };

  // 保存
  handleSave = async (isValid) => {
    try {
      const { rowData, displayTableData, userData, spyCheckedData } = this.state;
      let baseInfoFormValue = await this.baseInfoFormRef.handleSave();
      if (baseInfoFormValue.error) {
        message.error('请完善必填信息');
        return;
      }
      let otherFormValue = await this.otherFormRef.handleSave();
      if (otherFormValue.error) {
        message.error('请完善必填信息');
        return;
      }
      let dspColData = displayTableData && displayTableData.filter(item => item.checked === 'Y').map(item => item.id); // 显示设置 - 只传入显示数据的id
      // let spyData = monitoringTableData && monitoringTableData.filter(item => item.checked === 'Y').map(item => item.id); // 监测内容
      let data = {
        params: [{
          ...baseInfoFormValue,
          ...otherFormValue,
          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', // 是否生效
          dspColData,
          spyData: spyCheckedData,
        }]
      }
      let res = await React.$asyncPost(this, '04011004', 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, '04011009', data);
      message.success(res?.errorMessage || '删除成功');
      this.getTableData();
    } catch (error) {
      console.log(error)
    }
  };

  // 复制数据时判断是否存在
  handleDuplicateCheck = (checkArr) => {
    const { tableData } = this.state;
    let repeatArr = [];
    if (Array.isArray(checkArr) && checkArr.length > 0) {
      const tableDataIds = tableData.map(item => item.comConfigID);
      for (let i = 0; i < checkArr.length; i++) {
        if (tableDataIds.includes(checkArr[i].comConfigID)) {
          repeatArr.push(checkArr[i]?.descripts || checkArr[i].comConfigID);
        }
      }
    }
    return repeatArr;
  }

  render() {
    const { tabHeight } = this.props;
    const { queryParams, loading, columns, tableData, totalWidth, rowID, rowData, selectData, baseInfoFormData, displayColumns, displayTableData, displayLoading, otherFormData, monitoringTotalWidth, monitoringColumns,
      monitoringLoading, monitoringTableData, spyCheckedData
    } = this.state;

    const rowSelection = {
      selectedRowKeys: spyCheckedData,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ spyCheckedData: selectedRowKeys })
      },
    };

    return (
      <div className="ward-information-settings">
        <Row>
          <Col span={10}>
            <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')}>仅显示生效</Checkbox>
                )}
              >
                <div className="table-body-height">
                  <div style={{ marginBottom: 12 }}>
                    <span className="common-input-label">名称：</span>
                    <Input
                      title="输入内容后可回车检索"
                      placeholder="请输入名称检索"
                      className="common-query-input"
                      style={{ width: '200px' }}
                      value={queryParams?.alias}
                      onChange={(e) => this.handleModifyInputValue(e.target.value, 'alias')}
                      onPressEnter={this.getTableData}
                    />
                    <Button type="primary" style={{ marginRight: 12 }} onClick={this.getTableData}>查询</Button>
                    {this.props.locID && <Button ghost type="primary" style={{ float: 'right' }} onClick={this.handleCopy}>复制</Button>}
                  </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 ? 'WardInformationSettings' : 'WardInformationCommonSettings',
                      columns: columns && columns.length > 0 ? [...columns, this.getOperationObj('tableData')] : [], // 表头配置
                    }}
                    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={14}>
            <Card
              bordered={false}
              size="small"
              title={(
                <div className="card-title-left-img">
                  <img src={iconMessages} alt="" />
                  设置
                </div>
              )}
              extra={(
                this.props.locID && rowID && <Button size="small" type="danger" onClick={() => this.handleSave('N')}>从本科移除</Button>
              )}
            >
              <div
                style={{
                  height: (tabHeight ? (tabHeight + 92) : store.getState().tableHeight.y + 180) + 'px',
                  overflow: 'auto',
                  padding: '12px'
                }}
                className="scroll-bar-style"
              >
                <DynamicRenderingForm
                  rowData={rowData}
                  selectData={selectData}
                  formData={baseInfoFormData}
                  onRef={ref => this.baseInfoFormRef = ref}
                />
                <Row className="ant-form-item dynamic-rendering-form">
                  <Col span={3} className="ant-form-item-label">
                    <label>显示设置</label>
                  </Col>
                  <Col span={12} className="common-table-empty">
                    <div style={{ minHeight: '82px' }}>
                      <PublicTablePagination
                        param={{
                          loading: displayLoading,
                          data: displayTableData, // 表格数据
                          x: 'none', // 表格的宽度
                          y: 'auto',
                          height: 'auto',
                          componentName: 'WardInformationDisplaySettings',
                          columns: displayColumns ? [...displayColumns, this.getOperationObj('displayTableData')] : [], // 表头配置
                        }}
                        getColumns={this.getDisplayTableColumns}
                        onClickRowPublic={this.handleDisplayRowClick}
                        setRowClassNamePublic={this.handleDisplaySetRowClassName}
                      />
                    </div>
                  </Col>
                </Row>
                <DynamicRenderingForm
                  rowData={rowData}
                  selectData={selectData}
                  formData={otherFormData}
                  onRef={ref => this.otherFormRef = ref}
                />
                <Row className="ant-form-item dynamic-rendering-form">
                  <Col span={3} className="ant-form-item-label">
                    <label>监测内容</label>
                  </Col>
                  <Col span={21} className="common-table-empty">
                    <div style={{ minHeight: '82px' }}>
                      <PublicTablePagination
                        param={{
                          loading: monitoringLoading,
                          data: monitoringTableData, // 表格数据
                          x: monitoringTotalWidth, // 表格的宽度
                          y: 'auto',
                          height: 'auto',
                          componentName: 'WardInformationMonitoring',
                          columns: monitoringColumns ? [...monitoringColumns] : [], // 表头配置
                        }}
                        rowSelectionPublic={rowSelection}
                        getColumns={this.getMonitoringColumns}
                      // onClickRowPublic={this.handleDisplayRowClick}
                      // setRowClassNamePublic={this.handleDisplaySetRowClassName}
                      />
                    </div>
                  </Col>
                </Row>
                <Row style={{ marginTop: '12px' }}>
                  <Col span={3} className="ant-form-item-label"></Col>
                  <Col span={12}>
                    <Button style={{ marginRight: '12px' }} type="primary" disabled={!rowID} onClick={() => this.handleSave('Y')}>{this.props.locID ? '保存到本科' : '保存'}</Button>
                    {this.props.locID ? (
                      <Popconfirm
                        title="确认恢复默认设置吗?"
                        disabled={!(rowData?.deleteFlag === 'Y')}
                        onConfirm={this.handleDelete}
                      >
                        <Button disabled={!(rowData?.deleteFlag === 'Y')}>恢复默认设置</Button>
                      </Popconfirm>
                    ) : (
                      <Popconfirm
                        title="删除不可恢复，你确定要删除吗?"
                        disabled={!rowID}
                        onConfirm={() => this.handleSave('N')}
                      >
                        <Button type="danger" disabled={!rowID}>删除</Button>
                      </Popconfirm>
                    )}
                  </Col>
                </Row>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 复制配置 */}
        <CommonConfigCopy
          queryCode="04011005"
          copyCode="04011008"
          componentName="CopyWardInfoConfig"
          locID={this.props.locID || undefined}
          selectData={selectData}
          onRef={ref => this.copyRef = ref}
          handleQuery={this.getTableData}
          duplicateCheck={this.handleDuplicateCheck}
        />
      </div>
    )
  }
};

export default WardInformationSettings;