//手术套维护
import React from 'react';
import {
  Card, Table, Input, Select, Checkbox, Modal, Spin, Button, Tooltip, Icon, Divider, message, Popconfirm
} from 'antd';
import { Util } from 'tools/index';
import { $http } from 'containers/config/https';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import ShowCommonTableModal from '../../workstation/component/ShowCommonTableModal.jsx'
import store from 'store';
import './style/index.less';
const confirm = Modal.confirm;
let tableRecord = {};
class OperationSetMaintain extends React.Component {
  constructor(props) {
    super(props)
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    var recordData = JSON.parse(sessionStorage.getItem('recordData'))
    var titleData = JSON.parse(sessionStorage.getItem('titleData'))
    this.state = {
      dataSource: [],
      total: 0,
      page: 1,
      pageSize: 10,
      subrateData: {},
      userData: userData,
      recordData: recordData,
      titleData: titleData,
      subData: [],
      ids: [],
      selectData: [],
      cannelStatus: false,
      dynColumns: [],
      saveStatus: false,
      eyePartList: [],
      bodyPartList: [],
      stageList: [],
      priorityExtList: [],
      checkData: [],            //多选的数据 createBY: DYK
      totalWidth: 2200, // 总列宽
      classificationData: [],		// 手术分类下拉数据源
      anesthesiaData: [],			// 麻醉下拉数据源
      operationData: [],			// 手术下拉数据源
      operationLevelData: [],		// 级别下拉数据源
      operationPartData: [],		// 手术部位下拉数据源
      operationCutData: [],		// 手术切口下拉数据源
      operationPostData: [],		// 手术体位下拉数据源
      operationPartPar: [],		//部位明细
      searchCode: '',
      operationColumns: [],
      mainFormData: [], // 表单数据
      levelDataOption: []
    }
    this.selectFocus = React.createRef();
  }

  componentDidMount() {
    this.loadUseLevel();
    this.loadLeftData();
    this.initData();
    this.getSelectData();
    this.loadColumns();
    document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 20 + 'px'
  }

  loadUseLevel() {
    var params = {
      params: [{}]
    }
    $http.post('urlDeault', this, {
      code: "03050073",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          this.setState({
            levelDataOption: res.data
          }, () => {
            console.log("levelDataOption:", this.state.levelDataOption)
            this.getMainFormData(); // 获取主表表单数据
          });
        }
      }
    });
  }

  initData() {
    // var date = new Date();
    this.leftColumns = [
      {
        title: '级别',
        dataIndex: 'title',
        width: 100,
        align: 'center',
        render: (text, data) => {
          // return <span style={{ width: 120 }}>{data.title + '(' + data.count + ')'}</span>
          return data.operationSetID ? null : <span><span>{data.title}</span><span>({data.count})</span></span>
        }
      }, {
        title: '名称',
        dataIndex: 'operationSetDesc',
        width: 70,
        align: 'center',
        render: (text, data) => {
          return <Tooltip title={data.operationSetDesc}><div className='complete-text-ellipsis'>{data.operationSetDesc}</div></Tooltip>
        }
      }, {
        title: '别名',
        dataIndex: 'operationSetAlias',
        width: 80,
        align: 'center',
        render: (text, data) => {
          return <Tooltip title={data.operationSetAlias}><div className='complete-text-ellipsis'>{data.operationSetAlias}</div></Tooltip>
        }
      }, {
        title: '操作员',
        dataIndex: 'userName',
        width: 80,
        align: 'center',
      }, {
        title: '状态',
        dataIndex: 'status',
        width: 80,
        align: 'center',
      }, {
        title: '操作',
        dataIndex: '6',
        width: 100,
        align: 'center',
        render: (text, data) => {
          return (
            data.operationSetID ? <span>
              <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
              <span className='span' onClick={this.editData.bind(this, data)}>编辑</span><br />
              <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
              <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDel.bind(this, data)} >
                <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
              </Popconfirm>
            </span > : null
          )
        }
      }
    ]
  }

  loadColumns() {
    var dynColumns = [{
      key: 1,
      title: '手术',
      dataIndex: 'operationDesc',
      align: "center",
      width: '300px',
      render: (text, record, index) => {
        return (
          <Input
            allowClear={true}
            autoFocus
            onClick={this.handleStopPropagation}
            id={"operation-input" + index}
            value={record.operationDesc}
            onFocus={this.onDiagDescFocus.bind(this, index)}
            style={{ width: "100%", textAlign: "left" }}
            onChange={this.handleFieldChange.bind(this, index, 'operationDesc')}
            onPressEnter={this.getOperationData}
            disabled={false}
            autoComplete="off"
          />
        )
      }

    }, {
      key: 5,
      title: '手术分类',
      dataIndex: 'classification',
      align: "center",
      width: '100px',
      render: (text, record, index) => {
        return (
          <Select
            value={record.classification}
            allowClear
            style={{ width: "100%", textAlign: "left" }}
            onChange={this.handleFieldChange.bind(this, index, 'classification')}
            disabled={false}
            showSearch
            optionFilterProp='role'
          >
            {this.state.classificationData.map(data => (
              <Select.Option
                role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                key={data.id}
              >
                {data.descripts}
              </Select.Option>))}
          </Select>
        )
      }
    }, {
      key: 6,
      title: '手术项目类型',
      dataIndex: 'projectType',
      align: "center",
      width: '100px',
      render: (text, record, index) => {
        return (
          <Select
            value={record.projectType}
            allowClear
            style={{ width: "100%", textAlign: "left" }}
            disabled={false}
            showSearch
            placeholder="请选择项目类型"
            optionFilterProp="seachprop"
            onChange={this.handleFieldChange.bind(this, index, 'projectType')}
            onFocus={() => this.handleProjectTypeFocus(record, index)}
          >
            {React.$SelectOptions(record?.projectTypeData || [])}
          </Select>
        )
      }
    }, {
      key: 2,
      title: '级别',
      dataIndex: 'categoryID',
      align: "center",
      width: '100px',
      render: (text, record, index) => {
        return (
          <Select
            value={record.categoryID}
            allowClear
            style={{ width: "100%", textAlign: "left" }}
            onChange={this.handleFieldChange.bind(this, index, 'categoryID')}
            disabled={false}
            showSearch
            optionFilterProp='role'
          >
            {this.state.operationLevelData.map(data => (
              <Select.Option
                role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                key={data.id}
              >
                {data.descripts}
              </Select.Option>))}
          </Select>
        )
      }
    }, {
      key: 3,
      title: '手术部位',
      dataIndex: 'operationPart',
      align: "center",
      width: '100px',
      render: (text, record, index) => {
        return (
          <Select
            mode="multiple"
            value={record.operationPart ? record.operationPart : ''}
            allowClear
            style={{ width: "100%", textAlign: "left" }}
            onChange={this.handleFieldChange.bind(this, index, 'operationPart')}
            disabled={false}
            showSearch
            optionFilterProp='role'
          >
            {this.state.operationPartData.map(data => (
              <Select.Option
                role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                key={data.id}
              >
                {data.descripts}
              </Select.Option>))}
          </Select>
        )
      }
    }, {
      key: 4,
      title: '切口',
      dataIndex: 'incisionID',
      align: "center",
      width: '100px',
      render: (text, record, index) => {
        return (
          <Select
            value={record.incisionID}
            allowClear
            style={{ width: "100%", textAlign: "left" }}
            onChange={this.handleFieldChange.bind(this, index, 'incisionID')}
            disabled={false}
            showSearch
            optionFilterProp='role'
          >
            {this.state.operationCutData.map(data => (
              <Select.Option
                role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}
                key={data.id}
              >
                {data.descripts}
              </Select.Option>))}
          </Select>
        )
      }
    }, {
      key: 7,
      title: '手术备注',
      dataIndex: 'notes',
      align: "center",
      width: '150px',
      render: (text, record, index) => {
        return (
          <Input
            onClick={this.handleStopPropagation}
            value={record.notes}
            style={{ width: "100%", textAlign: "left" }}
            onChange={this.handleFieldChange.bind(this, index, 'notes')}
            disabled={false}
          />
        )
      }
    }];
    var operationColumns = [{
      title: 'ICD编码',
      dataIndex: 'ICDCode',
      width: 80,
      align: 'left',
    }, {
      title: '名称',
      dataIndex: 'descripts',
      width: 200,
      align: 'left',
    }, {
      title: '手术级别',
      dataIndex: 'categoryDesc',
      width: 200,
      align: 'left',
    }]
    this.setState({
      dynColumns: dynColumns,
      operationColumns: operationColumns
    })
  }

  // 手术项目类型获取焦点事件
  handleProjectTypeFocus = async (record, index) => {
    let oldProjectTypeData = record?.projectTypeData || [];
    if (record && 'classification' in record && record.classification && oldProjectTypeData && oldProjectTypeData.length < 2) { // 默认进来有一条已选择的数据
      let projectTypeData = await this.getOperationProjType(record.classification);
      this.state.dataSource[index].projectTypeData = projectTypeData;
      this.setState({});
    }
  }

  // 获取主表表单数据
  getMainFormData = () => {
    let mainFormData = [{
      dataIndex: 'operationSetDesc',
      title: '名称',
      typeCode: 'Input',
      required: 'Y'
    }, {
      dataIndex: 'operationSetAlias',
      title: '别名',
      typeCode: 'Input',
      required: 'Y'
    }, {
      dataIndex: 'authRangeID',
      title: '使用级别',
      typeCode: 'Select',
      detailItem: this.state.levelDataOption || []
    }, {
      dataIndex: 'startDate',
      title: '开始日期',
      typeCode: 'Date',
      required: 'Y',
      default: 0,
    }, {
      dataIndex: 'stopDate',
      title: '结束日期',
      typeCode: 'Date'
    }];
    this.setState({ mainFormData })
  }

  // 记录表单的值
  recordMainFormInput = record => {
    this.setState({ cpmpleteData: { ...this.state.cpmpleteData, ...record } })
  }

  isEditing = (record) => {
    return record.key === this.state.editingKey
  }

  //获取焦点时触发
  onDiagDescFocus = (index, e) => {
    this.setState({
      selectIndex: index,
    })
  }

  // 阻止默认事件
  handleStopPropagation = (e) => {
    if (typeof e == 'object') {
      e.stopPropagation();
    }
  }

  // 获取手术下拉框数据
  getOperationData = (e) => {
    let searchCode = e.target ? e.target.value : this.state.searchCode
    if (searchCode != '') {
      this.setState({
        searchCode: searchCode,
      })
    }
    let data = {
      params: [{
        admID: (this.state.patientData && this.state.patientData.admID) ? this.state.patientData.admID : '',
        searchCode: searchCode ? searchCode : this.state.searchCode
      }],
      pagination: [{
        pageSize: this.state.pageSize,
        currentPage: this.state.page
      }]
    };
    $http.post('urlDeault', this, {
      code: "04160041",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let rowMedID = "";
          if ((res.result.Data) && (res.result.Data.length > 0)) {
            rowMedID = res.result.Data[0].id
          }
          this.setState({
            rowMedID: rowMedID,
            operationData: res.result.Data,
            total: res.result.TotalCount,
          }, () => this.child.showModal())
        }
      },
      error: function (error) {
        message.error('失败：' + error);
      }
    });
  }

  // 获取手术项目类型
  getOperationProjType = async (classID) => {
    try {
      let data = {
        params: [{
          classID
        }]
      }
      let res = await React.$asyncPost(this, '04160025', data);
      return res?.result || ''
    } catch (error) {
      return []
    }
  }

  // 表格下拉框选中
  handleFieldChange = async (index, code, value, opt) => {
    let top = document.getElementById("operation-input" + index).getBoundingClientRect().top + 40
    let left = document.getElementById("operation-input" + index).getBoundingClientRect().left;
    let windowHeight = window.innerHeight;
    if ((top + 360) > windowHeight) {
      top = top - 330 - 80;
    }
    top = top + "px";
    left = left + "px";
    let { dataSource, operationPartPar } = this.state;
    if (value !== undefined) {
      if (code === 'operationPart') {
        operationPartPar = [];
        for (var key in value) {
          operationPartPar.push(value[key])
        }
        dataSource[index].operationPart = operationPartPar;
      }
      else if (code === 'notes') {
        if (value.target.value.length > 50) {
          message.warning('备注超长');
          return;
        }
        dataSource[index][code] = (typeof (value) == 'string') ? value : value.target.value;
      }
      else if (code == 'classification') {
        dataSource[index].projectType = undefined;
        let projectTypeData = await this.getOperationProjType(value);
        dataSource[index].projectTypeData = projectTypeData;
        dataSource[index][code] = (typeof (value) == 'string') ? value : value.target.value;
      }
      else {
        dataSource[index][code] = (typeof (value) == 'string') ? value : value.target.value;
      }
    } else {
      dataSource[index][code] = '';
      if (code == 'classification') {
        dataSource[index].projectType = undefined;
        dataSource[index].projectTypeData = [];
      }
    }
    this.setState({
      dataSource,
      operationPartPar,
      top: top,
      left: left,
    })
  }

  // 获取下拉框数据
  getSelectData = () => {
    var userData = this.state.userData
    let data = {
      params: [{
        hospID: userData && userData.hospID ? userData.hospID : '', // 登录医院id       
        locID: userData.locID,
        admID: (this.state.patientData && this.state.patientData.admID) ? this.state.patientData.admID : '',
        patID: (this.state.patientData && this.state.patientData.patID) ? this.state.patientData.patID : '',
      }]
    }
    $http.post('urlDeault', this, {
      code: "04160001",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            locType: res.locType,
            operationDocData: res.DoctorArr,
            assistantDocData: res.NurseArr,

            operationPostData: res.OperationPosition,
            operationCutData: res.IncisionType,
            operationPartData: res.OperationPart,
            operationLevelData: res.OperationCategory,
            anesthesiaData: res.anesthesiaMode,
            classificationData: res.operationClass,
            motivationData: res.operationMotivation.data,
            surgicalPopulationData: res.surgicalPopulationData,
            crystalsRepReasonArr: res.crystalsRepReasonArr,
            anaesthesiaDocaArr: res.anaesthesiaDocaArr,
            docECGDocArr: res.docECGDocArr,
            triageAssociatedData: res.triageAssociatedData,
          });
          //this.addMechansim()
        }
      },
      error: function (error) {
        message.error('失败：' + error);
      }
    });
  }

  // 添加行
  addMechansim = () => {
    const { dataSource } = this.state;
    if ((dataSource.length > 0) && (dataSource[dataSource.length - 1]) && (dataSource[dataSource.length - 1]['operationID'] === '')) {
      message.warning('请先选择上一条记录的科手术');
      return;
    }
    console.log(this.state.dataSource)
    let newData = dataSource.map((item) => ({ ...item }));
    // 重新修改数据key
    for (let i = 0; i < newData.length; i++) {
      newData[i].key = i
      newData[i].seqNo = i + 1
    }
    tableRecord = {
      key: newData.length,
      seqNo: dataSource.length + 1,
      operationDesc: '',
      operationID: '',
      categoryID: '',
      operationPart: [],
      incisionID: '',
      notes: '',
      classification: '',
      projectType: '',
      motivation: '',
      editable: true
    }
    newData.push(tableRecord);
    this.setState({
      tableRecord: tableRecord,
      dataSource: newData,
      editingKey: newData.length - 1
    });
  }

  editData(data) {
    this.setState({
      cpmpleteData: data
    })
    console.log(data)
    this.mainModalRef && this.mainModalRef.modifyVisible(true);
  }

  onBlurFreqSelect(name, index, data, e) {
    var params = {
      params: [{
        hospID: this.state.userData.hospID
      }]
    }
    $http.post('urlDeault', this, {
      code: "03050143",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          this.state.dataSource[index]['frequenceList'] = res.result
          this.setState({})
        }
      }
    });
  }

  changeMedItemDescFocus(index) {
    this.setState({
      edit: false
    })
  }

  handleDel(data) {
    var params = {
      params: [{
        userID: this.state.userData.userID,
        operationSetID: data.operationSetID
      }]
    }
    $http.post('urlDeault', this, {
      code: "04160042",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          message.success('删除成功！', this.state.userData && this.state.userData.messageTime)
          this.loadLeftData()
        }
      }
    });
  }

  loadData() {

  }

  loadLeftData(page, pageSize, e) {
    this.setState({
      leftData: [],
    });
    var params = {
      params: [{
        userID: this.state.userData.userID,
        locID: this.state.userData.locID,
        hospID: this.state.userData.hospID,
        groupID: this.state.userData.groupID,
        activeFlag: this.state.activeFlag,
        selfFlag: this.state.selfFlag,
        searchCode: this.state.searchCode,

      }]
    }
    $http.post('urlDeault', this, {
      code: "04160038",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          this.setState({
            leftData: res.data.list || [],
          })
        }
      }
    });
  }

  //分页切换
  onChange(e) {
    this.setState({ page: e }, () => {
      this.loadData(e);
    });
  }

  //分页切换
  changePageSize(current, pageSize) {
    this.setState({ pageSize: pageSize, page: current }, () => {
      this.loadSelectData('', current, pageSize, 'search');
    });
  }

  changeLeftCheckBox(name, e) {
    this.setState({
      [name]: e.target.checked ? 'Y' : 'N'
    }, () => {
      this.loadLeftData()
    })
  }

  changeExpanded(expaded, record) {
    let id = record.id;
    if (Util.isEmpty(this.state.subrateData[id])) {
      this.fetchsubMerchant(id);
    }
  }
  //删除
  delMechansim() {
    // this.loadDeleteTemplate()
    var flag = true;
    var that = this;
    var { dataSource, ids, checkData } = this.state;
    if (ids.length < 1) {
      message.error('请选择你需要删除的数据', this.state.userData && this.state.userData.messageTime)
      return
    }

    confirm({
      title: '删除',
      content: '您确定要删除选中的数据吗？',
      onOk() {
        for (var i = 0; i < checkData.length; i++) {
          for (var j = 0; j < dataSource.length; j++) {

            if (!Util.isEmpty(checkData[i].operationSetDetailID) && dataSource[j].key == checkData[i].key) {
              //防止删除时，多次调用
              if (flag) {
                flag = false
                that.loadDeleteTemplate()
                // that.state.dataSource.splice(j, 1);
              }
            } else {
              if (checkData[i].key == dataSource[j].key) {
                that.state.dataSource.splice(j, 1);
              }
            }
          }
        }
        that.setState({ ids: [] })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  //插入手术
  insertDoctorAdvice = async () => {
    var { dataSource, operationSetID, completeColData } = this.state;
    this.setState({ saveStatus: true })
    var temp = []
    try {
      let data = {
        params: [{
          userID: this.state.userData.userID,
          locID: this.state.userData.locID,
          hospID: this.state.userData.hospID,
          groupID: this.state.userData.groupID,
          operationSetID,
          dataSource
        }]
      }
      console.log("data:", data)
      let res = await React.$asyncPost(this, '04160043', data);
      message.success(res.errorMessage ? res.errorMessage : '保存成功');
      this.setState({ saveStatus: false })
    } catch (error) {
      this.setState({ saveStatus: false })
    }
  }
  loadListData(e) {
    if (e.keyCode == '13') {
      var params = {
        params: [{
          userID: this.state.userData.userID,
          locID: this.state.userData.locID,
          hospID: this.state.userData.hospID,
          groupID: this.state.userData.groupID,
          activeFlag: this.state.activeFlag,
          selfFlag: this.state.selfFlag,
          searchCode: this.state.searchCode,

        }]
      }
      $http.post('urlDeault', this, {
        code: "04160038",
        data: params,
        success: function (res) {
          if (res.errorCode == '0') {
            this.setState({
              leftData: res.data.list,
            })
          }
        }
      });
    }
  }

  setRowElement = (record, index) => {
    return {
      onDoubleClick: () => {
        this.rowClick(record, index)
      }
    }
  }

  rowClick = (record, index) => {
    if (!Util.isEmpty(record.operationSetID)) {
      message.error('手术套维护中无法添加手术套，请重新选择', this.state.userData && this.state.userData.messageTime)
      return
    }
    this.setState({
      visible: false,
      rowData: record.medDesc,
      ordSpecID: record.ordSpecID,
      selectData: [],
      visStatus: false,
      // changeValue: undefined
    }, () => {
      this.child.handleCancel();
      this.loadTableData('', record, index)
    })
  }

  //获取列表行数据
  loadTableData(status, record, data) {
    var that = this;
    var date = new Date();
  }

  //隐藏弹出框
  hideModal(name) {
    this.setState({
      [name]: false,//将所有参数置为false
      cpmpleteData: {}
    });
  }

  //成套医嘱弹框
  showCompleteMedicalModal() {
    this.setState({
      cpmpleteData: {}
    });
    this.mainModalRef && this.mainModalRef.modifyVisible(true);
  }

  loadDeleteTemplate() {
    var { ids, checkData, dataSource } = this.state;
    var code = []
    for (var i = 0; i < checkData.length; i++) {
      if (!Util.isEmpty(checkData[i].operationSetDetailID)) {
        code.push(checkData[i].operationSetDetailID)
      }
    }
    var params = {
      params: [{
        operationSetDetailID: code,
        userID: this.state.userData.userID
      }],
    }
    $http.post('urlDeault', this, {
      code: "03050065",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          message.success('删除成功', this.state.userData && this.state.userData.messageTime)
          var source = []
          if (!Util.isEmpty(dataSource)) {
            for (var i = 0; i < dataSource.length; i++) {
              for (var j = 0; j < checkData.length; j++) {
                if (dataSource[i].operationSetDetailID == checkData[j].operationSetDetailID) {
                  // source.push(dataSource[i])
                  this.state.dataSource.splice(i, 1);
                }
              }
            }
          } else {
            this.state.dataSource = []
          }
          this.setState({})
          // this.loadCompleteDetail('temp')
        }
      }
    });
  }

  //上移
  handleUpSort() {
    var keys = []
    var check = this.state.checkData

    //createBy: DYK
    if (check.length === 0) {
      message.warning('请先选择要移动的手术！');
      return;
    }

    if (!Util.isEmpty(check)) {
      for (var i = 0; i < check.length; i++) {
        keys.push(check[i].key)
      }
    }
    var data = this.state.dataSource
    var newKeys = []
    var temp = []
    for (var i = 0; i < data.length; i++) {
      if (!Util.isEmpty(data[i].operationSetDetailID)) {
        temp.push(data[i])
      }
    }
    keys = keys.sort(function (m, n) {
      if (m < n) return -1
      else if (m > n) return 1
      else return 0
    });
    for (var i = 0; i < keys.length; i++) {
      if (keys[i] - 1 === 0) {
        newKeys.push(keys[i])
        // continue
        message.warn('已经到顶了，无法再移动！', this.state.userData && this.state.userData.messageTime)
        return
      }
      // if (keys[i] == data[keys[i]-1].tabIndex) {
      var curRowData = data[keys[i] - 1]

      var curRowKey = curRowData.key
      var upRowData = data[keys[i] - 2]
      var upRowKey = upRowData.key
      upRowData.key = curRowKey
      curRowData.key = upRowKey

      data[keys[i] - 1] = upRowData
      data[keys[i] - 2] = curRowData
      newKeys.push(keys[i] - 1)
      if (Util.isEmpty(data[keys[i] - 2].key)) {
        return
      }
    }
    this.setState(
      {
        dataSource: data,
      }
    )
  }

  //下移
  handleDownSort() {
    var keys = []
    var check = this.state.checkData
    //createBy: DYK
    if (check.length === 0) {
      message.warning('请先选择要移动的手术！');
      return;
    }
    if (!Util.isEmpty(check)) {
      for (var i = 0; i < check.length; i++) {
        keys.push(check[i].key)
      }
    }
    var data = this.state.dataSource
    var newKeys = []
    keys = keys.sort(function (m, n) {
      if (m < n) return -1
      else if (m > n) return 1
      else return 0
    });
    for (var i = keys.length - 1; i >= 0; i--) {
      if (keys[i] === data.length) {
        newKeys.push(keys[i])
        // continue
        message.warn('已经到底了，无法再移动！', this.state.userData && this.state.userData.messageTime)
        return
      }

      var curRowData = data[keys[i] - 1]
      var upRowData = data[keys[i]]
      var curRowKey = curRowData.key
      var upRowKey = upRowData.key
      upRowData.key = curRowKey
      curRowData.key = upRowKey
      data[keys[i] - 1] = upRowData
      data[keys[i]] = curRowData
      newKeys.push(keys[i] + 1)
    }

    this.setState(
      {
        dataSource: data,
      }
    )
  }

  onSelectChange(ids, data) {
    this.setState({
      ids: ids,
      checkData: data
    })
  }

  //根据正选和反选，向对应数据增加一个标识，处理反选下拉依旧置灰问题
  onSelect(data, flag) {
    var selectData = []
    this.state.selectData.push(data)
    if (flag) {
      data['checkIdenty'] = '2'
    } else {
      data['checkIdenty'] = '1'
      //去除缓存的moveStatus标识    changeBY: DYK
      delete data.moveStatus;
    }
    this.setState({})
  }

  onSelectAll(flag, selectedRows, changeRows) {
    this.state.selectData.push(changeRows)
    for (var i = 0; i < changeRows.length; i++) {
      if (flag) {
        changeRows[i]['checkIdenty'] = '2'
      } else {
        changeRows[i]['checkIdenty'] = '1'
      }
    }
    this.setState({})
  }

  //添加成套医嘱
  handleComplete = async values => {
    try {
      let data = {
        params: [{
          code: values.operationSetDesc,
          descripts: values.operationSetDesc,
          alias: values.operationSetAlias,
          authRangeID: values.authRangeID,
          startDate: values.startDate,
          stopDate: values.stopDate,
          userID: this.state.userData.userID,
          locID: this.state.userData.locID,
          hospID: this.state.userData.hospID,
          operationSetID: this.state.cpmpleteData.operationSetID,
        }]
      }
      let res = await React.$asyncPost(this, '04160039', data);
      message.success(res.errorMessage ? res.errorMessage : '保存成功');
      this.mainModalRef && this.mainModalRef.modifyVisible(false, 'Y');
      this.loadLeftData()
    } catch (error) {
      this.setState({
        tableData: [],
        dataSource: [], mainTotal: 0, loading: false
      })
    }
  }

  loadCompleteDetail(status) {
    this.setState({
      saveStatus: true
    })
    var that = this;
    var date = new Date()
    var params = {
      params: [{
        userID: this.state.userData.userID,
        locID: this.state.userData.locID,
        hospID: this.state.userData.hospID,
        groupID: this.state.userData.groupID,
        operationSetID: this.state.operationSetID,
      }]
    }
    $http.post('urlDeault', this, {
      code: "04160040",
      data: params,
      success: function (res) {
        this.setState({
          saveStatus: false
        })
        if (res.errorCode == '0') {
          let operationDetail = res.result.data[0].operationDetail;
          if (operationDetail.length > 0) {
            for (var i = 0; i < operationDetail.length; i++) { // 用于第一次回显手术项目类型
              if (operationDetail[i] && operationDetail[i].projectType) {
                operationDetail[i].projectTypeData = [{
                  id: operationDetail[i].projectType,
                  descripts: operationDetail[i].projectTypeDesc,
                }]
              }
            }
            this.setState({
              dataSource: operationDetail,
            }, () => {
              //this.handleFieldChange (index, code, value)

            })
          } else {
            this.setState({
              dataSource: [],
            })
          }
          this.deleteNullData()
        }
      },
      error: function () {
        this.setState({
          saveStatus: false
        })
      }
    });
  }

  //点击行，渲染当前行样式
  onClickRow = (record, index) => {
    return {
      onClick: () => {
        this.setState({
          completeColData: record,
          operationSetID: record.operationSetID,
          indexTable: this.state.dataSource.length - 1,
          groupStatus: false, batchStatus: false,
          ids: []
        }, () => {
          record.operationSetID ? this.loadCompleteDetail() : ''
          // this.loadCompleteDetail()
        })
      },
    };
  }

  //点击行，渲染当前行样式
  setRowClassName = (record) => {
    return this.state.operationSetID && this.state.operationSetID == record.operationSetID ? 'clickRowStyle' : '';
  }

  onClickRightRow = (record, index) => {
    return {
      onClick: () => {
        this.setState({
          rightData: record,
          rightIndex: index,
          edit: true
        })
      }
    }
  }

  deleteNullData() {
    var data = []
    var that = this;
    var { dataSource, ids } = this.state;
    for (var j = 0; j < dataSource.length; j++) {
      if (Util.isEmpty(dataSource[j].operationID)) {
        that.state.dataSource.splice(j, 1);
      }
    }
    that.setState({})
  }

  setRowClassNamePublic = (record) => {
    return record.medID === this.state.rowMedID ? 'clickRowStyle' : '';
  }

  onRef = (ref) => {
    this.child = ref;
  }

  //操作弹框
  onClickRowPublic = (record, index) => {
    return {
      onDoubleClick: () => {
        // if (!record.categoryID) {
        // 	message.warning('该手术无手术级别，请与医务科联系')
        // 	return;
        // }
        let { dataSource, editingKey } = this.state;
        dataSource[editingKey].operationID = record.id;
        dataSource[editingKey].operationDesc = record.descripts;
        dataSource[editingKey].categoryID = record.categoryID;
        dataSource[editingKey].insuCode = record?.insuCode || '';
        dataSource[editingKey].insuDesc = record?.insuDesc || '';
        this.setState({ dataSource }, () => {
          this.child.handleCancel();
        })
      },
      onClick: () => {
        this.setState({
          rowMedID: record.id
        })
      }
    }
  }

  //取消弹框显示，焦点问题
  handleFocus() {
    this.setState({
      operationData: []
    }, () => {
      if ((this["operationDesc" + this.state.selectIndex]) && (this["operationDesc" + this.state.selectIndex].current)) {
        this["operationDesc" + this.state.selectIndex].current.focus()
      }
    })
  }

  handleOnKeydown(e) {
    var e = window.event || e;
    let scroll_height = 50;
    let id = '';
    let oneArr = this.state.selectData && this.state.selectData.length > 0 ? this.state.selectData : [];
    switch (e.keyCode) {
      case 13:
        if (this.state.rowMedID) {
          let obj = {}
          for (var i = 0; i < oneArr.length; i++) {
            if (oneArr[i].medID === this.state.rowMedID) {
              obj = i > 0 ? oneArr[i] : oneArr[0];
              break;
            }
          }
          this.rowClick(obj);
        } else {
          message.info("请选择一条需要操作的数据", this.state.userData && this.state.userData.messageTime)
        }
        break;
      case 38: //上
        if (this.state.rowMedID) {
          for (var i = 0; i < oneArr.length; i++) {
            if (oneArr[i].medID === this.state.rowMedID) {
              id = i > 0 ? oneArr[i - 1].medID : oneArr[0].medID;
              break;
            }
          }
          this.setState({ rowMedID: id }, () => {
            var gundong = document.getElementById("gundong");
            gundong.scrollTop = gundong.scrollTop - scroll_height;
          })
        } else {
          this.setState({ rowMedID: oneArr[0].medID })
        }
        break;
      case 40: //下
        if (this.state.rowMedID) {
          for (let i = 0; i < oneArr.length; i++) {
            if (oneArr[i].medID === this.state.rowMedID) {
              id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].medID : oneArr[i + 1].medID;
              break;
            }
          }
          this.setState({ rowMedID: id }, () => {
            var gundong = document.getElementById("gundong");
            gundong.scrollTop = gundong.scrollTop + scroll_height;
          })
        } else {
          this.setState({ rowMedID: oneArr[0].medID })
        }
        break;
    }
  }

  onColumnRef = (ref) => {
    this.columnRef = ref;
  }

  render() {
    var { ids, dataSource, page, total, top, left, totalWidth, operationColumns } = this.state;
    const rowSelection = {
      ids,
      onChange: this.onSelectChange.bind(this),
      onSelect: this.onSelect.bind(this),
      onSelectAll: this.onSelectAll.bind(this),
      selectedRowKeys: ids,
    }
    let param = {
      width: '800px',
      height: 330,
      top: top,
      left: left,
      bordered: true,
      columns: operationColumns && operationColumns.length > 0 ? operationColumns : this.operationColumns,
      data: this.state.operationData,
      isOnRow: true,
      TableClassName: 'tab-placeholder',
      rowClassName: true,
      showPagination: true,
      total,
      page,
      x: 600,
    }
    return (
      <Spin spinning={this.state.saveStatus} tip='加载中...'>
        <div className='complete-body' style={{ height: '100%', width: '100%', background: '#F5F7FE' }}>
          {/**列input框新表格弹框 */}
          <div
            tabIndex={1}
            onKeyDown={this.handleOnKeydown.bind(this)}
            style={{ outline: 'none' }}
          >
            <PublicModalFormHooks
              onRef={ref => this.mainModalRef = ref}
              formData={this.state.mainFormData}
              rowData={this.state.cpmpleteData}
              formItemCol={{ labelCol: 5, wrapperCol: 16, col: 24 }}
              recordFormInput={this.recordMainFormInput}
              handleSave={this.handleComplete}
            />
            <ShowCommonTableModal onClickRowPublic={this.onClickRowPublic}
              handleFocus={this.handleFocus.bind(this)}
              setRowClassNamePublic={this.setRowClassNamePublic}
              param={param}
              onRef={this.onRef}
              id="gundong"
              search={this.state.search}
              compilePage={this.changePageSize.bind(this)}>
            </ShowCommonTableModal>
          </div>
          {/**确认医嘱弹框 */}
          <Card className='complete-left-card' hoverable={true} title={<span style={{ marginLeft: 10 }}>手术套餐</span>}>
            <div style={{ display: 'flex', marginTop: 10 }}>
              <Input placeholder='输入名称/别名回车查询' onChange={Util.commonInputChange.bind(this, 'searchCode')}
                onKeyDown={this.loadListData.bind(this)} style={{ width: '65%' }} />
              <Button style={{ marginLeft: 5 }} type='primary' onClick={this.showCompleteMedicalModal.bind(this)}>+手术套餐</Button>
            </div>

            <div style={{ marginTop: 10 }}>
              <Checkbox onChange={this.changeLeftCheckBox.bind(this, 'activeFlag')} />仅显示生效
              <Checkbox onChange={this.changeLeftCheckBox.bind(this, 'selfFlag')} />仅显示本人添加的手术套
            </div>
            <div style={{ marginTop: 5 }}>
              <Table
                columns={this.leftColumns}
                dataSource={this.state.leftData}
                loadData={this.loadLeftData.bind(this)}
                onRow={this.onClickRow}
                expandRowByClick={true}
                rowClassName={this.setRowClassName}
                scroll={{ y: store.getState().tableHeight.y + 80 }}
                rowKey={(data) => {
                  return data.authID || data.operationSetID
                }}
                pagination={false}
              >

              </Table>
            </div>
          </Card>
          <Card className='complete-right-card' hoverable={true} title={<span style={{ marginLeft: 10 }}>手术套明细项维护</span>}>
            {this.state.operationSetID ? <div>{this.state.completeColData ? <div style={{ background: '#d4e9fd' }}>
              <span>当前套餐：{this.state.completeColData ? this.state.completeColData.operationSetDesc : ''}</span>
              <Divider type="vertical" style={{ background: 'rgba(0, 0, 0, 0.65)' }} />
              <span>{this.state.completeColData ? this.state.completeColData.authRangeDesc : ''}套餐</span>
            </div> : null}
              <div style={{ height: 40, lineHeight: '40px' }}>
                <span style={{ cursor: 'pointer' }}
                  onClick={this.addMechansim.bind(this)}>
                  <Icon className='doctor-add-splice' />
                  <span>添加</span>
                </span>
                <span style={{ cursor: 'pointer', marginLeft: 10 }}
                  onClick={this.delMechansim.bind(this)}>
                  <Icon className='doctor-delete-splice' />
                  <span>删除</span>
                </span>
                <span style={{ cursor: 'pointer', marginLeft: 10 }}
                  onClick={this.handleUpSort.bind(this)}
                >
                  <Icon className='doctor-up-splice' />
                  <span>上移</span>
                </span>
                <span style={{ cursor: 'pointer', marginLeft: 10 }}
                  onClick={this.handleDownSort.bind(this)}
                >
                  <Icon className='doctor-down-splice' />
                  <span>下移</span>
                </span>
                <Button size='small' type='primary' style={{ marginLeft: 10 }} onClick={this.insertDoctorAdvice.bind(this)}>保存</Button>
              </div>
              <Table columns={this.state.dynColumns}
                dataSource={dataSource}
                loadData={this.loadData.bind(this)}
                onRow={this.onClickRightRow}
                rowSelection={rowSelection}
                rowClassName={(data) => {
                  return data.ordBilledCode == 'P' ? 'rowClassStyle' : ''
                }}
                scroll={{ x: totalWidth, y: store.getState().tableHeight.y + 40 }}
                bordered
                title={() => {
                  return <span>提示信息</span>
                }}
                onHeaderRow={column => {
                  return {
                    onDoubleClick: () => {
                      this.columnRef.onOpenModel();
                    },
                  };
                }}
                rowKey={(data) => {
                  return data.tabIndex || data.operationSetDetailID
                }}
                pagination={false}></Table></div> : '请选择对应的手术套进行手术添加！'}
          </Card>
        </div>
      </Spin>
    )
  }
}

export default OperationSetMaintain;