<template>
  <div>
    <div>
      <el-table :data="patientRegister.prList" border ref="info" id="info"
        :height="(window.pageHeight < 600) ? 230 : (window.pageHeight - 370)" highlight-current-row @row-click="rowClick"
        size="small" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column prop="completeFlag" label="体检进度">
          <template slot-scope="scope">
            <div :style="`color: ${setPrStatusColor(scope.row.isAudit, scope.row.completeFlag)}`">{{
              dddw(dict.completeFlag, "id", scope.row.completeFlag, "displayName") }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="isReportPrint" label="打印" width="50" align="center">
          <template slot-scope="scope">
            <i class="el-icon-printer" v-if="scope.row.isReportPrint == 'Y'" style="font-size: 24px;color: green;"></i>
          </template>
        </el-table-column>
        <el-table-column prop="isUploadAppoint" label="预约备单" align="center">
          <template slot-scope="scope">
            <div style="font-family: 'Microsoft YaHei';">{{ scope.row.isUploadAppoint == "Y" ? "√" : "" }}</div>
          </template>
        </el-table-column> 
        <el-table-column prop="isUpload" label="报告上传" align="center">
          <template slot-scope="scope">
            <div style="font-family: 'Microsoft YaHei';">{{ scope.row.isUpload == "Y" ? "√" : "" }}</div>
          </template>
        </el-table-column> 
        <el-table-column prop="customerOrgName" label="单位" width="180" />
        <el-table-column prop="departmentName" label="部门" width="180" />
        <el-table-column prop="patientName" label="姓名" align="center" />
        <el-table-column prop="mobileTelephone" label="手机" width="130" />
        <el-table-column prop="sexName" label="性别" align="center" />
        <el-table-column prop="age" label="年龄" align="center" />
        <el-table-column prop="patientRegisterNo" label="条码号" width="150" align="center" />
        <el-table-column prop="patientNo" label="档案号" align="center" />
        <el-table-column prop="medicalTimes" label="体检次数" align="center" />
        <el-table-column label="分组/套餐" width="150">
          <template slot-scope="scope">
            <div v-if="scope.row.medicalPackageName">
              {{ scope.row.medicalPackageName }}
            </div>
            <div v-if="scope.row.customerOrgGroupName">
              {{ scope.row.customerOrgGroupName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="nationId" label="民族" align="center">
          <template slot-scope="scope">
            <div>
              {{ dddw(dict.nation, "nationId", scope.row.nationId, "displayName") }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="idNo" label="身份证" width="150" align="center" />
        <el-table-column prop="birthDate" label="出生日期" width="100" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.birthDate">
              {{ lmoment(scope.row.birthDate, "yyyy-MM-DD") }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="telephone" label="电话" width="130" />
        <el-table-column prop="address" label="地址" width="400" />
        <el-table-column prop="medicalCardNo" label="体检卡号" />
        <el-table-column prop="jobCardNo" label="工卡号" />
        <el-table-column prop="maritalStatusName" label="婚姻状况" align="center" />
        <el-table-column prop="medicalTypeName" label="体检类别" align="center"/>
        <el-table-column prop="personnelTypeName" label="人员类别" align="center"/>
        <el-table-column prop="jobPost" label="职务" />
        <el-table-column prop="jobTitle" label="职称" />
        <el-table-column prop="salesman" label="介绍人" />
        <el-table-column prop="isVip" label="VIP" width="50" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.isVip == "Y" ? "是" : "否" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="registerName" label="登记人" align="center"/>
        <el-table-column prop="registerDate" label="登记日期" width="150" align="center"/>
        <el-table-column prop="isLock" label="锁住" align="center" width="50">
          <template slot-scope="scope">
            <div>{{ scope.row.isLock == "Y" ? "是" : "否" }}</div>
          </template>
        </el-table-column>
        
        <!--
        "sexHormoneTermId": "00000000-0000-0000-0000-000000000000",
        "interposeMeasure": null,
        "medicalConclusionId": "00000000-0000-0000-0000-000000000000",
        "reportPrintTimes": 0,        
        "isMedicalStart": "N",
        "medicalStartDate": "6/28/2023",
        "isRecoverGuide": "N",
        "summaryDate": "",
        "summaryDoctor": null,
        "isAudit": "N",
        "auditDoctor": null,
        "auditDate": "",        
        "isNameHide": "N",
        "isPhoneFollow": "N",
        "thirdInfo": null,
        "guidePrintTimes": null,
        "remark": null,
        "medicalCenterId": "00000000-0000-0000-0000-000000000000",
        "customerOrgRegisterId": "00000000-0000-0000-0000-000000000000",
        "lastModifierName": "",
        "lastModificationTime": null,
        "lastModifierId": null,
        "creatorId": null,
        "id": "3a0c196d-a6d0-37fe-5c32-4806bdc4530f"
        -->
      </el-table>
      <div style="display: flex;justify-content:space-between;">
        <div></div>
        <div>
          <span style="font-size:12px;">共：{{ loadOpts.totalCount }} 条记录，当前显示：{{ patientRegister.prList.length }}
            条。</span>
        </div>
      </div>
    </div>    
  </div>
</template>
<script>

import moment from "moment";
import { mapState, mapActions } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { dddw, deepCopy, objCopy, arrayReduce, arrayExistObj, setPrStatusColor } from "@/utlis/proFunc";

import PatientRegisterEdit from "../../components/patientRegister/PatientRegisterEdit.vue";
import Camera from "../../components/patientRegister/Camera.vue";
import PatientRegisterAsbItem from "../../components/patientRegister/patientRegisterAsbItem.vue";

export default {
  components: {
    PatientRegisterEdit,
    Camera,
    PatientRegisterAsbItem,
  },
  props: ['fromType'],
  data() {
    return {
      
      dialogVisible: false,
      dialogCamera: false,
      dialogGuide: false,
      guideMsg: 'guideMsg',
      tabChoosed: "1",
      formInitData: {},      //体检登记初始表单数据
      editTimes: 0,

      rClickRow: null,       //右击的行
      rClickColumn: null,    //右击的列（预留）

      dom: null,   //用于滚动加载数据
      lazyLoading: false,  //是否懒加载中
      loadOpts: {
        totalCount: 0,
        skipCount: 0,
        maxResultCount: 100,
      },
      loadOptsInit: {},
    };
  },


  created() {
    this.loadOptsInit = Object.assign({}, this.loadOpts)
    this.patientRegister.prList = []
  },

  //挂载完成
  mounted() {
    this.$nextTick(() => {
      this.scrollFull()
    })
  },
  computed: {
    ...mapState(["window", "dict", 'dataTransOpts', "patientRegister", "customerOrg", "report"]),
  },
  methods: {
    dddw, setPrStatusColor,

    handleSelectionChange(val) {
      this.dataTransOpts.tableM.patient_register = val
    },

    //获取单位分组 /api/app/customer-org-group/in-customer-org-id/3a0c0444-d7a0-871f-4074-19faf1655caf
    // getCustomerOrgGroup(customerOrgld) {
    //   getapi(`/api/app/customer-org-group/in-customer-org-id/${customerOrgld}`)
    //     .then((res) => {
    //       console.log("getCustomerOrgGroup", res.data);
    //       if (res.code == 1) {
    //         this.patientRegister.customerOrgGroup = res.data;
    //       }
    //     });
    // },

    //点击体检次数行
    rowClick(row) {
      this.dataTransOpts.tableS.patient_register = deepCopy(row)
      this.dataTransOpts.tableS.patient_register.id = row.patientRegisterId
      // 刷新个人资料
      this.dataTransOpts.refresh.patient_register.S++
      // 刷新总检状态
      this.dataTransOpts.refresh.sumDoctor.M++
      // 刷新检查项目
      this.dataTransOpts.refresh.register_check.M++

    },

    async load() {
      this.loadOpts.skipCount++
      await this.queryEvent()
    },

    //滚动加载数据 
    scrollFull() {
      this.dom = this.$refs['info'].bodyWrapper
      console.log('this.dom', this.dom)

      this.dom.addEventListener('scroll', async () => {
        // console.log('scrollTop',this.dom.scrollTop,'clientHeight',this.dom.clientHeight,'scrollHeight',this.dom.scrollHeight);
        if (this.dom.scrollTop + this.dom.clientHeight + 20 > this.dom.scrollHeight && !this.lazyLoading) {
          // 获取到的不是全部数据 当滚动到底部 
          console.log('scrollTop', this.dom.scrollTop, 'clientHeight', this.dom.clientHeight, 'scrollHeight', this.dom.scrollHeight);
          if (Number(this.loadOpts.skipCount) * Number(this.loadOpts.maxResultCount) >= Number(this.loadOpts.totalCount)) {
            this.lazyLoading = false
          } else {
            this.lazyLoading = true
            await this.load()
            this.lazyLoading = false
            // this.dom.scrollTop = this.dom.scrollTop - 100
          }
        }
      })
    },

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

    //查询
    async btnQuery() {
      this.loadOpts.skipCount = 0
      this.queryEvent()
    },

    async queryEvent() {
      if (this.fromType == 'report') {
        this.reportQuery()
        return
      }

      this.patientRegister.prList = [];
      let body = {}

      console.log(`this.patientRegister.query`, this.patientRegister.query)

      body = deepCopy(this.patientRegister.query)
      if (this.patientRegister.query.customerOrgFlag) {
        if (this.patientRegister.query.CustomerOrgParentId) {
          body.customerOrgId = this.patientRegister.query.CustomerOrgParentId
        } else {
          if (this.patientRegister.query.customerOrgId) body.customerOrgId = this.patientRegister.query.customerOrgId
        }
      }

      if (this.patientRegister.query.sex) body.sexId = this.patientRegister.query.sex      

      //StartDate EndDate
      if (this.patientRegister.query.dateRange) {
        body.startDate = moment(new Date(this.patientRegister.query.dateRange[0])).format("yyyy-MM-DD")
        body.endDate = moment(new Date(this.patientRegister.query.dateRange[1])).format("yyyy-MM-DD")
      }

      console.log('body',body)

      if (this.patientRegister.query.idCardNo) body = { idNo: this.patientRegister.query.idCardNo }

      if (this.patientRegister.query.patientNo) body = { patientNo: this.patientRegister.query.patientNo }

      if (this.patientRegister.query.patientRegisterNo) body = { patientRegisterNo: this.patientRegister.query.patientRegisterNo }


      console.log('/api/app/patientregister/getlistinfilter', body)
      postapi('/api/app/patientregister/getlistinfilter', body)
        .then((res) => {
          if (res.code != -1) {
            this.patientRegister.prList = res.data.items;
          }
        })
      // try {
      //   let res =await postapi('/api/app/patientregister/getlistinfilter', body);
      //   this.patientRegister.prList = res.data;
      // } catch (error) {
      //   console.log("query error",error);
      // }  
    },

    // 报告查询
    reportQuery() {
      console.log('reportQuery this.loadOpts', this.loadOpts)
      if (this.loadOpts.skipCount != 0 && this.loadOpts.skipCount * this.loadOpts.maxResultCount >= this.loadOpts.totalCount) return

      let body = {
        skipCount: this.loadOpts.skipCount,
        maxResultCount: this.loadOpts.maxResultCount
      };

      let customerOrgs = [];

      if (this.report.dataCusOrgOCX.length > 0) {
        this.report.dataCusOrgOCX.forEach(e => {
          let rd = {
            startDate: moment(e.startDate).format('yyyy-MM-DD'),
            endDate: moment(e.endDate).format('yyyy-MM-DD'),
            dateType: e.dateType == 'summaryDate' ? '3' : (e.dateType == 'medicalStartDate' ? '2' : '1')
          }

          if (e.customerOrgId) {
            rd.customerOrgId = e.customerOrgId
            if (e.customerOrgId == this.dict.personOrgId) {
              rd.customerOrgRegisterId = null
              rd.customerOrgGroupId = []
            } else {
              rd.customerOrgRegisterId = e.customerOrgRegister.id
              rd.customerOrgGroupId = e.customerOrgGroupIds
            }
          }
          customerOrgs.push(rd)
        })
      }

      body.customerOrgs = customerOrgs
      if (this.patientRegister.query.patientRegisterNo) body.patientRegisterNo = this.patientRegister.query.patientRegisterNo
      if (this.patientRegister.query.patientNo) body.patientNo = this.patientRegister.query.patientNo
      if (this.patientRegister.query.patientName) body.patientName = this.patientRegister.query.patientName
      if (this.patientRegister.query.idCardNo) body.idCardNo = this.patientRegister.query.idCardNo
      if (this.patientRegister.query.phone) body.phone = this.patientRegister.query.phone
      if (this.patientRegister.query.completeFlag) body.completeFlag = this.patientRegister.query.completeFlag
      if (this.patientRegister.query.isAudit) body.isAudit = this.patientRegister.query.isAudit
      if (this.patientRegister.query.reportPrintTimes >= 0) body.isReportPrint = this.patientRegister.query.reportPrintTimes
      if (this.patientRegister.query.isUpload) body.isUpload = this.patientRegister.query.isUpload
      if (this.patientRegister.query.medicalTypeIds) body.medicalTypeIds = this.patientRegister.query.medicalTypeIds
      if (this.patientRegister.query.personnelTypeId) body.personnelTypeId = this.patientRegister.query.personnelTypeId

      //console.log('/api/app/peisreport/getpatientregisterreport',body)

      postapi('/api/app/peisreport/getpatientregisterreport', body).then(res => {
        if (res.code > -1) {
          // 刷新最大记录数
          this.loadOpts.totalCount = res.data.totalCount

          if (body.skipCount == 0) {  //查询
            this.patientRegister.prList = [];
          }
          this.patientRegister.prList = this.patientRegister.prList.concat(res.data.items)
          if (body.skipCount == 0 && this.patientRegister.prList.length == 1) {
            this.rowClick(this.patientRegister.prList[0])
            this.$refs['info'].setCurrentRow(this.patientRegister.prList[0]);
          } else {
            this.$refs['info'].setCurrentRow();
            this.dataTransOpts.tableS.patient_register = { id: '' }
            // 刷新个人资料
            this.dataTransOpts.refresh.patient_register.S++
            // 刷新总检状态
            this.dataTransOpts.refresh.sumDoctor.M++
            // 刷新检查项目
            this.dataTransOpts.refresh.register_check.M++
          }
        }
      })
    },


  },

  //监听事件
  watch: {
    //触发查询事件
    "patientRegister.query.times": {
      // immediate:true,
      handler(newVal, oldVal) {
        console.log('查询触发', newVal, oldVal)
        if (newVal != oldVal) {
          this.btnQuery();
        }
      }
    },

    //新增后，触发赋值
    "patientRegister.patientRegisterRd.id"(newVal, oldVal) {
      if (newVal != oldVal) {
        //console.log('patientRegister.patientRegisterRd.customerOrgId',this.patientRegister.patientRegisterRd.customerOrgId)
        objCopy(this.patientRegister.patientRegisterRd, this.form);
      }
    },
  },
};
</script>
<style scoped>
.box {
  display: flex;
}

.listBtn {
  margin-top: 5px;
  text-align: center;
}

.btnClass {
  width: 110px;
}

::v-deep .el-input__inner {
  text-align: center;
  padding-left: 1px;
  padding-right: 1px;
}

::v-deep .el-table th.el-table__cell {
  text-align: center;
  padding-left: 1px;
  padding-right: 1px;
}

::v-deep .el-table td.el-table__cell {
  padding-left: 1px;
  padding-right: 1px;
}

::v-deep .el-table .cell {
  padding-left: 1px;
  padding-right: 1px;
}

::v-deep input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none !important;
  margin: 0 !important;
}
</style>
