<template>
  <div @contextmenu="onContextmenu">
    <div style="display: flex; flex-wrap: wrap;height:70px; width: 100%;overflow-y: auto;">
      <div>
        <span class="query">条码号</span>
        <el-input ref="tmh" placeholder="条码号" v-model="prBase.patientRegisterNo" size="small" style="width: 120px;"
          clearable />
      </div>
      <div>
        <el-tooltip content="点击显示该人员调查问卷信息" placement="top">
          <el-button type="primary" style="margin-left: 5px;margin-top: 3px; height: 22px;padding: 2px 2px;"
            @click="btnQuestion">档案号</el-button>
        </el-tooltip>
        <el-input placeholder="档案号" v-model="prBase.patientNo" size="small" style="width: 90px;" clearable />
      </div>
      <div>
        <span class="query">姓名</span>
        <el-input placeholder="姓名" v-model="prBase.patientName" size="small" style="width: 100px;" clearable />
      </div>
      <div>
        <span class="query">检查条码</span>
        <el-input placeholder="检查条码" v-model="prBase.pacsNo" size="small" style="width: 120px;" clearable />
      </div>
      <div>
        <span class="query">检验条码</span>
        <el-input placeholder="检验条码" v-model="prBase.lisNo" size="small" style="width: 120px;" clearable />
      </div>
      <div>
        <el-button type="primary" style="margin-left: 5px;margin-top: 3px; height: 22px;padding: 2px 2px;"
          @click="readIdCard">读身份证</el-button>
        <el-input placeholder="身份证号" v-model="prBase.idNo" size="small" style="width: 150px;" clearable />
      </div>
      <div>
        <span class="query">手机</span>
        <el-input placeholder="手机号" v-model="prBase.mobileTelephone" style="width: 120px;" size="small" clearable />
      </div>
      <div>
        <span class="query">性别</span>
        <!--
        <el-select v-model="prBase.sexId" style="width: 80px;" size="small" disabled>
          <el-option v-for="item in dict.sex" :key="item.id" :label="item.displayName" :value="item.id" />
        </el-select>
        -->
        <el-input v-model="prBase.sexName" size="small" style="width: 40px;" disabled />
      </div>
      <div>
        <span class="query">年龄</span>
        <el-input v-model="prBase.age" size="small" style="width: 40px;" disabled />
      </div>
      <div>
        <span class="query">体检次数</span>
        <el-input v-model="prBase.medicalTimes" size="small" style="width: 40px;" disabled />
      </div>
      <div>
        <span class="query">婚姻</span>
        <!--
        <el-select v-model="prBase.maritalStatusId" style="width: 80px;" size="small" disabled>
          <el-option v-for="item in dict.maritalStatus" :key="item.id" :label="item.displayName" :value="item.id" />
        </el-select>
        -->
        <el-input v-model="prBase.maritalStatusName" size="small" style="width: 40px;" disabled />
      </div>
      <div>
        <span class="query">体检日期</span>
        <el-input :value="prBase.medicalStartDate ? lmoment(prBase.medicalStartDate, 'yyyy-MM-DD') : ''"
          style="width: 100px;" size="small" disabled></el-input>
      </div>
      <div>
        <span class="query">单位</span>
        <el-input v-model="prBase.customerOrgParentName" style="width: 150px;" size="small" disabled />
      </div>
      <div>
        <span class="query">部门</span>
        <el-input v-model="prBase.customerOrgName" style="width: 120px;" size="small" disabled />
      </div>
      <div>
        <span class="query">体检类别</span>
        <!--
        <el-select v-model="prBase.medicalTypeId" disabled style="width: 100px;" size="small">
          <el-option v-for="item in dict.medicalType" :key="item.id" :label="item.displayName" :value="item.id" />
        </el-select>
        -->
        <el-input v-model="prBase.medicalTypeName" style="width: 100px;" size="small" disabled />
      </div>
      <div>
        <span class="query">人员类别</span>
        <!--
        <el-select v-model="prBase.personnelTypeId" disabled style="width: 100px;" size="small">
          <el-option v-for="item in dict.personnelType" :key="item.id" :label="item.displayName" :value="item.id" />
        </el-select>
        -->
        <el-input v-model="prBase.personnelTypeName" style="width: 100px;" size="small" disabled />
      </div>
      <div>
        <span class="query">民族</span>
        <!--
        <el-select v-model="prBase.nationId" disabled style="width: 100px;" size="small">
          <el-option v-for="item in dict.nation" :key="item.id" :label="item.displayName" :value="item.id" />
        </el-select>
        -->
        <el-input v-model="prBase.nationName" style="width: 80px;" size="small" disabled />
      </div>
    </div>

    <!-- 体检人员记录列表 -->
    <el-dialog title="体检人员列表" :visible.sync="dialogWin.PatientRegisterForChoose" width="800px" :show-close="false"
      :close-on-click-modal="false" :append-to-body="true">
      <PatientRegisterForChoose :params="PatientRegisterList" @chooseBak="chooseBak" />
    </el-dialog>

    <el-dialog title="调查问卷" :visible.sync="dialogWin.question" width="800px" :close-on-click-modal="false"
      :append-to-body="true">
      <Question :refParams="questionParams" />
    </el-dialog>
  </div>
</template>
<script>
import moment from "moment";
import { mapState, mapMutations } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { dddw, deepCopy, objCopy, opjCopy, parsIcCardtoLocal } from '../../utlis/proFunc'
import PatientRegisterForChoose from "../../components/patientRegister/PatientRegisterForChoose.vue";
import Question from "../../components/doctorCheck/Question.vue";

export default {
  components: {
    PatientRegisterForChoose, Question
  },
  props: ["refParams"],
  data() {
    return {
      dialogVisible: false,
      prBase: {
        id: '', //体检登记ID
        patientRegisterNo: '', //条码号
        pacsNo: '', //
        lisNo: '',
        patientNo: '', //档案号
        patientName: '', //姓名
        sexId: '', //性别
        sexName: '', //性别
        idNo: '', // 身份证号
        age: '',   // 年龄
        medicalTimes: '', //体检次数
        maritalStatusId: '', //婚姻
        maritalStatusName: '', //婚姻
        medicalStartDate: '', //体检日期
        customerOrgParentName: '', //单位
        customerOrgName: '', //部门
        medicalTypeId: '', //体检类别
        medicalTypeName: '', //体检类别
        personnelTypeId: '', //人员类别
        personnelTypeName: '', //人员类别
        nationId: '', //民族
        nationName: '', //民族
        mobileTelephone: '', //手机
      },
      prBaseInit: {},
      PatientRegisterList: [], // 参数
      userId: '',
      // 调查问卷参数
      questionParams: {
        idNo: '', // 身份证号
        refresh: 0, // 刷新调查问卷
      }
    };
  },

  created() {
    this.prBaseInit = deepCopy(this.prBase)
  },

  //挂载完成
  mounted() {
    // 监听来自 Electron 的调用 右击事件    
    if (this.$peisAPI) {
      try {
        this.$peisAPI.onContextMenuAction((data) => {
          this.onContextMenuDIY(data)
        });
      } catch (error) {
        console.error(error)
      }
    }

    // 回车替代查询
    this.enterToQuery()

    this.userId = window.sessionStorage.getItem("userId")

    //获取体检登记信息 （检查医生诊台 与 总检医生诊台 切换时用到）
    this.getPatientRegister(this.prBase.patientRegisterNo)

    this.$nextTick(() => {
      this.$refs['tmh'].focus(); //打开光标定位到条码栏里 
    });
  },

  computed: {
    ...mapState(["dict", "dialogWin", "dataTransOpts", "doctorCheck", "sumDoctorCheck"]),
  },
  methods: {
    ...mapMutations(['doctorCheckPrBaseInit', 'sumPREditInit']),
    dddw, moment,

    // 选择人员返回
    chooseBak(chooseData) {
      console.log('chooseBak', chooseData)
      this.prBase.patientRegisterNo = chooseData.patientRegisterNo
      this.onQueryByOnlyNo('patientRegisterNo')
    },

    //查询后触发相关信息处理
    afterFind(rd) {
      this.$emit("triggerQuery", rd)
    },

    btnQuestion() {
      if (!this.prBase.idNo) {
        this.$message.warning({ showClose: true, message: '该人员无身份证号，无调查问卷！' })
        return
      }
      this.dialogWin.question = true
      this.questionParams.idNo = this.prBase.idNo
      this.questionParams.refresh++
    },

    //读身份证
    readIdCard() {
      if (!this.$peisAPI) {
        this.$message.info({ showClose: true, message: "此功能，需要在壳客户端才可运行！" })
        return
      }
      this.$peisAPI.peopleIcCard().then(res => {
        console.log('peopleIcCard', res)
        let lres = JSON.parse(res)
        if (lres.code > -1) {
          let idNos = parsIcCardtoLocal(lres.data, this.dict.sex, this.dict.nation)

          this.prBase.patientName = idNos.Name
          this.prBase.idNo = idNos.IDCode
          this.onQueryByOnlyNo('idNo')
        } else {
          this.$message.error({ showClose: true, message: lres.message })
        }
      })
        .catch(err => {
          this.$message.error({ showClose: true, message: `读取身份证失败，原因：${err}` })
        })
    },



    // 根据pacs条码查询
    onQueryByPacsNo(checkRequestNo) {
      postapi('/api/app/PatientRegister/GetPatientRegisterNoByCheckRequestNo', { checkRequestNo }).then(res => {
        if (res.code > 0) {
          this.prBase.patientRegisterNo = res.data.patientRegisterNo
          this.onQueryByOnlyNo('patientRegisterNo', 'pacsNo')
        }
      })
    },

    // 根据lis条码查询
    onQueryByLisNo(lisRequestNo) {
      postapi('/api/app/PatientRegister/GetPatientRegisterNoByLisRequestNo', { lisRequestNo }).then(res => {
        if (res.code > 0) {
          this.prBase.patientRegisterNo = res.data.patientRegisterNo
          this.onQueryByOnlyNo('patientRegisterNo', 'lisNo')
        }
      })
    },

    //按条码号、档案、身份证  查个人数据
    // noType -- 查询关键值字段名
    // storeCol -- 保留字段值不刷新（用检查条码与检验条码查时）
    onQueryByOnlyNo(noType, storeCol) {
      let noVal = this.prBase[noType]  //唯一号的值
      if (!noVal) return
      let body = {}
      if (noType == 'idNo') noVal = noVal.toUpperCase()
      body[noType] = noVal
      let storeObj = {}
      let patientRegister = { id: '' }
      if (storeCol) storeObj[storeCol] = this.prBase[storeCol]
      patientRegister[noType] = noVal
      this.prBase = deepCopy(patientRegister)

      postapi('/api/app/patientregister/GetAlreadyRegisterPatientRegisterByNo', body)
        .then((res) => {
          if (res.code > -1) {
            this.prBase = Object.assign({},this.prBase, res.data, storeObj)

            // ----------  如果是总检与审核医生不可选时，则总检与审核默认当前用户，此功能放至保存时触发 
            if (this.prBase.completeFlag != '3') this.prBase.summaryDoctorId = this.prBase.summaryDoctorId || this.userId
            if (this.prBase.completeFlag == '3' && this.prBase.isAudit == 'N') {
              this.prBase.auditDoctorId = this.prBase.auditDoctorId || this.userId
            }
            // ----------
            console.log('res.data',res.data)
            console.log('this.prBase',this.prBase)
            console.log('storeObj',storeObj)

          }
          this.afterFind(this.prBase)
        });

    },


    //按手机号或姓名查找客户信息
    onQueryByNotOnlyNo(valType) {
      let noVal = this.prBase[valType]  //唯一号的值
      if (!noVal) return

      let body = {
        isFilterPreRegistration: 'Y' //是否需要过滤预登记数据 Y=过滤预登记数据 N=不过滤 默认为N (备注：只有CompleteFlag参数的值不为0的情况才有效，null值也有效)
      }
      let noType = valType
      if (valType == 'mobileTelephone') noType = 'phone'
      body[noType] = noVal

      let patientRegister = { id: '' }
      patientRegister[valType] = noVal
      this.prBase = deepCopy(patientRegister)

      postapi('/api/app/patientregister/getlistinfilter', body)
        .then(res => {
          if (res.code > -1) {
            if (res.data.items.length == 1) {
              this.prBase = res.data.items[0]
              if (this.prBase.completeFlag != '3') this.prBase.summaryDoctorId = this.userId
              if (this.prBase.completeFlag == '3' && this.prBase.isAudit == 'N') {
                this.prBase.auditDoctorId = this.userId
              }
              this.dataTransOpts.refresh.patient_register.S++
              // this.getPatientRegister(res.data.items[0].id)

            } else if (res.data.items.length > 1) {
              this.PatientRegisterList = res.data.items
              if (Array.isArray(this.PatientRegisterList) && this.PatientRegisterList.length > 0) {
                this.PatientRegisterList.forEach(e => {
                  e.groupPack = e.medicalPackageName || e.customerOrgGroupName
                  e.org = e.customerOrgParentName || e.customerOrgName
                  e.dept = e.customerOrgParentName == e.customerOrgName ? '' : e.customerOrgName
                });
              }
              this.dialogWin.PatientRegisterForChoose = true // 弹窗
              this.dataTransOpts.plus.PatientRegisterForChoose++
            } else {
              this.afterFind(this.prBase)
            }
          }
        })



    },



    //根据patientRegisterNo 获取 人员信息
    getPatientRegister(patientRegisterNo) {
      // this.afterFind({ id: '', patientRegisterNo: '' })
      if (!patientRegisterNo) return
      let body = { patientRegisterNo }
      postapi('/api/app/patientregister/GetAlreadyRegisterPatientRegisterByNo', body)
        .then((res) => {
          if (res.code > -1) {
            this.prBase = res.data
            if (this.prBase.completeFlag != '3') this.prBase.summaryDoctorId = this.userId
            if (this.prBase.completeFlag == '3' && this.prBase.isAudit == 'N') {
              this.prBase.auditDoctorId = this.userId
            }
          }
        })
        .finally(() => {
          this.afterFind(this.prBase)
        });

    },




    lmoment(date, forMat) {
      return moment(new Date(date)).format(forMat);
    },


    //回车替代查询
    enterToQuery() {
      // console.log('enterToTab');
      this.$nextTick(() => {
        let inputs = document.querySelectorAll(["input"]); //用数组可以读取多个标签的元素  //.inline-input

        // 为每个输入框添加键盘事件监听器
        inputs.forEach((input, i) => {
          // console.log('input',input);
          input.addEventListener('keydown', (event) => {
            if (event.keyCode === 13) {
              // 阻止回车键的默认行为（换行）            
              event.preventDefault();
              // 如果按下的是回车查询
              console.log(input.getAttribute('placeholder'), input.value)
              let placeholder = input.getAttribute('placeholder')
              switch (placeholder) {
                case '条码号':
                  if (input.value) this.onQueryByOnlyNo('patientRegisterNo') //this.onQueryByPatientRegisterNo()
                  input.select()
                  break;
                case '档案号':
                  if (input.value) this.onQueryByOnlyNo('patientNo') //this.onQueryByPatientNo()
                  input.select()
                  break;
                case '身份证号':
                  if (input.value) this.onQueryByOnlyNo('idNo') //this.onQueryByPatientNo()
                  input.select()
                  break;
                case '检查条码':
                  if (input.value) this.onQueryByPacsNo(input.value)
                  input.select()
                  break;
                case '检验条码':
                  if (input.value) this.onQueryByLisNo(input.value)
                  input.select()
                  break;
                case '姓名':
                  if (input.value) this.onQueryByNotOnlyNo('patientName') //this.getlistinfilterByName(input.value)
                  input.select()
                  break;
                case '手机号':
                  if (input.value) this.onQueryByNotOnlyNo('mobileTelephone') //this.getlistinfilterByName(input.value)
                  input.select()
                  break;
              }
            }
          });

          input.addEventListener('click', (event) => {
            let placeholder = input.getAttribute('placeholder')
            switch (placeholder) {
              case '条码号':
              case '档案号':
              case '姓名':
              case '检查条码':
              case '检验条码':
                input.select()
                break;
            }
          });

        });
      });
    },

    // 右击菜单
    onContextmenu(event) {
      if (!this.$peisAPI) {
        return
      }


      let menus = [
        // { type: 'separator' },
        // { label: '测试菜单', itemId: '测试菜单', enabled: true },
        // {
        //   label: '更多操作',
        //   submenu: [
        //     { label: '子菜单', itemId: '子菜单', enabled: true }
        //   ]
        // }
      ]

      this.$peisAPI.showContextMenu(menus)
        .then(res => {
          console.log('res', res)
        })
        .catch(err => {
          console.log('err', err)
        })
        .finally(() => {
          console.log('finally')
        })

    },

    // 自定义右击事件
    onContextMenuDIY(data) {
      //this.$message({showClose:true,message:data})
    }

  },

  watch: {
    // "doctorCheck.prBase.id":{
    //   immediate:true,
    //   handler(newVal, oldVal) {
    //     // debugger
    //     // console.log("watch 2doctorCheck.prBase.id newVal：", newVal, " oldVal：", oldVal);
    //     // if (newVal != oldVal) {

    //       objCopy(this.doctorCheck.prBase,this.prBase)
    //       // this.prBase = Object.assign({},this.doctorCheck.prBase)
    //     // }
    //     // console.log(222);
    //   }
    // },

    // 强制刷新人员登记信息
    "refParams.brushQueryDisp": {
      // immediate:true,
      handler(newVal, oldVal) {
        console.log(`watch 组合项目列表 newVal: ${newVal} oldVal: ${oldVal} patientRegisterId: ${this.refParams.id}`);
        if (newVal && newVal != oldVal) {
          // this.getPatientRegister(this.prBase.patientRegisterNo)
          // this.dataTransOpts.refresh.register_check.M++
          this.prBase = Object.assign({}, this.prBase, this.refParams)
        }
      }
    },

    // 重置查询条件
    "refParams.resetTimes": {
      // immediate:true,
      handler(newVal, oldVal) {
        console.log(`watch.refParams.resetTimes newVal: ${newVal} oldVal: ${oldVal}`);
        if (newVal && newVal != oldVal) {
          this.prBase = Object.assign({}, this.prBase, this.prBaseInit)
          this.$nextTick(() => {
            this.$refs['tmh'].focus(); //打开光标定位到条码栏里 
          });
        }
      }
    },
  },
};
</script>
<style scoped>
.query {
  margin-left: 10px;
  margin-right: 2px;
  padding: 1px 1px;
  font-size: 14px;
}


::v-deep .test .el-input__inner {
  background-color: yellow !important;
  color: red !important;
}
</style>
