/*
 * Create:      柿子
 * CreateDate:  2023/10/31
 * Describe：   床位图图标设置
 * */
import React, { Component } from 'react';
import { Button, Input, Select, Switch } from 'antd';
import store from 'store';
import BedItem from '../component/BedItem';
import ColorPickup from 'pages/emr/component/ColorPickup.jsx';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import '../style/common.less';

class BedChartIconSetting extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectData: {},
      loading: false,
      tableData: [],
      columns: [],
      totalWidth: 0,
      rowID: '',
      isColorPickup: false,
      fontColor: '#000',
    }
  }

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

  // 获取表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'BedChartIconSetting',
          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 && columns.map(item => {
          let dataIndex = item?.dataIndex || '';
          let linkService = item?.linkService || '';
          let typeCode = item?.linkMethod || '';
          return {
            ...item,
            render: (text, record, index) => {
              if (typeCode === 'Input') {
                return (
                  <Input
                    allowClear
                    style={{ width: '90%' }}
                    placeholder="请输入"
                    value={record[dataIndex] || undefined}
                    onChange={(e) => this.handleInputChange(e.target.value, record, dataIndex)}
                  />
                )
              } else if (typeCode === 'Select') {
                linkService = linkService || dataIndex;
                return (
                  <Select
                    allowClear
                    showSearch
                    style={{ width: '90%' }}
                    placeholder="请选择"
                    optionFilterProp="search"
                    value={record[dataIndex] || undefined}
                    onChange={(e) => this.handleInputChange(e, record, dataIndex)}
                  >
                    {React.$SelectOptions(selectData && linkService in selectData && Array.isArray(selectData[linkService]) ? selectData[linkService] : [])}
                  </Select>
                )
              } else if (typeCode === 'Switch') {
                return (
                  <Switch
                    checkedChildren="是"
                    unCheckedChildren="否"
                    checked={record[dataIndex] === 'Y' ? true : false}
                    onChange={(e) => this.handleInputChange(e ? 'Y' : 'N', record, dataIndex)}
                  />
                )
              } else if (dataIndex === 'color') {
                if (record?.type === 'careLevel') {
                  return (
                    <span
                      id={'icon-setting-color-' + index}
                      className="span-color-block"
                      style={{ backgroundColor: record?.color || '', cursor: 'pointer' }}
                      onClick={() => this.handleShowColorTemplate('icon-setting-color-' + index, item, index)}
                    ></span>
                  )
                } else {
                  return (
                    <div style={{ textAlign: 'left', paddingLeft: '10%' }}>
                      <span
                        id={'icon-setting-color-' + index}
                        className="span-color-border"
                        style={{ borderColor: record?.color || '', color: record?.color || '', cursor: 'pointer' }}
                        onClick={() => this.handleShowColorTemplate('icon-setting-color-' + index, item, index)}
                      >
                        {record?.title || '无'}
                      </span>
                    </div>
                  )
                }
              } else {
                return text;
              }
            }
          }
        })
        this.setState({ columns, totalWidth: res?.totalWidth || 0 })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 修改输入域的值
  handleInputChange = (val, record, dataIndex) => {
    record[dataIndex] = val;
    this.setState({});
  };

  getOperationObj = () => {
    const { tableData } = this.state;
    // 列表操作
    const operationObj = {
      width: 120,
      key: 'operation',
      title: '操作',
      align: 'center',
      fixed: 'right',
      render: (text, record, index) => (
        <>
          <Button
            size="small"
            disabled={record?.type === 'first' || record?.type === 'careLevel'}
            style={{ marginRight: '8px' }}
            onClick={(e) => this.handleMove(record, 'up', e)}
          >
            前移
          </Button>
          <Button
            size="small"
            disabled={tableData?.length - 1 <= index || record?.type === 'careLevel'}
            onClick={(e) => this.handleMove(record, 'down', e)}
          >
            后移
          </Button>
        </>
      ),
    };
    return operationObj;
  }

  getTableData = () => {
    let tableData = [{
      key: 1,
      iconDesc: '一级护理',
      color: 'red',
      range: '',
      title: '无',
      displayMethod: '',
      showFlag: 'N',
      type: 'careLevel',
    }, {
      key: 2,
      iconDesc: '二级护理',
      color: 'yellow',
      range: '',
      title: '无',
      displayMethod: '',
      showFlag: 'N',
      type: 'careLevel',
    }, {
      key: 3,
      iconDesc: '三级护理',
      color: '#00ffff',
      range: '',
      title: '无',
      displayMethod: '',
      showFlag: 'N',
      type: 'careLevel',
    }, {
      key: 4,
      iconDesc: '特级护理',
      color: '#00ffff',
      range: '',
      title: '无',
      displayMethod: '',
      showFlag: 'N',
      type: 'careLevel',
    }, {
      key: 5,
      iconDesc: '新入院患者',
      color: '#00ffff',
      range: '',
      title: '入',
      displayMethod: '',
      showFlag: 'N'
    }, {
      key: 6,
      iconDesc: '今日手术',
      color: '#00ffff',
      range: '',
      title: '术',
      displayMethod: '',
      showFlag: 'N'
    }, {
      key: 7,
      iconDesc: '今日出院',
      color: '#00ffff',
      range: '',
      title: '出',
      displayMethod: '',
      showFlag: 'N'
    }, {
      key: 8,
      iconDesc: '新开医嘱',
      color: '#00ffff',
      range: '',
      title: '新',
      displayMethod: '',
      showFlag: 'N'
    }];
    for (let i = 0; i < tableData.length - 1; i++) {
      if (tableData[i].type === 'careLevel' && tableData[i + 1].type !== 'careLevel') {
        tableData[i + 1].type = 'first';
      }
    }
    this.setState({ tableData });
  }

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

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

  handleShowColorTemplate = (id, record, index) => {
    let top = document.getElementById(id).getBoundingClientRect().top + 26 + 'px';
    let left = document.getElementById(id).getBoundingClientRect().left + 'px';
    this.setState({
      top, left,
      isColorPickup: true,
      currentPickupIndex: index,
      fontColor: record?.color || '#000'
    });
  }

  cancelColorPickup = () => {
    this.setState({ isColorPickup: false });
  }

  handleColorChange = (colorCode) => {
    let { currentPickupIndex, tableData } = this.state;
    const fontColor = colorCode?.hex || '';
    tableData[currentPickupIndex].color = fontColor;
    this.setState({ tableData });
  }

  // 复位
  handleReset = () => {

  }

  // 保存
  handleSave = () => {
    let { tableData } = this.state;
    console.log('tableData', tableData);
  }

  render() {
    const { loading, tableData, columns, totalWidth, top, left, isColorPickup, fontColor } = this.state;
    return (
      <div className="nurse-station-common flex">
        <div style={{ width: '28%', padding: '0 24px 200px 4px' }} className="flex-column-center">
          <h3>效果图预览</h3>
          <div style={{ width: '92%', margin: '24px 0' }}>
            <BedItem
              rowData={{ id: '1' }}
              bedInfo={{
                roomDescripts: '一病室',
                bedCode: '601',
                id: '1',
                patName: '窦后田',
                patNo: '0000740775',
                admDateTime: '2023-11-12 09:51:43',
                admDiag: '1.葡萄膜炎[色素膜炎](双眼);2.白内障(双眼);3.葡萄膜炎[色素膜炎](双眼);4.黄斑水肿(双眼);5.老年性白内障(双眼)',
                admReasonDesc: '六安市-(城乡居民基本医疗保险)',
                patMedicalNo: '03000808',
                admNurDesc: '刘慧娟',
                admDocDesc: '张婉',
                patSexDesc: '男',
                patAge: '40岁',
                admInDays: '0',
                headerIcon: [{
                  key: 5,
                  iconDesc: '新入院患者',
                  color: '#00ffff',
                  range: '',
                  title: '入',
                  displayMethod: '',
                  showFlag: 'N'
                }, {
                  key: 6,
                  iconDesc: '今日手术',
                  color: '#00ffff',
                  range: '',
                  title: '术',
                  displayMethod: '',
                  showFlag: 'N'
                }, {
                  key: 7,
                  iconDesc: '今日出院',
                  color: '#00ffff',
                  range: '',
                  title: '出',
                  displayMethod: '',
                  showFlag: 'N'
                }]
              }} />
          </div>
          <Button ghost type="primary">预览</Button>
        </div>
        <div style={{ width: '72%', paddingLeft: '16px', position: 'relative' }}>
          <div className="common-card-left-split-line" style={{ width: '6px' }}></div>
          <div className="table-body-height" style={{ height: store.getState().tableHeight.y + 90 + 'px' }}>
            <PublicTablePagination
              param={{
                loading,
                data: tableData, // 表格数据
                x: totalWidth, // 表格的宽度
                y: store.getState().tableHeight.y + 40,
                componentName: 'BedChartIconSetting',
                columns: columns && columns.length > 0 ? [...columns, this.getOperationObj()] : [], // 表头配置
              }}
              getColumns={this.getTableColumns}
              onClickRowPublic={this.onClickRowPublic}
            // setRowClassNamePublic={this.setRowClassNamePublic}
            />
            <ColorPickup
              top={top}
              left={left}
              visible={isColorPickup}
              color={fontColor}
              onChange={this.handleColorChange}
              cancelColorPickup={this.cancelColorPickup} />
          </div>
          <div style={{ marginTop: '12px' }} className="flex-center">
            <Button style={{ marginRight: '24px' }} onClick={this.handleReset}>复位</Button>
            <Button type="primary" onClick={this.handleSave}>保存</Button>
          </div>
        </div>
      </div>
    )
  }
};

export default BedChartIconSetting;