<template>
  <h-view style="overflow:auto;" title="还款明细">
    <div class="page-box" style="width:100% height:100%">
      <ul id="box" style="margin-bottom: 150px;">
        <li v-for="(item, index) in Lists" :key="index" class="items">
          <input v-model="checked[index]" class="" type="checkbox" @mouseup="onClickHander(index)">
          <ul v-if="item.characterid_n == '首付款'" class="">
            <li><span>期数：</span>{{ item.times_str }}</li>
            <li><span>还款日期：</span>{{ item.recduedt_char }}</li>
            <!--<li><span>首期租赁费金额：</span>{{ item.recdueamt }}</li>-->
            <li><span>剩余应还首期租赁费：</span>{{ item.rec_rental_str }}</li>
            <!--<li><span>收款类别：</span>{{ item.characterid_n }}</li>-->
          </ul>
          <ul v-if="item.characterid_n == '租金'" class="">
            <li><span>期数：</span>{{ item.times_str }}</li>
            <li><span>还款日期：</span>{{ item.recduedt_char }}</li>
            <!--<li><span>租金金额：</span>{{ item.recdueamt }}</li>-->
            <!--<li><span>违约金金额：</span>{{ item.ovducmpsamt }}</li>-->
            <li><span>剩余应还租金：</span>{{ item.rec_rental_str }}</li>
            <li><span>剩余应还违约金：</span>{{ item.rec_ovdu_str }}</li>
            <!--<li><span>收款类别：</span>{{ item.characterid_n }}</li>-->
          </ul>
          <ul v-if="item.characterid_n == '留购金'" class="">
            <li><span>期数：</span>{{ item.times_str }}</li>
            <li><span>还款日期：</span>{{ item.recduedt_char }}</li>
            <!--<li><span>留购金金额：</span>{{ item.recdueamt }}</li>-->
            <li><span>剩余应还留购金：</span>{{ item.rec_rental_str }}</li>
            <!--<li><span>收款类别：</span>{{ item.characterid_n }}</li>-->
          </ul>
        </li>
      </ul>
    </div>
    <!-- 总计还款金额 -->
    <div v-if="bottomType == 0" class="bottomBox">
      <div class="total">
        <div class="counter"><span>合计还款金额：{{ total }}</span></div>
        <input
          id="payamount" type="number" placeholder="请输入支付金额" required
          oninvalid="setCustomValidity('请输入支付金额！');"
          oninput="setCustomValidity('');" onfocus="this.placeholder=''" onblur="this.placeholder='请输入支付金额'">
      </div>
      <button class="button1" @click="download()">账单查询</button>
      <button @click="pay">支付</button>
    </div>
    <!-- 二维码遮罩 -->
    <div v-if="bottomType == 1" class="ermPage">
      <div class="topBlack" />
      <div id="bottomErm" class="bottomErm">
        <div class="ermTitle">
          <button class="close" @click="close">
            <p>x</p>
          </button>
          <p>扫码支付</p>
        </div>
        <div class="ermTotal"><span>￥{{ showPayamount }}</span></div>
        <div id="qrcode" />
        <div class="ermBottom"><span>支持微信/支付宝/银联支付</span></div>
        <div class="ermImage">
          <img src="../../../assets\image\wechart.png" alt="">
          <img src="../../../assets\image\alipay.png" alt="">
          <img src="../../../assets\image\chinapay.png" alt="">
        </div>
      </div>
    </div>
  </h-view>
</template>

<script>
import QRCode from 'qrcodejs2'

export default {
  data () {
    return {
      contractno: '', // 接受参数
      bottomType: 0, // 控制显示哪个页面
      checked: [], // 多选绑定数组
      unchecked: [], // 记录每一个选项是否可选
      total: 0, // 总计金额
      ListNum: 0, // 总共有多少项
      Lists: [], // 原始数据
      payamount: 0, // 支付金额
      showPayamount: 0, // 后续支付结果页面显示
      recamt_id: '', // 获得的账单二维码
      counter: [10, 10, 1], // 前十次请求间隔,后十次请求间隔,间隔一/二
      timer: '',
      timer2: '',
      firstTime: -1,
      payTimes:[],
    }
  },
  created () {
    // 当数据拿到之后给checked初始值；
    var name = this.$route.query.contractno
    // console.log('传值', name)
    this.contractno = name
    this.getData()
  },
  beforeMount () {
  },
  methods: {
    getData () {
      // console.log('获取最新账单')
      let vm = this
      let url = process.env.basePath + 'getCmbConDetail'
      let params = {
        'contractno': this.contractno,
      }
      // console.log("请求");
      vm.$post(url, params).then(function (res) {
        if (res.success == true) {
          var dataInfo = JSON.parse(res.result.json)
          // console.log('请求成功', dataInfo.lists)
          vm.ListNum = dataInfo.lists.length
          // 给checked和unchecked初始值
          for (let i = 0; i < vm.ListNum; i++) {
            // console.log('给checked初始值');
            vm.checked[i] = false
            vm.unchecked[i] = dataInfo.lists[i].select_flag === 'N'
            if(dataInfo.lists[i].select_flag !== 'N'&&vm.firstTime===-1){
              vm.firstTime=dataInfo.lists[i].times
            }
          }
          vm.Lists = dataInfo.lists
        } else {
          vm.hlsPopup.showLongCenter('获取合同还款计划失败，请联系管理员')
        }
      }).then(function () {
        // 添加样式，区分不可选和可选的选项
        vm.addClass()
      })
      // console.log(vm.Lists);
    },
    // 点击支付
    pay () {
      let vm = this
      let $input = document.getElementById('payamount')
      //判断是否跳期
      let jumpFlag=true
      vm.payTimes=[]
      this.checked.forEach((item, index) => {
        if (item) {
          if(vm.Lists[index].times===vm.firstTime){
            jumpFlag=false
          }
          if(vm.Lists[index].characterid_n!=='留购金') {
            vm.payTimes.push(vm.Lists[index].times)
          }
        }
      })
      if(jumpFlag){
        vm.hlsPopup.showLongCenter('此前有未支付金额，请确认')
        return
      }

      if(vm.payTimes.length>1){
        jumpFlag=false
        let i=vm.payTimes[0]
        for(let j=0;j<vm.payTimes.length;j++){
          if(vm.payTimes[j]!==i){
            jumpFlag=true
            break
          }
          i++
        }
        if(jumpFlag){
          vm.hlsPopup.showLongCenter('此前有未支付金额，请确认')
          return
        }
      }

      // 点击支付之后显示二维码页面遮罩
      if ($input.value <= this.total && $input.value != 0) {
        // console.log($input.value);
        this.payamount = $input.value
        this.showPayamount = $input.value
        // 请求支付
        let vm = this
        let url = process.env.basePath + 'createLd037'
        let params = {
          'contractno': this.contractno,
          'amount': this.payamount,
        }
        vm.hlsPopup.showLoading('申请中!')
        vm.$post(url, params).then(function (res) {
          if (res.result.return_status == 'S') {
            var dataInfo = res.result
            vm.recamt_id = dataInfo.recamt_id
            // console.log('获取支付id', vm.recamt_id)
            vm.bottomType = 1
            $input.value = ''
            $input.placeholder = '请输入支付金额'
            vm.payamount = 0
            vm.total = 0
            vm.showRecamt()
          } else {
            vm.hlsPopup.hideLoading()
            vm.hlsPopup.showLongCenter(res.result.return_message)
          }
        })
      } else if (this.total == 0) {
        $input.value = ''
        $input.placeholder = '请选择要支付的款项'
      } else if ($input.value > this.total) {
        $input.value = ''
        $input.placeholder = '您输入的支付款过多！'
      } else if ($input.value === '') {
        $input.placeholder = '请输入支付金额'
      } else if ($input.value === 0) {
        $input.placeholder = '请输入支付金额'
      }
    },
    showRecamt () {
      let vm = this
      let url = process.env.rootPath + '/cmb/poly/get/qrcode'
      // console.log('支付id', this.recamt_id)
      let params = {
        'recamt_id': this.recamt_id,
      }
      // console.log('params', params)
      vm.$post(url, params).then(function (res) {
        // console.log(res)
        document.getElementById('qrcode').innerHTML = ''
        if (res.respCode == 'SUCCESS') {
          vm.hlsPopup.hideLoading()
          let dataInfo = res.qrCode
          let qrcode = new QRCode('qrcode',
            {
              text: dataInfo,
              width: 128,
              height: 128,
              colorDark: '#000000',
              colorLight: '#ffffff',
              correctLevel: QRCode.CorrectLevel.H, // 容错等级
            }
          )
          // console.log(qrcode)
        } else {
          vm.hlsPopup.hideLoading()
          vm.hlsPopup.showLongCenter(res.respMsg)
        }
      }).then(function (res) {
        vm.waitResult(params)
      })
    },
    waitResult (params) {
      var num = this.counter[0]// 记录请求次数
      var frequency = this.counter[1]// 记录请求次数
      clearInterval(this.timer)
      clearInterval(this.timer2)
      let vm = this
      let url = process.env.rootPath + '/cmb/poly/query/order/status'
      let urlp = process.env.rootPath + '/cmb/poly/close/order'
      //   this.timer = setInterval(() => {
      //     // console.log(num);
      //     num--
      //     if (num === 0) {
      //       num = number
      //       frequency++
      //       // 间隔x秒请求结果
      //       console.log(this.counter[2], frequency)
      //       vm.$post(url, params).then(function (res) {
      //         if (res.respCode == 'SUCCESS') {
      //           console.log('成功')
      //           // 接口文档上有状态，但实际没有;
      //           if (res.tradeState != 'P') {
      //             clearInterval(vm.timer)// 判断订单已支付暂停定时器
      //           };
      //           // 支付成功应该不需要前端主动关闭订单吧;
      //           // vm.closeBill(urlp, params);
      //           console.log(res.respMsg)
      //         } else {
      //           console.log(res.respMsg)
      //         }
      //       })
      //     };
      //     // 每15/30秒请求一次，每种间隔请求frequency次
      //     if (frequency === 10) {
      //       if (this.counter[2] === 1) {
      //         number = this.counter[1]
      //         frequency = 0
      //         this.counter[2] = 2
      //       } else {
      //         this.counter[2] = 1
      //         console.log('停止查询')
      //         clearInterval(this.timer)
      //         this.closeBill(urlp, params)// 关闭订单
      //       }
      //     }
      //   }, 1000)
      // },
      this.timer = setInterval(() => {
        // console.log(num);
        if (num !== 0) {
          num--
          // 间隔15秒请求结果
          // console.log('查询1', num)
          vm.$post(url, params).then(function (res) {
            if (res.respCode == 'SUCCESS') {
              // console.log('成功')
              // 接口文档上有状态，但实际没有;
              if (res.tradeState != 'P') {
                clearInterval(vm.timer)// 判断订单已支付暂停定时器
                if (res.tradeState == 'S') {
                  vm.hlsPopup.showLongCenter('支付完成')
                  vm.close()
                }
              };
              // 支付成功应该不需要前端主动关闭订单吧;
              // vm.closeBill(urlp, params);
              console.log(res.respMsg)
              // vm.hlsPopup.showLongCenter(res.respMsg)
            } else {
              console.log(res.respMsg)
              // vm.hlsPopup.showLongCenter(res.respMsg)
            }
          })
        } else {
          // 运行10次关闭定时器
          clearInterval(vm.timer)// 判断订单已支付暂停定时器
          this.timer2 = setInterval(() => {
            if (frequency !== 0) {
              frequency--
              // 间隔x秒请求结果
              // console.log('查询2', frequency)
              vm.$post(url, params).then(function (res) {
                if (res.respCode == 'SUCCESS') {
                  // console.log('成功')
                  // 接口文档上有状态，但实际没有;
                  if (res.tradeState != 'P') {
                    clearInterval(vm.timer2)// 判断订单已支付暂停定时器
                  };
                  console.log(res.respMsg)
                  // vm.hlsPopup.showLongCenter(res.respMsg)
                } else {
                  console.log(res.respMsg)
                  // vm.hlsPopup.showLongCenter(res.respMsg)
                }
              })
            } else { clearInterval(vm.timer2) }
          }, 30000)
        }
      }, 15000)
    },
    closeBill (urlp, params) {
      let vm = this
      vm.$post(urlp, params).then(function (res) {
        // console.log(res, '订单关闭')
        if (res.respCode == 'SUCCESS') {
          // console.log(res.respMsg)
          vm.hlsPopup.showLongCenter(res.respMsg)
        }
      })
    },
    close () {
      // 点击关闭二维码页面;
      this.bottomType = 0
      this.total = 0
      this.showPayamount = 0
      this.payamount = 0
      clearInterval(this.timer)
      clearInterval(this.timer2)
      this.getData()
    },
    // 选择账单后把总计金额显示在底部
    onClickHander (index) {
      if (this.Lists[index].select_flag == 'N') {
        return
      }
      var num = this.total
      // 计算
      if (this.checked[index] == false) {
        num = Math.round((num + this.Lists[index].recdueamt_total) * 100) / 100
      } else if (this.checked[index] == true) {
        num = Math.round((num - this.Lists[index].recdueamt_total) * 100) / 100
      }
      this.total = num
      document.getElementById('payamount').value = this.total
      // console.log(index)
    },
    // 根据getData时 生成的 unchecked:[] 给checkbox添加样式，true为不可选
    addClass () {
      for (var i = 0; i < this.ListNum; i++) {
        let $input = document.getElementById('box').children[i].children[0]
        let $ul = document.getElementById('box').children[i].children[1]
        // console.log($input.className);
        if (this.unchecked[i] == true) {
          $input.className = 'uncheck-box'
          $ul.className = 'uncheck-ul'
        } else {
          $input.className = 'check-box'
          $ul.className = 'check-ul'
        }
      }
    },
    download () {
      // console.log('下载')
      let contractno=this.contractno;
      window.open(process.env.basePath+'https://lease.hitachics.com:8990/ReportServer?reportlet=/report/HCLC_PDR003.cpt&CONTRACTNO=' + contractno + '&format=PDF&extype=simple', '_self')
    },
  },
}
</script>
<style lang="less" scoped>
.items {
  margin-top: 10px;
  display: flex;
  height: 75px;
  width: 100%;
  justify-content: space-between;
  font-size: 12px;

  /*可选和不可选的项目样式可能要不一样*/
  ul {
    margin-right: 3%;
    width: 87%;
    border: 2px solid #afafaf;
    border-radius: 8px;
    background-color: #ffffff;

    li {
      padding-left: 8px;
      padding-top: 15px;
      float: left;
      width: 50%;

      span {
        font-weight: 700;
      }
    }
  }

  .uncheck-ul {
    background-color: #ffffff;
  }

  .check-ul {
    background-color: #ffffff;
  }

  /*复选框样式*/
  input[type="checkbox"] {
    cursor: pointer;
    position: relative;
    width: 1rem;
    height: 1rem;
    font-size: 0.9rem;
    top: 50%;
    left: 3%;
    transform: translateY(-5px);
    visibility: hidden;
  }

  /*可选时选中和未选中两种状态*/
  .check-box[type="checkbox"]:checked::after {
    height: 18px;
    line-height: 15px;
    content: "✓";
    color: rgb(255, 255, 255);
    background-color: #7aae3b;
    border: 2px solid #7aae3b;
    font-size: 15px;
    font-weight: bold;
  }

  .check-box[type="checkbox"]::after {
    position: absolute;
    background-color: #ffffff;
    border: 2px solid #dab2b2;
    width: 18px;
    height: 18px;
    display: inline-block;
    visibility: visible;
    text-align: center;
    content: " ";
    border-radius: 50%;
  }

  /*不可选的样式*/
  .uncheck-box[type="checkbox"]::after {
    position: absolute;
    background-color: #d9d9d9;
    border: 2px solid #bfbfbf;
    width: 18px;
    height: 18px;
    display: inline-block;
    visibility: visible;
    text-align: center;
    content: " ";
    border-radius: 50%;
  }
}

.bottomBox {
  position: absolute;
  bottom: 0px;
  width: 100%;
  height: 18%;
  background-color: #fffffe;
  border-top: 2px solid #7aae3b;

  .total {
    font-size: 14px;
    font-weight: bolder;
    color: rgb(180, 0, 0);
    width: 90%;
    // height: 20 %;
    margin: 20px auto;
    display: flex;
    justify-content: space-around;
    align-items: flex-end;

    .counter {
      vertical-align: bottom;
      position: relative;
      bottom: 0px;
    }

    input {
      font-size: 12px;
      position: relative;
      right: 0px;
      width: 40%;
      border: 1px solid #a69a9a;
      border-radius: 5px;
      text-align: center;
      padding-left: 2%;
      padding-right: 2%;
    }
  }

  button {
    position: relative;
    width: 20%;
    height: 25%;
    //top: - 10 px;
    left: 42%;
    transform: translateX(-50%);
    font-size: 16px;
    color: #ffffff;
    border-radius: 8px;
    border: 1px solid rgb(0, 200, 0);
    background-color: rgb(0, 200, 0);
  }


.button1 {
  position: relative;
  /*margin-top: 3%;*/
  left: 40%;
  width: 20%;
  height: 25%;
  font-size: 16px;
  color: #fff;
  background-color: rgb(0, 200, 0);
  border: 2px solid rgb(0, 200, 0);
  border-radius: 5px;
  padding-right: 1px;
  padding-left: 1px;
}
}

.ermPage {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0px;
  left: 0px;

  .topBlack {
    width: 100%;
    height: 70%;
    background-color: rgb(140, 140, 140);
    opacity: 0.7;
  }

  .bottomErm {
    position: absolute;
    bottom: 0px;
    width: 100%;
    height: 40%;
    background-color: #ffffff;
    border: 1px solid #dab2b2;
    border-top-left-radius: 18px;
    border-top-right-radius: 18px;

    p {
      font-weight: 700;
      margin-top: 15px;
      padding-right: 20px;
      font-size: 16px;
      text-align: center;
    }

    .close {
      position: relative;
      float: left;
      left: 90%;
      padding: 0px;
      color: #fa9494;
      width: 24px;
      height: 24px;
      border-radius: 50%;
      border: 3px solid #dab2b2;
      font-size: 14px;

      p {
        position: relative;
        top: 0px;
        left: 0px;
        width: 18px;
        height: 18px;
        margin-top: -3px;
        padding: 0px;
        line-height: 18px;
        text-align: center;
      }
    }

    .ermTotal {
      font-weight: 700;
      margin-top: 10px;
      font-size: 16px;
      text-align: center;
    }

    .ermBottom {
      font-weight: 700;
      margin-top: 38%;
      font-size: 16px;
      text-align: center;
      color: rgb(55, 69, 197);
    }

    .ermImage {
      position: absolute;
      left: 38%;
      margin-top: 1%;

      img {
        width: 12%;
        height: 11%;
      }
    }

    #qrcode {
      position: absolute;
      width: 128px;
      height: 128px;
      top: 25%;
      left: 50%;
      transform: translateX(-50%);
      //background-color: #72a03c;
    }
  }
}
</style>
