<template>
  <div>
    <div>
      <div style="display: flex;justify-content:space-between;"> 
        <div class="contenttitle">
          体检登记 /<span class="contenttitleBold">体检人员登记</span>
        </div>  
        <div style="position: absolute;top:50px;right:10px;z-index: 2000;">
          <el-image
            style="margin-right:115px; width: 112px; height: 120px;"
            :src="peoplePhoto"
            >
            <div slot="placeholder" class="image-slot">
              加载中<span class="dot">...</span>
            </div>
          </el-image>
        </div>
      </div>
      <div style="display: flex;">
        <div :style="`width:${window.pageWidth - 120}px;`">
          <div style="display: flex;justify-content:space-between;z-index:-1;" >
            <div>
              <PatientRegisterBase />
            </div>
            <div>
              <el-image
                :style="'margin-top:-80px; width: 120px; height: 130px;z-index:-1;'"
                :src="peoplePhoto"
                >
                <div slot="placeholder" class="image-slot">
                  加载中<span class="dot">...</span>
                </div>
              </el-image>
            </div>
          </div>

          <div style="display: flex;">            
            <el-tabs v-model="activeName" tab-position="bottom" style="width: 200px;">
              <el-tab-pane label="组合项目" name="asbitem">
                <RegisterCheckList />
              </el-tab-pane>
              <el-tab-pane label="叫号" name="call">
                <div :style="`height:${window.pageHeight < 600 ? 400:window.pageHeight-200}px;`">叫号</div>
              </el-tab-pane>
            </el-tabs>

            <div :style="'width:' + (window.pageWidth - 200 - 110 - 15) + 'px;'" >              
              <div :style="'margin-left: 2px;width:' + (window.pageWidth - 200 - 110 - 15 - 2) + 'px;'" >
                <CheckItemList :isCheckPicture="isCheckPicture" :registerCheckId="dataTransOpts.tableS.register_check.id"/>
              </div>
              <div v-if="isCheckPicture" class="demo-image__preview" :style="'margin-top: 2px;margin-left: 2px;height:110px;width:' + (window.pageWidth - 200 - 110 - 45 - 2) + 'px;'">
                <CheckPicture />
              </div>
              <div :style="'margin-top: 2px;margin-left: 2px;width:' + (window.pageWidth - 200 - 110 - 15 - 2) + 'px;'">
                <CheckSumSug :registerCheckId="dataTransOpts.tableS.register_check.id" :isCheckPicture="isCheckPicture" :optGrant="optGrant" :addSummary="addSummary" :btnMakeDiagnosis="btnMakeDiagnosis" :save="save" :audit="audit" :unAudit="unAudit" :btnLineUp="btnLineUp"/>
              </div>
              <div :style="'margin-top: 2px;width:' + (window.pageWidth - 200 - 110 - 15 - 2) + 'px;'">
                <RegisterCheckEdit :registerCheckId="dataTransOpts.tableS.register_check.id"/>
              </div>
            </div>
          </div>
        </div>
        <div style="width:110px;">
          <ButtonList :optGrant="optGrant" :addSummary="addSummary" :btnMakeDiagnosis="btnMakeDiagnosis" :save="save" :audit="audit" :unAudit="unAudit"/>
        </div>
      </div>
    </div>    
  </div>
</template>
<script>
import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { arrayExistObj,tcdate,photoParse } from "../../utlis/proFunc";

import PatientRegisterBase from "../../components/doctorCheck/PatientRegisterBase.vue";
import ButtonList from "../../components/doctorCheck/ButtonList.vue";
import CheckPicture from "../../components/doctorCheck/CheckPicture.vue";
import RegisterCheckList from "../../components/doctorCheck/RegisterCheckList.vue";
import CheckItemList from "../../components/doctorCheck/CheckItemList.vue";
import CheckSumSug from "../../components/doctorCheck/CheckSumSug.vue";
import RegisterCheckEdit from "../../components/doctorCheck/RegisterCheckEdit.vue";
import moment from 'moment';

export default {
  components: {
    RegisterCheckList,
    PatientRegisterBase,
    ButtonList,
    CheckPicture,
    CheckItemList,
    CheckSumSug,
    RegisterCheckEdit
  },
  data() {
    return {
      peoplePhoto:'', //人员照片
      activeName:'asbitem',
      isCheckPicture:true,  //是否显示结果图片
    };
  },

  created() {
    if (this.$peisAPI) {
      // this.$message.info("此功能，需要在壳客户端才可运行！");
      // console.log('this.$peisAPI',this.$peisAPI)
      this.$peisAPI.getIsCheckPicture().then(res =>{
        if(res) this.isCheckPicture = res
      })
    }

  },

  //挂载完成
  mounted() {
    this.dictInit();
  },  

  computed: {
    ...mapState(["window","dataTransOpts","dict", "patientRegister", "customerOrg", "doctorCheck","sumDoctorCheck"]),
  },

  methods: {    
    
    //数据初始化
    dictInit() {
      //性别（仅档案用）
      getapi("/api/app/sex").then((res) => {
        if (res.code == 1) {
          this.dict.sex = res.data;
        }
      });

      //性别（查询）
      getapi("/api/app/for-sex").then((res) => {
        if (res.code == 1) {
          this.dict.forSex = res.data;
        }
      });      

      //体检中心
      getapi("/api/app/organization-units/organization-unit-by-is-peis").then(
        (res) => {
          if (res.code == 1) {
            this.dict.organization = res.data;
          }
        }
      );

      //体检单位
      getapi("/api/app/customer-org/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.customerOrg = res.data.items;
        }
      });

      //体检类别
      getapi("/api/app/medical-type/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.medicalType = res.data.items;
        }
      });

      //人员类别
      getapi("/api/app/personnel-type/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.personnelType = res.data.items;
        }
      });

      //婚姻状况
      getapi("/api/app/marital-statuses").then((res) => {
        if (res.code == 1) {
          this.dict.maritalStatus = res.data.items;
        }
      });

      //性激素期
      getapi("/api/app/sex-hormone-term/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.sexHormoneTerm = res.data.items;
        }
      });

      //民族
      getapi("/api/app/nation/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.nation = res.data.items;
        }
      });

      //籍惯 ，出生地
      getapi("/api/app/birth-place/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.birthPlace = res.data.items;
        }
      });

      //套餐
      postapi("/api/app/medicalpackage/getmedicalpackagelist",{}).then((res) => {
        if (res.code == 1) {
          this.dict.medicalPackage = res.data;
        }
      });

      //分组，所有分组，不限单位，不限次数
      getapi("/api/app/customer-org-group").then((res) => {
        if (res.code == 1) {
          this.dict.customerOrgGroupAll = res.data.items;
        }
      });

      //支付方式
      getapi("/api/app/pay-mode").then((res) => {
        if (res.code == 1) {
          this.dict.payMode = res.data;
        }
      });

      //体检类别 树结构
      getapi("/api/app/item-type/by-code-all").then((res) => {
        if (res.code == 1) {
          this.dict.itemTypeTree = res.data;
          tcdate(this.dict.itemTypeTree);
        }
      });

      //所有组合项目
      postapi("/api/app/asbitem/getasbitemlist",{isFilterActive:'Y'}).then((res) => {
        if (res.code == 1) {
          this.dict.asbItemAll = res.data;
        }
      });

      //获取体检单位列表树信息   
      getapi("/api/app/customerorg/getbycodeall").then((res) => {
        //customerOrgTree = res.data;
        console.log("res.data", res.data);
        this.patientRegister.customerOrgTreeAll = res.data;
        tcdate(this.patientRegister.customerOrgTreeAll)
      });
    

      console.log("dict", this.dict);
    },

    //操作判断
    optGrant(optType) {
      let ret = ''
      if (!this.doctorCheck.RegisterCheckEdit.id) return '请选择组合项目'
      if (this.doctorCheck.RegisterCheckEdit.isLock == 'Y') return '组合项目已锁定，不可执行此操作'
      if (this.doctorCheck.RegisterCheckEdit.completeFlag == '2') return '组合项目已弃检，不可执行此操作'
      if (optType == 'save') {
          // if (!this.doctorCheck.RegisterCheckEdit.checkDoctorId) return "请选择检查医生"
          if (this.doctorCheck.RegisterCheckEdit.completeFlag == '1') return "该项目项目已保存，不可再执行此操作，如需操作请点【修改结果】"
          if (this.doctorCheck.RegisterCheckEdit.isAudit == 'Y') return '组合项目已审核，请先取消审核，方可执行此操作！'
      }
      if (optType == 'edit') {
          if (this.doctorCheck.RegisterCheckEdit.completeFlag == '0') return "该检查项目尚未保存，无需执行此操作"
          if (this.doctorCheck.RegisterCheckEdit.isAudit == 'Y') return '组合项目已审核，请先取消审核，方可执行此操作！'
      }
      if (optType == 'del') {
          if (this.doctorCheck.RegisterCheckEdit.completeFlag == '0') return "该检查项目尚未保存，无需执行此操作"
          if (this.doctorCheck.RegisterCheckEdit.isAudit == 'Y') return '组合项目已审核，请先取消审核，方可执行此操作！'
      }
      if (optType == 'audit') {
          if (this.doctorCheck.RegisterCheckEdit.completeFlag == '0') return "该检查项目尚未保存，无需执行此操作"
          if (this.doctorCheck.RegisterCheckEdit.isAudit == 'Y') return "该检查项目已审核，无需再执行此操作"
      }
      if (optType == 'unAudit') {
          if (this.doctorCheck.RegisterCheckEdit.completeFlag == '0') return "该检查项目尚未保存，无需执行此操作"
          if (this.doctorCheck.RegisterCheckEdit.isAudit == 'N') return "该检查项目尚未审核，无需执行此操作"
      }
      if (optType == 'delItem' || optType == 'refuseItem' || optType == 'makeDiagnosis' ) {
          if (this.doctorCheck.RegisterCheckEdit.completeFlag == '1') return "该项目项目已保存，不可再执行此操作，如需操作请点【修改结果】"
          if (this.doctorCheck.RegisterCheckEdit.isAudit == 'Y') return "该检查项目已审核，请先取消审核"
      }
      return ret
    },

    // 生成小结
    btnMakeDiagnosis(){
      let ret = this.optGrant('makeDiagnosis')
      if (ret) {
          this.$message.warning(ret)
          return
      }

      if(this.doctorCheck.checkItemList.length == 0){
        this.$message.warning("系统错误，组合项目没有明细")
        return
      }
      
      console.log('生成小结');

      if(this.doctorCheck.checkSummaryList.length > 0){            
        this.$confirm("已经有小结，是否重新生成小结?", "提示", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning",
        }).then(() => {
          this.makeDiagnosisFun();
        }).catch((err) => {
          if (err == "cancel") {
            this.$message.info("已取消");
          }
        });
      }else{
        this.makeDiagnosisFun();
      }

    },

    // 生成小结的函数
    makeDiagnosisFun(){
      
      // /api/app/diagnosisfunction/getdiagnosisresult
      // {
      //     "registerCheckId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //     "items": [
      //         {
      //         "itemId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //         "result": "string"
      //         }
      //     ]
      // }
      
    
      let body = {
          registerCheckId:'',
          items:[]
      }

      this.doctorCheck.checkItemList.forEach((e,index) =>{
          if(index == 0) body.registerCheckId = e.registerCheckId
          body.items.push({
              itemId:e.itemId,
              result:e.result
          })
      })
      
      console.log(`/api/app/diagnosisfunction/getdiagnosisresult`, body)
      this.doctorCheck.checkSummaryList = []
      this.doctorCheck.checkSuggestionList = []
      postapi(`/api/app/diagnosisfunction/getdiagnosisresult`, body)
      .then((res) => {                
          if (res.code != -1) {
              // console.log(res.data)
              // {
              //     "diagnosisResultDetails": [
              //     {
              //         "diagnosisResult": "超重"
              //     }
              //     ],
              //     "diagnosisSuggestionDetails": [
              //     {
              //         "diagnosisSuggestion": "定期复查"
              //     },
              //     {
              //         "diagnosisSuggestion": "控制热量摄入，适当运动"
              //     }
              //     ]
              // }
              
              // 小结
              res.data.diagnosisResultDetails.forEach(e =>{
                  this.doctorCheck.checkSummaryList.push({
                      id:Math.random(),
                      registerCheckId:body.registerCheckId,
                      summary:e.diagnosisResult,
                      summaryFlag:'Y'
                  })
              })

              // 建议
              res.data.diagnosisSuggestionDetails.forEach(e =>{
                  this.doctorCheck.checkSuggestionList.push({
                      id:Math.random(),
                      registerCheckId:body.registerCheckId,
                      suggestion:e.diagnosisSuggestion
                  })
              })
              console.log("操作成功！")
          }
      })
      .catch((err) => {
        this.$message({ type: "error", message: `生成小结失败，原因：${err}` });
      });
    },

    // 手动新增小结与建议
    addSummary() {
      let ret = this.optGrant('makeDiagnosis')
      if (ret) {
          this.$message.warning(ret)
          return
      }

      this.doctorCheck.checkSummaryList.push({
          id:Math.random(),
          registerCheckId: this.doctorCheck.RegisterCheckEdit.id,
          summary: '',
          summaryFlag: 'N',
      })
      this.doctorCheck.checkSuggestionList.push({
          id:Math.random(),
          registerCheckId: this.doctorCheck.RegisterCheckEdit.id,
          suggestion: '',
      })
    },

    //保存数据
    save() {
      let ret = this.optGrant('save')
      if (ret) {
        this.$message.warning(ret)
        return
      }

      //更新明细
      this.updateCheckItemList();

      //更新检查项目与医生
      this.updateDoctorCheck();

      //更新小结        
      this.saveCheckSummary();

      //更新建议      
      this.saveCheckSuggestion(true);
    },

    //更新检查医生
    updateDoctorCheck(successTip) {
      let checkDate = this.doctorCheck.RegisterCheckEdit.checkDate||new Date(); 
      checkDate = moment(new Date(checkDate)).format('yyyy-MM-DD'); //yyyy-MM-DD HH:mm:ss
      let checkDoctorId = this.doctorCheck.RegisterCheckEdit.checkDoctorId||window.sessionStorage.getItem("user");

      let body = {
        registerCheckId: this.doctorCheck.RegisterCheckEdit.id,
        checkDoctorId,
        checkDate
      }
      console.log(`/api/app/registercheck/updatecheckdoctor`, body)
      postapi(`/api/app/registercheck/updatecheckdoctor`, body)
        .then((res) => {
            console.log("updateDoctorCheck", res.data);
            if (res.code != -1) {
              console.log("更新检查医生 成功", res.data);
              this.doctorCheck.RegisterCheckEdit.completeFlag = '1';
              //更新组合项目列表记录状态
              let lfind = arrayExistObj(this.doctorCheck.RegisterCheckList,'id',body.registerCheckId)
              if(lfind > -1) this.doctorCheck.RegisterCheckList[lfind].completeFlag = '1'
              if(successTip) console.log("操作成功！")
            }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `更新检查医生失败，原因：${err}` });
        });
    },

    //更新检查项目明细
    updateCheckItemList(successTip) {            
      let checkDate = this.doctorCheck.RegisterCheckEdit.checkDate||new Date();            
      checkDate = moment(new Date(checkDate)).format('yyyy-MM-DD'); //yyyy-MM-DD HH:mm:ss
      let checkDoctorId = this.doctorCheck.RegisterCheckEdit.checkDoctorId||window.sessionStorage.getItem("user");
      let body = []
      for (let i = 0; i < this.doctorCheck.checkItemList.length; i++) {
        body.push({
          registerCheckId: this.doctorCheck.checkItemList[i].registerCheckId,
          itemId: this.doctorCheck.checkItemList[i].itemId,
          result: this.doctorCheck.checkItemList[i].result,
          checkDoctorName: checkDoctorId,
          checkDate,
        })
      }
      console.log(`/api/app/registercheckitem/updateregistercheckitemmany`, body)
      postapi(`/api/app/registercheckitem/updateregistercheckitemmany`, body)
        .then((res) => {
          console.log("updateCheckItemList", res.data);
          if (res.code != -1) {
            console.log("更新检查项目明细成功", res.data);
            if(successTip) console.log("操作成功！")
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `更新检查项目明细失败，原因：${err}` });
        });
    },

    //更新小结        
    saveCheckSummary(successTip) {
      let details = []
      this.doctorCheck.checkSummaryList.forEach(item => {
        details.push({
          registerCheckId: item.registerCheckId,
          summary: item.summary,
          summaryFlag: item.summaryFlag,
        })
      });
      let body = {
        registerCheckId:this.doctorCheck.RegisterCheckEdit.id,
        details
      }           
      
      console.log(`/api/app/registerchecksummary/createregisterchecksummarymany`, body)
      postapi(`/api/app/registerchecksummary/createregisterchecksummarymany`, body)
        .then((res) => {
          console.log("saveCheckSummary", res.data);
          if (res.code != -1) {
            console.log("更新小结 成功", res.data);
            if(successTip) console.log("操作成功！")
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `更新小结失败，原因：${err}` });
        });

    },

    //更新建议      
    saveCheckSuggestion(successTip) {
      let details = []
      this.doctorCheck.checkSuggestionList.forEach(item => {
        details.push({
          registerCheckId: item.registerCheckId,
          suggestion: item.suggestion
        })
      });

      let body = {
        registerCheckId:this.doctorCheck.RegisterCheckEdit.id,
        details
      }     

      console.log(`/api/app/registerchecksuggestion/createregisterchecksuggestionmany`, body)
      postapi(`/api/app/registerchecksuggestion/createregisterchecksuggestionmany`, body)
        .then((res) => {
          console.log("saveCheckSuggestion", res.data);
          if (res.code != -1) {
            //this.doctorCheck.RegisterCheckEdit.completeFlag = '1';
            if(successTip) console.log("操作成功！")
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `更新建议失败，原因：${err}` });
        });

    },

    //审核
    audit() {
      let ret = this.optGrant('audit')
      if (ret) {
        this.$message.warning(ret)
        return
      }
      let body = {
        registerCheckId: this.doctorCheck.RegisterCheckEdit.id,
        //auditorUserId: "3fa85f64-5717-4562-b3fc-2c963f66afa6", 
        //auditTime: "string" 不传时，取当前时间
      }

      console.log(`/api/app/registercheck/updateauditordoctor`, body)
      postapi(`/api/app/registercheck/updateauditordoctor`, body)
        .then((res) => {
            console.log("audit", res.data);
            if (res.code != -1) {
                this.doctorCheck.RegisterCheckEdit.isAudit = 'Y';
                this.$message({ type: "success", message: `组合项目审核成功` });
            }
        })
        .catch((err) => {
            this.$message({ type: "error", message: `组合项目审核失败，原因：${err}` });
        });
    },

    //取消审核
    unAudit() {
      let ret = this.optGrant('unAudit')
      if (ret) {
        this.$message.warning(ret)
        return
      }

      console.log(`/api/app/registercheck/updateisaudit?RegisterCheckId=${this.doctorCheck.RegisterCheckEdit.id}&IsAudit=N`)
      postapi(`/api/app/registercheck/updateisaudit?RegisterCheckId=${this.doctorCheck.RegisterCheckEdit.id}&IsAudit=N`)
        .then((res) => {
          console.log("unAudit", res.data);
          if (res.code != -1) {
              this.doctorCheck.RegisterCheckEdit.isAudit = 'N';
              this.$message({ type: "success", message: `组合项目取消审核成功` });
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `组合项目取消审核失败，原因：${err}` });
        });
    },

    // 排队
    btnLineUp(){
      console.log('排队')
    },



  },

  //监听事件()
  watch: {
    // //1级单位值改变，分组改变
    // "patientRegister.query.CustomerOrgParentId"(newVal, oldVal) {
    //   console.log(
    //     "watch patientRegister.query.CustomerOrgParentId newVal：",
    //     newVal,
    //     " oldVal：",
    //     oldVal
    //   );
    //   if (newVal != oldVal && newVal !== this.dict.personOrgId) {
    //     this.getCustomerOrgGroup(newVal);
    //   }
    // },
    "patientRegister.photo":{
      immediate:true,
      // deep:true,
      handler(newVal, oldVal) {
        //console.log('patientRegister.patientRegisterRd.id newVal：',newVal,' oldVal：',oldVal)
        if (newVal != oldVal) {
          this.peoplePhoto = photoParse(newVal)
        }
      }
    },

  },
};
</script>
<style scoped>
@import '../../assets/css/global_card.css';
@import '../../assets/css/global_input.css';
@import '../../assets/css/global_table.css';
@import '../../assets/css/global.css';
</style>
  