<template>
  <div style="margin-top: -15px;">
    <div style="display: flex;justify-content: space-between;">
      <div
        style="display: flex;flex-wrap: wrap;background-color: #fff;border-radius: 8px;align-items: center;padding: 2px;width:700px;">
        <div class="query">
          <!--
          <el-select v-model="query.thirdInterfaceId" placeholder="请选择" style="width: 100px" size="small">
            <el-option v-for="item in thirdInterfaces" :key="item.id" :label="item.displayName" :value="item.id" />
          </el-select>
          -->
          <el-date-picker v-model="query.startDate" type="date" placeholder="起始日期" size="small"
            style="width:90px;" value-format="yyyy-MM-dd" :picker-options="pickerOptions" />
          <span class="spanClass">至</span>
          <el-date-picker v-model="query.endDate" type="date" placeholder="截止日期" size="small"
            style="width:90px;" value-format="yyyy-MM-dd" :picker-options="pickerOptions" />
        </div>        
        <div class="query">
          <span class="spanClass">检索关键字</span>
          <el-input placeholder="姓名、电话、身份证号" v-model="query.keyWord" size="small" clearable style="width: 240px" />
        </div>
        <div class="query">
          <span class="spanClass">状态</span>
          <el-select v-model="query.medicalStatus" placeholder="请选择" clearable style="width: 80px" size="small">
            <el-option v-for="item in localDict.medicalStatus" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
      <div style="margin-top: -38px;width: 80px;">
        <div>
          <el-button @click="peopleIcCard" class="commonbutton" style="width:80px;font-size: 14px;">读身份证</el-button>
        </div>
        <div>
          <el-button class="commonbutton" @click="btnQuery" style="margin-top: 6px; width:80px;">查询</el-button>
        </div>
      </div>
    </div>
    <div>
      <el-table :data="tableData" border style="width: 100%" row-key="id" height="430" highlight-current-row
        size="small" @row-click="rowClick" ref="webBooking">        
        <el-table-column label="姓名" width="80" prop="patientName" align="center" />
        <el-table-column label="身份证号" width="150" prop="idNo" align="center" />
        <el-table-column label="预约时间" width="150" prop="bookingDate" align="center" />
        <el-table-column label="手机号" width="130" prop="phone" align="center" />
        <el-table-column label="性别" width="40" prop="sexId" align="center" />
        <el-table-column label="年龄" width="40" prop="age" align="center" />
        <el-table-column label="单位" width="150" prop="customerOrgId" align="center" />
        <el-table-column label="单位体检次数" width="150" prop="customerOrgRegisterId" align="center" />
        <el-table-column label="分组/套餐" width="120" prop="customerOrgGroupId" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.customerOrgGroupId ? scope.row.customerOrgGroupId : scope.row.medicalPackageName }}
            </div>
          </template>
        </el-table-column>        
        <el-table-column label="预约编号" width="120" prop="thirdBookingId" align="center" />
        <el-table-column label="状态" width="50" prop="medicalStatus" align="center" >
          <template slot-scope="scope">
            {{ dddw(localDict.medicalStatus,'value',scope.row.medicalStatus,'label') }}
          </template>
        </el-table-column>
      </el-table>
     
    </div>
    <div style="margin-top: 10px; display: flex;justify-content: space-between;">
      <div style="margin: -8px 0 0 0; font-size: 12px;">
        {{ asbDesc }}
      </div>
      <div>        
        <el-button v-if="false" @click="btnTest">测试</el-button>
      </div>
      <div>
        <el-button class="commonbutton" @click="btnOk">确定</el-button>
        <el-button class="commonbutton" @click="btnClose">关闭</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { dddw, deepCopy } from "../../utlis/proFunc";
import moment from "moment";


export default {
  components: {

  },
  data() {
    return {
      thirdInterfaces: [],
      tableData: [],
      currRowData: {},
      tableDataDetails: [],
      query: {
        thirdInterfaceId: "",
        idNo: "",
        mobilePhone: "",
        appointStartDate: "",
        appointStopDate: "",
        completeFlag: "0",
        keyWord:'',
        startDate:'',
        endDate:'',
        medicalStatus:'0'
      },
      asbDesc: '', //所选套餐描述
      localDict:{
        medicalStatus:[
          {label:'未开始',value:'0'}, // 0未开始 1已登记 2已完成
          {label:'已登记',value:'1'},
          {label:'已完成',value:'2'},
        ]
      }
    };
  },

  created() {
    let today = moment(new Date()).format("yyyy-MM-DD")
    this.query.endDate = today
    this.query.startDate = today
  },

  updated() {
    // this.$nextTick(() => {
    //   this.$refs['webBookingDetaills'].doLayout()
    // })
  },
  //挂载完成
  mounted() {
    //回车替代查询
    this.enterToQuery()

    this.funMounted()
  },

  computed: {
    ...mapState([
      "pickerOptions",
      "window",
      "dict",
      "dataTransOpts",
      "dialogWin"
    ]),
  },

  methods: {
    dddw,
    funMounted() {
      this.dictInit()
        // .then(res => {
        //   //this.btnQuery()
        // })
    },

    //数据初始化
    dictInit() {   

      // return new Promise((resolve, reject) => {
      //   let curDate = moment(new Date()).format('YYYY-MM-DD')
      //   this.query.appointStartDate = curDate
      //   this.query.appointStopDate = moment(Date.now() + 3600 * 1000 * 24 * 7).format('YYYY-MM-DD')
      //   this.query.idNo = ''
      //   this.query.mobilePhone = ''
      //   this.tableData = []
      //   this.tableDataDetails = []

      //   // 获取接口列表，传07
      //   postapi("/api/app/ThirdInterface/GetListByThirdInterfaceTypeAsync", { thirdInterfaceType: "07" })
      //     .then(res => {
      //       if (res.code > -1) {
      //         this.thirdInterfaces = res.data
      //         if (res.data && Array.isArray(res.data) && res.data.length > 0) this.query.thirdInterfaceId = res.data[0].id
      //         resolve(res)
      //       } else {
      //         reject(res.message)
      //       }
      //     })
      //     .catch(err => {
      //       reject(err)
      //     })
      // })
    },

    //读取身份证信息
    peopleIcCard() {
      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.query.idNo = idNos.IDCode
          this.query.keyWord = idNos.IDCode
          // this.form.patientName = idNos.Name
          // this.form.birthDate = idNos.birthDate
          // this.form.sexId = idNos.sexId
          // this.form.age = idNos.age
          // this.form.nationId = idNos.nationId
          // this.form.idNo = idNos.IDCode
          // this.form.address = idNos.Address
          // this.peoplePhoto = 'data:image/bmp;base64,' + idNos.Photo
          // this.patientRegister.photo = 'data:image/bmp;base64,' + idNos.Photo
          this.btnQuery()

        } else {
          this.$message.error({ showClose: true, message: `${lres.message}` })
        }
      })
    },

    // 查询
    btnQuery() {
      // if (!(this.query.appointStartDate && this.query.appointStopDate)) {
      //   this.$message.error({ showClose: true, message: "必须选择日期段！" })
      //   return
      // }
      // if (!(this.query.idNo || this.query.mobilePhone)) {
      //   this.$message.error({ showClose: true, message: "手机号或身份证号必须填写一项！" })
      //   return
      // }
      if (!(this.query.startDate && this.query.endDate)) {
        this.$message.error({ showClose: true, message: "必须选择日期段！" })
        return
      }

      this.currRowData = {}
      this.tableData = []
      this.tableDataDetails = []

      let body = deepCopy(this.query)

      // body.appointStartDate = this.query.appointStartDate + " 00:00:00"
      // body.appointStopDate = this.query.appointStopDate + " 23:59:59"
      body.startDate = this.query.startDate + " 00:00:00"
      body.endDate = this.query.endDate + " 23:59:59"

      postapi('/api/app/ThirdBooking/GetThirdBookingList', body)
        .then(res => {
          if (res.code > -1) {
            this.tableData = res.data
            if (res.data && Array.isArray(res.data) && res.data.length == 1) {
              this.rowClick(res.data[0])
              this.$refs['webBooking'].setCurrentRow(res.data[0]);
            }
          }
        })
    },

    btnTest() {
      console.log('this.thirdInterfaces', this.thirdInterfaces)
      console.log('this.tableData', this.tableData)
      console.log('this.currRowData', this.currRowData)
      console.log('this.tableDataDetails', this.tableDataDetails)
      console.log('this.query', this.query)
    },

    rowClick(row) {
      this.currRowData = row
      // this.tableDataDetails = []
      // postapi('/api/app/AppointPatientRegister/GetAppointRegisterAsbitemListById', {
      //   thirdInterFaceId: this.query.thirdInterfaceId,
      //   appointPatientRegisterId: row.appointPatientRegisterId
      // }).then(res => {
      //   if (res.code > -1) {

      //     res.data.forEach(e => {
      //         e.discount = e.standardPrice == 0 ? 100: Math.floor(e.chargePrice * 10000/e.standardPrice)/100
      //         if(!e.isBelongGroupPackage){
      //           e.isBelongGroupPackage = e.isInMedicalPackage
      //         }              
      //         // e.standTotal = e.amount * e.standardPrice
      //         e.total = e.amount * e.chargePrice
      //       });
            
      //     this.tableDataDetails = res.data
      //   }
      // })

    },

    // 点击确定
    btnOk() {
      // if (!this.currRowData.appointPatientRegisterId) {
      //   this.$message.warning({ showClose: true, message: "请选择预约的记录" })
      //   return
      // }
      if (!this.currRowData.thirdBookingId) {
        this.$message.warning({ showClose: true, message: "请选择预约的记录" })
        return
      }        

      this.dataTransOpts.tableS.appoint_patient_register = this.dataTrans(this.currRowData)
      // this.dataTransOpts.tableM.appoint_register_asbitem = deepCopy(this.tableDataDetails)
      this.dialogWin.WebBookingMzak = false
    },

    dataTrans(curRow){
      // {  // 标准数据
      //   "appointPatientRegisterId": "string",
      //   "personId": "string",
      //   "personName": "string",
      //   "idNo": "string",
      //   "mobileTelephone": "string",
      //   "sexId": "string",
      //   "sexName": "string",
      //   "maritalStatusId": "string",
      //   "maritalStatusName": "string",
      //   "customerOrgId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //   "customerOrgName": "string",
      //   "childCustomerOrgName": "string",
      //   "customerOrgGroupId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //   "customerOrgGroupName": "string",
      //   "medicalPackageId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //   "medicalPackageName": "string",
      //   "completeFlag": "string",
      //   "appointDate": "2024-09-27T08:53:32.520Z",
      //   "remark": "string",
      //   "medicalCenterId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //   "customerOrgRegisterId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //   "pregnantFlag": "string",
      //   "pregnantFlagName": "string",
      //   "height": 0,
      //   "weight": 0
      // }

      // { // 人寿数据
      //   "thirdBookingId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //   "patientName": "string",
      //   "customerOrgGroupId": "string",
      //   "idNo": "string",
      //   "sexId": "string",
      //   "age": 0,
      //   "bookingDate": "2024-09-27T08:53:32.306Z",
      //   "phone": "string",
      //   "medicalStatus": "string",
      //   "customerOrgRegisterId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //   "customerOrgId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
      // }
      let ret = Object.assign({},curRow,{
        appointPatientRegisterId:curRow.thirdBookingId,
        mobileTelephone:curRow.phone,
        personName:curRow.patientName
      })
      return ret

    },

    // 点击关闭
    btnClose() {
      this.dataTransOpts.tableS.appoint_patient_register = {}
      this.dataTransOpts.tableM.appoint_register_asbitem = []
      this.dialogWin.WebBookingMzak = false
    },

    //自定义计算列
    getSummaries(param) {
      const { columns, data } = param;
      const sumCol = [6]  //需合计的列
      const sums = [];

      let count = this.tableDataDetails.length
      let pack = this.tableDataDetails.filter(e => { return e.isBelongGroupPackage == 'Y' }).length

      this.asbDesc = `共选 ${count} 个项目，其中套餐/分组 ${pack} 个，加做 ${count - pack} 个`

      columns.forEach((column, index) => {
        //console.log('column, index,data',column, index,data)
        //显示合计列
        if (index == 1) {
          sums[index] = `合计`;
          return;
        }

        //不合计的列
        if (sumCol.indexOf(index) == -1) {
          sums[index] = '';
          return;
        }

        sums[index] = 0
        data.forEach(e => {
          if (!isNaN(e[column.property])) {
            if (index == 1) {
              sums[index] += e[column.property] * e['amount']
            } else {
              sums[index] += e[column.property]
            }
          }
        })
        sums[index] = Math.round(sums[index] * 100) / 100 //+ ' 元';

        // const values = data.map(item => Number(item[column.property]));
        // if (!values.every(value => isNaN(value))) {
        //   sums[index] = values.reduce((prev, curr) => {
        //     const value = Number(curr);
        //     if (!isNaN(value)) {
        //       //return prev + curr;  //原始
        //       return prev + curr;  //改造
        //     } else {
        //       return prev;
        //     }
        //   }, 0);
        //   sums[index] = sums[index].toFixed(2) + ' 元';
        // } else {
        //   sums[index] = 'N/A';
        // }

      });
      this.totalStand = sums[1];
      //console.log('this.totalFoucs/this.discountFoucs',this.totalFoucs,this.discountFoucs)
      if (!this.totalFoucs) this.total = sums[5];
      if (!this.discountFoucs) this.discount = Math.round(this.total * 10000 / this.totalStand) / 100;
      return sums;
    },

    //回车替代查询
    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 '预约手机号':
                case '身份证号':
                case '姓名、电话、身份证号':
                  this.btnQuery()
                  input.select()
                  break;
              }
            }
          });

          input.addEventListener('click', (event) => {
            let placeholder = input.getAttribute('placeholder')
            switch (placeholder) {
              case '预约手机号':
              case '身份证号':
              case '姓名、电话、身份证号':
                input.select()
                break;
            }
          });
        });
      });
    },

  },

  //监听事件()
  watch: {
    "dataTransOpts.plus.WebBookingMzak": {
      // immediate:true,
      handler(newVal, oldVal) {
        console.log(`watch dataTransOpts.plus.WebBookingMzak newVal: ${newVal}, oldVal: ${oldVal} `);
        if (newVal != oldVal) this.funMounted()
      }
    },

  },

};
</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';

.query {
  margin-right: 10px;
  font-size: 14px;
  color: #232748;
  font-weight: 400;
  font-family: "NotoSansSC-Regular";
}

.spanClass {
  font-size: 14px;
  padding: 0 2px 0 0;
}
</style>
