<template>
  <h-view id="addCar">
    <transition name="trans">
      <div v-show="downNum" class="modal-show">
        <div class="down">
          <div class="top">
            录入产品信息
            <!-- <img src="@/assets/intoApproval/close.png"  > -->
            <span @click="downNum=false">x</span>
          </div>
          <div class="down-content">
            <span>请上传照片</span>
            <div class="photo">
              <img :src="vehicleImg" @click="showBigPicture(vehicleImg)">
            </div>
            <list-item :item-height="44">
              <item>
                <div slot="name">车架号</div>
                <input
                  slot="content"
                  v-model="rentInfo.frame_number"
                  readonly
                  placeholder="自动识别车架号"
                >
              </item>
              <item>
                <div slot="name">发动机号</div>
                <input slot="content" v-model="rentInfo.engine" readonly placeholder="自动识别发动机号" >
              </item>
              <item>
                <div slot="name">车辆型号</div>
                <input
                  slot="content"
                  v-model="rentInfo.vehicle_model"
                  readonly
                  placeholder="自动识别车辆型号"
                >
              </item>
              <item>
                <div slot="name">合格证编号</div>
                <input
                  slot="content"
                  v-model="rentInfo.certificate_number"
                  readonly
                  placeholder="自动识别合格证编号"
                >
              </item>
              <item>
                <div slot="name">发车日期</div>
                <input slot="content" v-model="rentInfo.departure_date" readonly placeholder="暂无数据" >
              </item>
              <item>
                <div slot="name">开票日期</div>
                <input slot="content" v-model="rentInfo.invoice_date" readonly placeholder="暂无数据" >
              </item>
            </list-item>
          </div>
        </div>
      </div>
    </transition>
    <h-header :proportion="[5,1,1]" class="bar-custom">
      <div slot="left" class="h-header-btn">
        <img src="@/assets/userBind/arrow.png" @click="$routeGo()" >
        <span>合同明细</span>
      </div>
    </h-header>
    <Tab :title="text" @getTabNum="getTabNum" />
    <h-content>
      <div v-show="tabNum===0">
        <div class="userInfo">承租人信息</div>
        <list-item :item-height="44">
          <item>
            <div slot="name">合同号</div>
            <input slot="content" v-model="info.project_number" readonly placeholder="暂无数据" >
          </item>
          <item>
            <div slot="name">经销商</div>
            <input slot="content" v-model="info.bp_agent_name" readonly placeholder="暂无数据" >
          </item>
          <item>
            <div slot="name">承租人</div>
            <input slot="content" v-model="info.bp_name" readonly placeholder="暂无数据" >
          </item>
          <item>
            <div slot="name">产品名称</div>
            <input slot="content" v-model="info.division_n" readonly placeholder="暂无数据" >
          </item>
          <item>
            <div slot="name">设备识别号</div>
            <input slot="content" v-model="info.product_code" readonly placeholder="暂无数据" >
          </item>
          <item>
            <div slot="name">合同金额</div>
            <input slot="content" v-model="info.total_price" readonly placeholder="暂无数据" >
          </item>
          <item>
            <div slot="name">商务政策</div>
            <input slot="content" v-model="info.product_plan_id_n" readonly placeholder="暂无数据" >
          </item>
          <item>
            <div slot="name">租赁物数量</div>
            <input slot="content" v-model="info.product_num" readonly placeholder="请输入租赁物数量" >
          </item>
        </list-item>
        <div class="userInfo">设备清单</div>
        <div
          v-for="(item,index) in equip"
          :key="index"
          class="equipment"
          @click="downNum=true;getRent(item.contract_id,item.contract_lease_item_id)"
        >
          <div class="left">
            <span>
              <img src="@/assets/contractStart/list.png" >
            </span>
          </div>
          <div class="center">
            <span>租赁物信息</span>
            <span
              :class="['status',item.lease_status === 'Y'?'unMantain':'mantain']"
            >{{ item.lease_status === 'Y'?'已维护':'待维护' }}</span>
            <p>
              设备识别号
              <span>{{ item.product_code }}-{{ index+1|lengthCheck }}</span>
            </p>
          </div>
          <div class="right">
            <img src="@/assets/contractStart/into.png" >
          </div>
        </div>
      </div>
      <!-- <div v-show="tabNum===1">
        <list-item :item-height="56" class="contract-text" style="background-color:rgb(250,250,250);">
          <item :proportion="[7,1]">
            <div slot="name" class="aguremrnt-list">
              <img src="@/assets/constractSigning/npack.png" alt class="pics" >
              <p class="second first">承租人确认意见</p>
            </div>
            <div slot="content" class="in-detail" @click="goContractContent('承租人确认意见')">
              <img src="@/assets/constractSigning/detail.png" alt >
            </div>
          </item>
          <item :proportion="[7,1]">
            <div slot="name" class="aguremrnt-list">
              <img src="@/assets/constractSigning/pack.png" alt class="pics" >
              <p class="second">融资租赁合同</p>
              <img :src="leasePic" alt class="read" >
            </div>
            <div slot="content" class="in-detail" @click="goContractContent('融资租赁合同')">
              <img src="@/assets/constractSigning/detail.png" alt >
            </div>
          </item>
          <item :proportion="[7,1]">
            <div slot="name" class="aguremrnt-list">
              <img src="@/assets/constractSigning/pack.png" alt class="pics" >
              <p class="second">租赁物所有权转移及接收确认书</p>
              <img :src="agentPic" alt class="read" >
            </div>
            <div slot="content" class="in-detail" @click="goContractContent('租赁物所有权转移及接收确认书')">
              <img src="@/assets/constractSigning/detail.png" alt >
            </div>
          </item>
        </list-item>
      </div>-->
      <div v-show="tabNum===1">
        <list-item
          :item-height="56"
          class="contract-text"
          style="background-color:rgb(250,250,250);"
        >
          <item v-for="(item,index) in attachArray" :proportion="[7,1]" :key="index">
            <div slot="name" class="aguremrnt-list">
              <img src="@/assets/constractSigning/npack.png" alt class="pics" >
              <p class="second first">{{ item.attachment_file }}</p>
              <img v-if="item.read_status === 'N'" class="unread" src="@/assets/constractSigning/unread.png" >
              <img v-if="item.read_status === 'Y'" class="unread" src="@/assets/constractSigning/read.png" >
            </div>
            <div slot="content" class="in-detail" @click="goContent(item)">
              <img src="@/assets/constractSigning/detail.png" alt >
            </div>
          </item>
        </list-item>
      </div>
    </h-content>
    <bottom-tab v-if="!flag">
      <tab-button class="before" @click.native="takePhonto">
        <img src="@/assets/constractSigning/certification.png" >认证
      </tab-button>
      <tab-button class="approve" @click.native="isConfirm">确定</tab-button>
    </bottom-tab>
    <!--活体检测-->
    <body-check ref="body" :check_id="$route.params.check_id" :confirm_id="confirm_id" />
  </h-view>
</template>
<script>
import Tab from '@/pages/carConfirm/tab'
import bodyCheck from './body-check'
export default {
  components: {
    Tab,
    bodyCheck,
  },
  filters: {
    lengthCheck: function (value) {
      if (value.toString().length === 1) {
        return `0${value}`
      } else {
        return value
      }
    },
  },
  data () {
    return {
      num: null,
      downNum: false,
      attachArray: [],
      show: false,
      flag: false, // 判断是否为已确认
      vehicleImg: '', // 查询到的合格证
      leasePic: '', // 租赁合同图片
      agentPic: '', // 经销商担保协议图片
      bankPic: '', // 农行代扣授权书图片
      legalPic: '', // 法人授权书图片
      confirm_id: '',
      readed: require('@/assets/constractSigning/read.png'), // 已读
      unRead: require('@/assets/constractSigning/unread.png'), // 未读
      tabNum: 0,
      text: {
        first: '合同详情',
        second: '合同文本',
      },
      info: {
        product_plan_id: '',
        product_num: '',
        first_pay: '',
        division_n: '',
        gps_fee: '',
        bp_name: '',
        project_number: '',
        bp_agent_name: ' ',
        product_plan_id_n: '',
        product_code: '',
      },
      rentInfo: {
        frame_number: '',
        engine: '',
        manufacturer: '',
        license_plate_number: '',
        vehicle_model: '',
        certificate_number: '',
        departure_date: '',
        invoice_date: '',
      },
      products: [],
      equip: [
        {
          product_id: '3',
          product_code: 'GTC389',
          contract_id: '231',
        },
      ],
    }
  },
  computed: {},
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (from.name === 'ConfirmList') {
        vm.getDetail()
        vm.getEquipment()
        vm.getAttachment()
      }
      vm.confirm_id = vm.$route.params.confirm_id
      vm.agentPic = vm.unRead
      vm.leasePic = vm.unRead
      if (vm.$route.params.confirm_status === 'SUBMIT') {
        vm.flag = false
      } else if (vm.$route.params.confirm_status === 'APPROVED') {
        vm.flag = true
      }
    })
  },
  methods: {
    // 合同文本详情附件查询
    getAttachment () {
      let vm = this
      let url = process.env.basePath + 'get_content_app'
      let param = {
        confirm_id: vm.$route.params.confirm_id,
        data_class: 'LEASE_ITEM',
      }
      hlsPopup.showLoading('请稍候')
      vm.hlsHttp.post(url, param).then(res => {
        hlsPopup.hideLoading()
        if (res.result === 'S') {
          vm.attachArray = res.attachments
        } else {
          vm.hlsPopup.showLongCenter(res.message)
        }
      })
    },
    goContent (item) {
      // 详情
      // window.open(url)
      // cordova.InAppBrowser.open(url, '_self', 'location=yes')
      cordova.ThemeableBrowser.open(item.attachment_file_path, '_blank', {})

      let vm = this
      let url = process.env.basePath + 'prj_content_status_save'
      let param = {
        master: {
          content_id: item.content_id,
          auth_credit_flag: 'Y',
        },
      }
      hlsPopup.showLoading('请稍候')
      vm.hlsHttp.post(url, param).then(res => {
        hlsPopup.hideLoading()
        if (res.result === 'S') {
        } else {
          vm.hlsPopup.showLongCenter(res.message)
        }
      })
    },
    getImg (id) {
      // 获取合格证
      let vm = this
      let randomString = Math.floor(Math.random() * 21)
      let url =
        process.env.basePath +
        'app_attment_query' +
        '&index' +
        `'${randomString}'`
      let param = {
        master: {
          source_type: 'CON_CONTRACT_LEASE_ITEM',
          pkvalue: id,
        },
      }
      vm.$post(url, param).then(function (res) {
        if (res.result === 'S') {
          if (res.info) {
            vm.vehicleImg =
              process.env.filePath +
              'attachment_id=' +
              res.info.attachment_id +
              '&access_token=' +
              window.localStorage.access_token
          }
        } else {
          hlsPopup.showLongCenter(res.message)
        }
      })
    },
    // 签约校验
    async signCheck () {
      let vm = this
      let url = process.env.basePath + 'sign_check'
      let param = {
        confirm_id: vm.confirm_id,
        data_class: 'LEASE_ITEM',
      }
      vm.hlsPopup.showLoading('请稍后!')
      let res = await vm.hlsHttp.post(url, param)
      vm.hlsPopup.hideLoading()
      if (res.result === 'S') {
        return true
      } else {
        vm.hlsPopup.showLongCenter(res.message)
      }
    },
    getTabNum (i) {
      this.tabNum = i
    },
    takePhonto () {
      let vm = this
      hlsPopup.showConfirm({
        title: '提示',
        content: '请自拍一张',
        onConfirm: function (index) {
          if (index === 1) {
            vm.takePhontoOpenCamera()
          } else {
          }
        },
      })
    },
    // 查看大图
    showBigPicture (pic) {
      let vm = this
      vm.hlsPopup.showBigPicture({
        imgUrl: pic,
        width: '100%',
      })
    },
    // 打开相机自拍
    takePhontoOpenCamera () {
      let vm = this
      vm.faceListUpload = []
      let obj = {
        pkvalue: vm.$route.params.check_id,
        source_type: 'PRJ_CDD_ITEM_CHECK',
        picture: '',
        filePath: '',
        attachment_id: '',
        user_id: 1,
        fileName: 'face',
      }
      let cameraoptions = {
        quality: 100,
        cameraDirection: 1,
      }
      let success = function (imgdata) {
        obj.filePath = imgdata
        // obj.filePath = 'http://hlsapp.hand-china.com/file/XCMG/2.jpg'
        vm.confirmContractSign(imgdata)
        vm.faceListUpload.push(obj)
      }
      let error = function () {
        hlsPopup.showLongCenter('请拍照')
      }
      hlsUtil.openCamera(cameraoptions, success, error)
    },
    // 执行同意的逻辑(查询对应的身份证正面图片->人脸识别->确认签约)
    async confirmContractSign (faceImg) {
      let idCardImgUrl = await this.idCardImgUrlGet()
      if (idCardImgUrl) {
        this.faceIdentify(faceImg, idCardImgUrl)
      }
    },
    // 获取身份证照片
    async idCardImgUrlGet () {
      let vm = this
      let url = $config.basePath + 'car_id_card_query'
      let param = {
        confirm_id: vm.confirm_id,
      }
      hlsPopup.showLoading('请稍候')
      let res = await vm.$post(url, param)
      hlsPopup.hideLoading()
      if (res.result === 'S' && res.info) {
        let cardUrl =
          process.env.filePath +
          'attachment_id=' +
          res.info.attachment_id +
          '&access_token=' +
          window.localStorage.access_token
        return cardUrl
      } else if (res.result === 'S' && !res.info) {
        hlsPopup.showLongCenter('未找到身份证照片')
        return null
      } else {
        hlsPopup.showLongCenter(res.message)
        return null
      }
    },
    // 人脸比对
    faceIdentify (faceImg, idCardImgUrl) {
      let vm = this
      let obj = {
        fileUrl: faceImg,
        idCardImgUrl: idCardImgUrl,
      }
      hlsPopup.showLoading('正在比对')
      let url = process.env.ocrPath + '/baidu/ocr/face'
      hlsUtil.baiduOcrFace(obj, url, function (res) {
        hlsPopup.hideLoading()
        if (res.success) {
          vm.save_picture(vm.faceListUpload)
          let identifyScore = res.result.result.score.toFixed(0)
          hlsPopup.showPopup({
            title: '提示',
            content: `识别分数为${identifyScore},请进行活体检测`,
            onConfirm: () => {
              // 进入活体检测页面
              vm.goBodyCheck(vm.confirm_id)
            },
          })
        } else {
          hlsPopup.showLongCenter('比对失败,请保证和绑定时是同一个人')
        }
      })
    },
    goBodyCheck (confirm_id) {
      // 活体检测
      this.$refs.body.show()
      /* this.$router.push({
        name: 'BodyCheck',
        params: {
          check_id: this.$route.params.check_id,
          confirm_id: confirm_id,
        },
      }) */
    },
    // 图片保存
    save_picture (list) {
      // alert('list' + JSON.stringify(list))
      let vm = this
      if (list.length) {
        // hlsPopup.showLoading('图片上传请稍候')
        var alreadyUploadNum = 0
        var attLength = 0
        var recordUploadInterval = setInterval(function () {
          if (alreadyUploadNum === attLength) {
            clearInterval(recordUploadInterval)
            /* hlsPopup.hideLoading()
            hlsPopup.showLongCenter('图片上传成功') */
          }
        }, 500)
        for (var i = 0; i < list.length; i++) {
          let uploadSuccess = function (res) {
            if (res.result === 'S') {
              alreadyUploadNum++
              for (var j = 0; j < list.length; j++) {
                if (list[j].filePath === res.response.filePath) {
                  list[j].attachment_id = res.response.attachment_id
                  vm.faceListUpload.push(list[j])
                  // alert('faceListUpload' + JSON.stringify(vm.faceListUpload))
                  break
                }
              }
            } else {
              hlsPopup.hideLoading()
            }
          }
          if (!list[i].attachment_id) {
            attLength++
            hlsUtil.fileUploadSvc(list[i], uploadSuccess)
          }
        }
      } else {
        hlsPopup.hideLoading()
      }
    },
    async isConfirm () {
      let vm = this
      let flag = await this.signCheck()
      if (flag) {
        // 只有认证通过后方可进行签约操作
        this.hlsPopup.showConfirm({
          title: '提示',
          content: '您确定同意发车吗？',
          onConfirm: data => {
            if (data === 1) {
              this.confirm()
            }
          },
        })
      }
    },
    confirm () {
      let vm = this
      let url = process.env.basePath + 'do_car_confirm'
      let param = {
        master: {
          confirm_id: vm.confirm_id,
          confirm_status: 'APPROVED',
          confirm_note: '同意',
        },
      }
      hlsPopup.showLoading('请稍候')
      vm.$post(url, param).then(function (res) {
        vm.hlsPopup.hideLoading()
        if (res.result === 'S') {
          vm.equip = res.lists
          vm.hlsPopup.showSuccess('发车成功')
          setTimeout(() => {
            vm.$router.push({
              name: 'ConfirmList',
            })
          }, 2000)
        } else {
          hlsPopup.showLongCenter(res.message)
        }
      })
    },
    // 跳转合同详情
    goContractContent (name) {
      this.$router.push({
        name: 'ContractContent',
        params: {
          name,
          business_type: this.$route.params.business_type,
        },
      })
      if (name === '经销商担保协议') {
        setTimeout(() => {
          this.agentPic = this.readed
        }, 1000)
      } else if (name === '租赁主合同') {
        setTimeout(() => {
          this.leasePic = this.readed
        }, 1000)
      }
    },
    getEquipment () {
      let vm = this
      let url = process.env.basePath + 'car_equip_list_query'
      let param = {
        project_id: this.$route.params.project_id,
      }
      hlsPopup.showLoading('请稍候')
      vm.$post(url, param).then(function (res) {
        vm.hlsPopup.hideLoading()
        if (res.result === 'S') {
          vm.equip = res.lists
        } else {
          hlsPopup.showLongCenter(res.message)
        }
      })
    },
    getRent (e, id) {
      let vm = this
      let url = process.env.basePath + 'leases_info_query'
      let param = {
        contract_id: e,
      }
      hlsPopup.showLoading('请稍候')
      vm.$post(url, param).then(function (res) {
        vm.hlsPopup.hideLoading()
        if (res.result === 'S') {
          Object.assign(vm.rentInfo, res.info)
          vm.getImg(id)
        } else {
          hlsPopup.showLongCenter(res.message)
        }
      })
    },

    getDetail () {
      let vm = this
      let url = process.env.basePath + 'con_contract_detial'
      let param = {
        project_id: this.$route.params.project_id,
      }
      hlsPopup.showLoading('请稍候')
      vm.$post(url, param).then(function (res) {
        vm.hlsPopup.hideLoading()
        if (res.result === 'S') {
          vm.info = res.info
        } else {
          hlsPopup.showLongCenter(res.message)
        }
      })
    },
  },
}
</script>
<style lang="less" scoped>
#addCar {
  input::placeholder {
    color: #888c8f;
  }
  .trans-enter-active,
  .trans-leave-active {
    transition: opacity 0.5s;
  }
  .trans-enter,
  .trans-leave-active {
    opacity: 0;
  }
  .aguremrnt-list {
    display: flex;
    flex-direction: row;
    .unread {
      width: 34px;
      height: 20px;
      margin: 8px 0 0 4px;
    }
    .pic {
      margin-left: -3px;
    }

    .pics {
      //    width: 21px;
      height: 30px;
    }

    .read {
      height: 16px;
      margin-top: 8px;
      margin-left: 6px;
    }

    .second {
      height: 32px;
      line-height: 32px;
      font-family: PingFangSC-Regular;
      font-size: 14px;
      margin-left: 16px;
      color: #383f45;
      letter-spacing: 0.43px;
    }

    .first {
      margin-left: 13px;
    }
  }

  .contract-text {
    .border-red {
      border: 2px solid rgba(255, 0, 0, 0.4);
    }

    .hls-item {
      margin-top: 8px;
      background-color: #fff;
    }

    .contents {
      padding: 0;
    }

    .in-detail {
      background-color: rgba(0, 70, 156, 0.08);
      width: 48px;
      height: 56px;
      text-align: center;
      line-height: 65px;

      img {
        width: 16px;
      }
    }

    .in-all {
      //width: 96px;
      display: flex;

      img {
        width: 16px;
      }

      div {
        width: 48px;
        height: 56px;
        text-align: center;
        line-height: 65px;
      }

      div:first-child {
        background-color: rgba(252, 200, 0, 0.1);
      }

      div:nth-child(2) {
        background-color: rgba(0, 70, 156, 0.08);
      }
    }
  }
  .hide {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    img {
      width: 30px;
      height: 30px;
      margin-left: 65%;
    }
  }
  .wrap {
    padding-top: 92px;
  }
  .modal-show {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 900;
    background-color: rgba(56, 63, 69, 0.3);
    display: flex;
    justify-content: center;
    align-items: center;
    .down {
      position: relative;
      width: 314px;
      height: 526px;
      background-size: 301px 24.7px;
      background-color: #fff;
    }
    .top {
      width: 100%;
      height: 44px;
      font-family: PingFangSC-Semibold;
      font-size: 16px;
      letter-spacing: 0;
      text-align: center;
      line-height: 44px;
      color: #fff;
      background: #0041c4;
      span {
        font-size: 24px;
        float: right;
        margin-right: 10px;
        font-family: YouYuan;
        // margin-left:100px;
      }
    }
    .down-content {
      margin-top: 8px;
      span:first-child {
        font-family: PingFangSC-Regular;
        font-size: 13px;
        color: #656464;
        letter-spacing: 0;
        margin-left: 15px;
      }
      .photo {
        width: 172px;
        height: 120px;
        border: 1px solid #dcdcdd;
        border-radius: 2px;
        margin: 0 auto;
        margin-top: 12px;
        background: url("../../assets/contractStart/photo.png") 70px no-repeat;
        background-size: 24px 20px;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .userInfo {
    height: 45px;
    line-height: 45px;
    color: #0041c4;
    font-size: 15px;
    margin-left: 16px;
    position: relative;
  }
  .userInfo::before {
    content: "";
    display: block;
    width: 4px;
    height: 20px;
    background-color: #0041c4;
    position: absolute;
    left: -15px;
    top: 12px;
  }
  .equipment:not(:first-child) {
    margin-top: 2px;
  }
  .equipment {
    width: 359px;
    height: 72px;
    background-color: #fff;
    margin: 0 auto;
    display: flex;
    .left {
      flex: 1;
      span {
        display: block;
        width: 30px;
        height: 30px;
        background-color: #e8e9ed;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 10px;
        margin-top: 8px;
        img {
          width: 11px;
          height: 14px;
        }
      }
    }
    .center {
      flex: 6;
      span:first-child {
        font-family: PingFangSC-Regular;
        font-size: 14px;
        color: #383f45;
        letter-spacing: 0.43px;
        margin-left: 10px;
        margin-top: 12px;
      }
      .status {
        display: inline-block;
        width: 46px;
        height: 16px;
        text-align: center;
        line-height: 16px;
        font-family: PingFangSC-Medium;
        font-size: 12px;
        color: #ffffff;
        letter-spacing: 0;
        margin-left: 21px;
        margin-top: 12px;
      }
      .unMantain {
        background-color: #1d3fff;
      }
      .mantain {
        background-color: #fff;
        border: 1px solid #1d3fff;
        color: #1d3fff;
      }
      p {
        font-family: PingFangSC-Regular;
        font-size: 13px;
        color: rgba(56, 63, 69, 0.6);
        letter-spacing: 0.4px;
        margin-left: 10px;
        margin-top: 10px;
        span {
          font-family: Helvetica;
          font-size: 13px;
          color: rgba(56, 63, 69, 0.6);
        }
      }
    }
    .right {
      flex: 1;
      display: flex;
      align-items: center;
      img {
        width: 13px;
        height: 13px;
      }
    }
  }
  .approve {
    color: #fff;
    background-color: #0041c4;
  }
  .before {
    border: 1px solid #fdb62f;
    border-radius: 4px;
    color: #fdb62f;
    img {
      width: 18px;
    }
  }
}
</style>
