<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.appointStartDate" 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.appointStopDate" 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.mobilePhone" size="small" clearable style="width: 110px" />
        </div>
        <div class="query">
          <span class="spanClass">身份证号</span>
          <el-input placeholder="身份证号" v-model="query.idNo" size="small" clearable style="width: 155px" />
        </div>

        <div class="query" v-if="false">
          <span class="spanClass">状态</span>
          <el-select v-model="query.completeFlag" placeholder="请选择" clearable style="width: 80px" size="small">
            <el-option v-for="item in dict.completeFlag" :key="item.id" :label="item.displayName" :value="item.id">
            </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="130" highlight-current-row
        size="small" @row-click="rowClick" ref="webBooking">
        <el-table-column label="姓名" width="80" prop="personName" align="center" />
        <el-table-column label="身份证号" width="150" prop="idNo" align="center" />
        <el-table-column label="预约时间" width="150" prop="appointDate" align="center" />
        <el-table-column label="性别" width="40" prop="sexName" align="center" />
        <el-table-column label="婚姻" width="40" prop="maritalStatusName" align="center" />
        <el-table-column label="单位" width="150" prop="customerOrgName" align="center" />
        <el-table-column label="分组/套餐" width="120" prop="customerOrgGroupName" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.customerOrgGroupName ? scope.row.customerOrgGroupName : scope.row.medicalPackageName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="怀孕" width="40" prop="pregnantFlagName" align="center" />
        <el-table-column label="身高" width="40" prop="height" align="center" />
        <el-table-column label="体重" width="40" prop="weight" align="center" />
      </el-table>

      <el-table :data="tableDataDetails" border style="width: 100%" row-key="id" height="300" highlight-current-row
      :summary-method="getSummaries" show-summary size="small" ref="webBookingDetaills"> 
        <el-table-column label="序号" width="40" type="index"/>
        <el-table-column label="已选组合项目" min-width="150" prop="asbitemName">
          <template slot-scope="scope">
            <div>              
              <el-tooltip class="item" effect="dark" content="标五角星表示属于分组或套餐的项目" placement="top">
                <i v-if="scope.row.isBelongGroupPackage == 'Y'" class="el-icon-star-on"
                  style="padding: 3px; font-size: 14px;color: purple;" />
              </el-tooltip>
              {{ scope.row.asbitemName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="标准价格" prop="standardPrice" min-width="70" align="center" />
        <el-table-column label="折扣" prop="discount" min-width="60">
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.discount" size="small" disabled/>
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="amount" min-width="50">
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.amount" size="small" disabled/>
          </template>
        </el-table-column>
        <el-table-column label="实收价格" prop="chargePrice" min-width="70">
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.chargePrice" size="small" disabled/>
            <!--立即触发保存 @blur="onSubmit('')"  -->
          </template>
        </el-table-column>
        <el-table-column prop="total" label="金额" min-width="70" align="center" />
        <el-table-column prop="standardPrice" label="标准金额" min-width="70" v-if="false" />
        <el-table-column label="支付方式" prop="payTypeFlag" width="80">
          <template slot-scope="scope">
            <el-select v-model="scope.row.payTypeFlag" size="small" disabled>
              <el-option v-for="item in dict.payType" :key="item.id" :label="item.displayName" :value="item.id" />
            </el-select>
          </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"
      },
      asbDesc: '', //所选套餐描述
      pickerOptions: {
        // disabledDate(time) {
        //   return time.getTime() > Date.now();
        // },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周后',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
    };
  },

  created() {

  },

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

    this.funMounted()
  },

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

  methods: {
    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.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
      }

      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"

      postapi('/api/app/AppointPatientRegister/GetListByFilter', 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)
    },

    async rowClick(row) {
      // chargeFlag	string  收费状态 0-未收费 1-已收费 2-已退费
      this.currRowData = Object.assign({},row)
      this.tableDataDetails = []

      let sysParmId = "small_program_individual_appointment_mandatory_fee"
      let sysParam = await postapi('/api/app/SysParmValue/GetSysParmValueBySysParmId', { sysParmId })
      // 要求强制收费
      if (sysParam.data == '1'){
        if(row.chargeFlag != '1'){
          this.$message.warning({ showClose: true, message: "该预约未缴费，不可进行登记" })
          this.currRowData = {}
          return
        }
      }


      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
              if(this.currRowData.chargeFlag == '1') e.isCharge = 'Y'
              e.total = e.amount * e.chargePrice
            });
            
          this.tableDataDetails = res.data
        }
      })

    },

    // 点击确定
    btnOk() {
      if (!this.currRowData.appointPatientRegisterId) {
        this.$message.warning({ showClose: true, message: "请选择预约的记录" })
        return
      }
      this.dataTransOpts.tableS.appoint_patient_register = deepCopy(this.currRowData)
      this.dataTransOpts.tableM.appoint_register_asbitem = deepCopy(this.tableDataDetails)
      this.dialogWin.WebBooking = false
    },

    // 点击关闭
    btnClose() {
      this.dataTransOpts.tableS.appoint_patient_register = {}
      this.dataTransOpts.tableM.appoint_register_asbitem = []
      this.dialogWin.WebBooking = 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 '身份证号':
                  this.btnQuery()
                  input.select()
                  break;
              }
            }
          });

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

  },

  //监听事件()
  watch: {
    "dataTransOpts.plus.WebBooking": {
      // immediate:true,
      handler(newVal, oldVal) {
        console.log(`watch 职业病 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>
