<template>
  <h-view id="create-enclosure-info">
    <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>
    <h-content>
      <div class="top">
        <div class="item">
          <img src="@/assets/contractCreate/finished.png" >
          <p>基本信息</p>
        </div>
        <span class="line" />
        <div class="item">
          <img src="@/assets/contractCreate/finished.png" >
          <p>租赁信息</p>
        </div>
        <span class="line" />
        <div class="item">
          <span v-if="!isReadOnly">3</span>
          <img v-if="isReadOnly" src="@/assets/contractCreate/finished.png" >
          <p style="color: #383F45;">附件信息</p>
        </div>
      </div>
      <div class="userInfo">基本资料</div>
      <div v-if="bpClass === 'ORG'" class="house">
        <p class="titles">营业执照</p>
        <div v-if="licenseImg" class="card-upload">
          <img :src="licenseImg" @click="showBigPicture(licenseImg)">
        </div>
      </div>
      <div class="house">
        <p v-if="bpClass === 'NP'" class="titles">身份证</p>
        <p v-if="bpClass === 'ORG'" class="titles">法人代表身份证</p>
        <div class="upload-box">
          <div v-if="idCardFront">
            <img
              v-if="idCardFront"
              :src="idCardFront"
              style="width: 100%;height: 100%;margin: 0"
              @click="showBigPicture(idCardFront)"
            >
          </div>
          <div v-if="idCardBack">
            <img
              v-if="idCardBack"
              :src="idCardBack"
              style="width: 100%;height: 100%;margin: 0"
              @click="showBigPicture(idCardBack)"
            >
          </div>
        </div>
      </div>
      <div class="house">
        <p class="titles">房产证件</p>
        <div v-if="houseImg" class="card-upload">
          <img :src="houseImg" @click="showBigPicture(houseImg)">
        </div>
      </div>
      <div class="house">
        <p class="titles">车辆行驶证</p>
        <div v-if="carImg" class="card-upload">
          <img :src="carImg" @click="showBigPicture(carImg)">
        </div>
      </div>
      <div v-if="bpClass === 'NP'" class="house">
        <p class="titles">婚姻状况证明</p>
        <div v-if="marryImg" class="card-upload">
          <img :src="marryImg" @click="showBigPicture(marryImg)">
        </div>
      </div>
      <div class="userInfo">补充资料</div>
      <div class="house">
        <p class="titles">特批申请书</p>
        <!--待上传图片列表-->
        <div
          v-for="(item, index) in upload_list"
          v-if="item.check_id === checkId"
          :key="index"
          class="card-upload"
        >
          <img :src="item.picture" @click="showBigPicture(item.picture)" >
          <div class="close" @click="remove_pic(item.attachment_id,index)">
            <img src="@/assets/userBind/deleteIcon.png" >
          </div>
        </div>
        <!--从服务器上下载的图片-->
        <div v-for="(pic, index) in dowload_list" :key="index">
          <div v-if="pic.check_id==checkId" :key="index" class="card-upload">
            <img :src="pic.url" @click="showBigPicture(pic.url)" >
            <div class="close" @click="delete_pic(pic.attachment_id)">
              <img src="@/assets/userBind/deleteIcon.png" >
            </div>
          </div>
        </div>
        <div v-if="!isReadOnly" class="card-upload plus" @click="ocrShow('特批申请书',checkId)">
          <img src="@/assets/userBind/camera.png" class="upload-btn" >
        </div>
      </div>
    </h-content>
    <bottom-tab class="add-box">
      <tab-button v-if="!isReadOnly" class="before" @click.native="handSave">保存</tab-button>
      <tab-button v-if="!isReadOnly" class="next" @click.native="isSubmit">提交</tab-button>
      <tab-button v-if="isReadOnly" class="before" @click.native="$routeGo()">上一步</tab-button>
    </bottom-tab>
  </h-view>
</template>
<script>
export default {
  data () {
    return {
      checkId: '', // 特批申请书id
      cddItemList: [],
      upload_list: [],
      dowload_list: [], // 下载图片列表
      idCardFrontCheck_id: '', // 承租人身份证正面
      idCardBackCheck_id: '', // 承租人身份证背面
      idCardFrontUrlFlag: false,
      idCardBackUrlFlag: false,
      houseFlag: false,
      carFlag: false,
      licenseFlag: false,
      idCardFront: '', // 身份证图片
      idCardBack: '',
      houseImg: '',
      carImg: '',
      marryImg: '',
      licenseImg: '',
      house_id: '',
      car_id: '',
      license_id: '',
      status: '', // 审批状态
      bpClass: '',
      isReadOnly: false, // 是否只读
      fromPage: window.localStorage.fromPage,
    }
  },
  watch: {

  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (from.name === 'CreateRentInfo') {
        vm.idCardFront = ''
        vm.idCardBack = ''
        vm.houseImg = ''
        vm.carImg = ''
        vm.marryImg = ''
        vm.licenseImg = ''
        vm.upload_list = []
        vm.dowload_list = []
        vm.cddItemList = []
        vm.bpClass = window.localStorage.bp_class
        vm.status = window.localStorage.user_bp_status
        vm.fromPage = window.localStorage.fromPage
        vm.loadItemList()
        vm.queryCheckId()
        if (vm.fromPage === 'sale') {
          vm.isReadOnly = false
        } else if (vm.fromPage === 'list') {
          if (window.localStorage.contractReadonly === 'true') {
            vm.isReadOnly = true
          } else {
            vm.isReadOnly = false
          }
        }
      }
    })
  },
  methods: {
    // 特批证书check_id查询
    queryCheckId () {
      let vm = this
      let url = process.env.basePath + 'prj_atm_query'
      let param = {
        project_id: window.localStorage.project_id,
      }
      vm.hlsPopup.showLoading('请稍候')
      vm.hlsHttp.post(url, param).then(function (res) {
        vm.hlsPopup.hideLoading()
        console.log('特批证书check_id查询', res)
        if (res.result === 'S') {
          vm.checkId = res.info.check_id
          vm.certificateQuery()
        }
      })
    },
    // 特批证书查询
    certificateQuery () {
      let vm = this
      let url =
        process.env.basePath + 'attachment_list_query' // 附件查询
      let param = {
        check_id: vm.checkId,
      }
      hlsPopup.showLoading('请稍候')
      vm.$post(url, param).then(function (res) {
        vm.hlsPopup.hideLoading()
        if (res.result === 'S') {
          res.lists.forEach(item => {
            item['url'] =
              process.env.filePath +
              'attachment_id=' +
              item.attachment_id +
              '&access_token=' +
              window.localStorage.access_token
          })
          vm.dowload_list = res.lists
          console.log('下载图片', vm.dowload_list)
        }
      })
    },
    // 查看大图
    showBigPicture (pic) {
      let vm = this
      vm.hlsPopup.showBigPicture({
        imgUrl: pic,
        width: '100% !important',
      })
    },
    // ocr识别入口
    ocrShow (desc, checkId) {
      let vm = this
      hlsPopup.showActionSheet({
        titleText: '请选择照片',
        buttonArray: ['拍照', '从相册取'],
        callback: index => {
          if (index === 0) {
            vm.openCamera(desc, checkId)
          } else {
            vm.takePicture(desc, checkId)
          }
        },
      })
    },
    openCamera (desc, checkId) {
      let vm = this
      let obj = {
        'pkvalue': checkId,
        'source_type': 'PRJ_CDD_ITEM_CHECK',
        'picture': '',
        'check_id': checkId,
        'filePath': '',
        'attachment_id': '',
        'user_id': 1,
        'fileName': desc + '_' + new Date().getTime(),
      }
      let cameraoptions = {
        quality: 100,
      }
      let success = function (imgdata) {
        obj.picture = imgdata
        obj.filePath = imgdata
        let list = []
        list.push(obj)
        // 拍完一张立马执行保存图片逻辑
        vm.save_picture(list)
      }
      let error = function () {
        hlsPopup.showLongCenter('请拍照')
      }
      hlsUtil.openCamera(cameraoptions, success, error)
    },
    takePicture (desc, checkId) {
      let vm = this
      let cameraoptions = {
        quality: 100,
      }
      let success = function (imgUrl) {
        var list = []
        for (let i = 0; i < imgUrl.length; i++) {
          let obj = {
            'pkvalue': checkId,
            'source_type': 'PRJ_CDD_ITEM_CHECK',
            'picture': '',
            'check_id': checkId,
            'filePath': '',
            'attachment_id': '',
            'user_id': 1,
            'fileName': desc + '_' + new Date().getTime(),
          }
          obj.picture = imgUrl[i]
          obj.filePath = imgUrl[i]
          list.push(obj)
        }
        vm.save_picture(list)
      }
      let error = function () {
      }
      vm.hlsUtil.takePicture(cameraoptions, success, error)
    },
    // 图片保存
    save_picture (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.upload_list.push(list[j])
                  break
                }
              }
            } else {
              hlsPopup.hideLoading()
            }
          }
          if (!list[i].attachment_id) {
            attLength++
            hlsUtil.fileUploadSvc(list[i], uploadSuccess)
          }
        }
      } else {
        hlsPopup.hideLoading()
      }
    },
    // 移除图片
    remove_pic (attachment_id, index) {
      let vm = this
      var delete_list = []
      let obj = {'attachment_id': attachment_id}
      delete_list.push(obj)
      let url = process.env.basePath + 'app_delete_attment' // 附件删除
      let param = {
        'picturelist': delete_list,
      }
      hlsPopup.showLoading('请稍候')
      vm.hlsHttp.post(url, param).then(function (res) {
        hlsPopup.hideLoading()
        if (res.result === 'S') {
          hlsPopup.showLongCenter('删除成功!')
          vm.remove_upload_list(attachment_id, index)
        } else if (res.result === 'E') {
          hlsPopup.showShortCenter(res.message)
        }
      })
    },
    remove_upload_list (attachment_id, index) {
      let vm = this
      vm.upload_list.remove(index)
      vm.upload_list.sort()
    },
    // 删除图片
    delete_pic (attachment_id) {
      let vm = this
      var delete_list = []
      let obj = {'attachment_id': attachment_id}
      delete_list.push(obj)
      let url = process.env.basePath + 'app_delete_attment' // 附件删除
      let param = {
        'picturelist': delete_list,
      }
      hlsPopup.showLoading('请稍候')
      vm.hlsHttp.post(url, param).then(function (res) {
        hlsPopup.hideLoading()
        if (res.result === 'S') {
          hlsPopup.showLongCenter('删除成功!')
          vm.remove_dowload_list(attachment_id)
        } else if (res.result === 'E') {
          hlsPopup.showShortCenter(res.message)
        }
      })
    },
    remove_dowload_list (attachment_id) {
      console.log('attachment_id', attachment_id)
      let vm = this
      vm.dowload_list = vm.dowload_list.filter(item => {
        return item.attachment_id !== attachment_id
      })
    },
    loadItemList () {
      let vm = this
      let bp_id_tenant = window.localStorage.getItem('bp_id_tenant')
      let url = process.env.basePath + 'prj_cdd_check_list'
      let group = ''
      if (vm.bpClass === 'NP') {
        group = 'HLS_NP'
      } else {
        window.localStorage.auth_flag === '是' ? group = 'HLS_ORG_AUTH' : group = 'HLS_ORG_NAUTH'
      }
      let param = {
        master: {
          document_id: bp_id_tenant,
          document_table: 'HLS_BP_MASTER',
          tab_group: group,
        },
      }
      // vm.hlsPopup.showLoading('请稍候')
      vm.hlsHttp.post(url, param).then(function (res) {
        // vm.hlsPopup.hideLoading()
        console.log(res)
        vm.cddItemList = res.lists
        if (res.result === 'S') {
          let listTemp = [...res.lists]
          listTemp.forEach(item => {
            switch (item.cdd_item) {
              // case 'NP_ID_CARD_F': // 自然人身份证正面
              //   vm.idCardFrontCheck_id = item.check_id
              //   break
              // case 'LEGAL_ID_CARD_F': // 法人代表身份证正面
              //   vm.idCardFrontCheck_id = item.check_id
              //   break
              // case 'NP_ID_CARD_B': // 身份证背面
              //   vm.idCardBackCheck_id = item.check_id
              //   break
              // case 'LEGAL_ID_CARD_B': // 身份证背面
              //   vm.idCardBackCheck_id = item.check_id
              //   break
              // case 'HOUSE_CARD': // 房产证
              //   vm.house_id = item.check_id
              //   break
              // case 'CAR_CARD': // 行驶证
              //   vm.car_id = item.check_id
              //   break
              case 'ORG_CODE': // 营业执照
                vm.license_id = item.check_id
                break
              default:
            }
          })
          // 查询图片
          listTemp.forEach((item, index) => {
            vm.load_picture(item.check_id, index, item.cdd_item)
          })
        }
      })
    },
    load_picture (check_id, index, cdd_item) {
      let vm = this
      let url =
        process.env.basePath + 'attachment_list_query' + '&index' + index // 附件查询
      let param = {
        check_id: check_id,
      }
      hlsPopup.showLoading('请稍候')
      vm.$post(url, param).then(function (res) {
        vm.hlsPopup.hideLoading()
        if (res.result === 'S') {
          res.lists.forEach(item => {
            item['url'] =
              process.env.filePath +
              'attachment_id=' +
              item.attachment_id +
              '&access_token=' +
              window.localStorage.access_token
          })
          console.log('图片查询', res.lists)
          switch (cdd_item) {
            case 'NP_ID_CARD_F': // 自然人身份证正面
              if (!vm.idCardFrontUrlFlag) {
                vm.idCardFront = res.lists[0].url
              }
              // vm.idCardFrontAttachmentId = res.lists[0].attachment_id
              break
            case 'LEGAL_ID_CARD_F': // 身份证正面
              if (!vm.idCardFrontUrlFlag) {
                vm.idCardFront = res.lists[0].url
              }
              // vm.idCardFrontAttachmentId = res.lists[0].attachment_id
              break
            case 'NP_ID_CARD_B': // 承租人身份证背面
              if (!vm.idCardBackUrlFlag) {
                vm.idCardBack = res.lists[0].url
              }
              // vm.idCardBackAttachmentId = res.lists[0].attachment_id
              break
            case 'LEGAL_ID_CARD_B': // 承租人身份证背面
              if (!vm.idCardBackUrlFlag) {
                vm.idCardBack = res.lists[0].url
              }
              // vm.idCardBackAttachmentId = res.lists[0].attachment_id
              break
            case 'HOUSE_CARD': // 房产证
              if (!vm.houseFlag) {
                vm.houseImg = res.lists[0].url
              }
              // vm.house_id = res.lists[0].attachment_id
              break
            case 'CAR_CARD': // 房产证
              if (!vm.carFlag) {
                vm.carImg = res.lists[0].url
              }
              // vm.house_id = res.lists[0].attachment_id
              break
            case 'ORG_CODE': // 营业执照
              if (!vm.licenseFlag) {
                vm.licenseImg = res.lists[0].url
              }
              // vm.house_id = res.lists[0].attachment_id
              break
            default:
          }
        } else {
          hlsPopup.showLongCenter(res.message)
        }
      })
    },
    // 保存
    handSave () {
      hlsPopup.showLongCenter('保存成功！')
    },
    isSubmit () {
      let vm = this
      this.hlsPopup.showConfirm({
        title: '提示',
        content: '您确定提交吗？',
        onConfirm: data => {
          if (data === 1) {
            this.handleSubmit()
          }
        },
      })
    },
    // 项目提交审批
    handleSubmit () {
      let vm = this
      let url = process.env.basePath + 'prj_project_submit'
      let param = {
        project_id: window.localStorage.project_id,
        phone: window.localStorage.getItem('user_phone'),
      }
      vm.hlsPopup.showLoading('请稍候')
      vm.hlsHttp.post(url, param).then(function (res) {
        // vm.hlsPopup.hideLoading()
        if (res.result === 'S') {
          vm.hlsPopup.showSuccess('提交成功')
          vm.$router.push({
            name: 'MyInfo',
          })
        } else {
          vm.hlsPopup.showLongCenter(res.message)
        }
      })
    },
  },
}
</script>
<style lang="less" >
#create-enclosure-info {
  .swipeout-list .item .function {
    height: 68px;
    background: url("../../assets/contractCreate/delete.png") 45% 45% #fde5e8
      no-repeat;
    background-size: 20px 20px;
  }
  .hls-list-item {
    margin-bottom: 0px !important;
  }
  .swipeout-list {
    padding: 0px;
  }
  .h-header-right {
    display: flex;
    align-items: center;
  }
  .flow {
    z-index: 999;
  }
  .left-icon {
    width: 18px;
    height: 18px;
    text-align: center;
    line-height: 18px;
    background-color: rgba(29, 63, 255, 0.2);
    color: @headerColor;
    border-radius: 4px;
  }
  input::placeholder {
    color: #b4b4b5;
  }
  .top {
    width: 100%;
    height: 81px;
    background-color: #faf5e0;
    display: flex;
    justify-content: center;
    align-items: center;
    .line {
      display: inline-block;
      width: 78px;
      border-top: 1px solid #a4a4a4;
      margin-bottom: 18px;
    }
    .line {
      border-top: 1px solid #ffa000;
    }
    .item {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-flow: column wrap;
      font-family: PingFangSC-Semibold;
      font-size: 12px;
      color: rgba(56, 63, 69, 0.5);
      letter-spacing: 0.43px;
      img {
        width: 18px;
      }
      span {
        display: block;
        text-align: center;
        line-height: 18px;
        border-radius: 50%;
        width: 18px;
        height: 18px;
        color: #fff;
        background: #a4a4a4;
      }
      p {
        margin-top: 10px;
      }
    }
    .item:nth-of-type(3) {
      font-family: PingFangSC-Semibold;
      font-size: 12px;
      color: rgb(56, 63, 69);
      letter-spacing: 0.43px;
      span {
        background-color: #ffa000;
      }
    }
  }
  .userInfo {
    height: 40px;
    line-height: 40px;
    color: @headerColor;
    // margin-top: -10px;
    font-size: 15px;
    margin-left: 16px;
    position: relative;
  }
  .userInfo::before {
    content: "";
    display: block;
    width: 4px;
    height: 20px;
    background-color: @headerColor;
    position: absolute;
    left: -15px;
    top: 12px;
  }
  .add-box {
    .before {
      border: 1px solid #fdb62f;
      border-radius: 4px;
      color: #fdb62f;
    }
    .next {
      background: #1d3fff;
      border-radius: 4px;
      color: #fff;
    }
  }
  .titles {
    color: #656464;
        margin-left: 16px;
        padding-top: 16px;
        font-size: 13px;
  }
  .house {
    background: #fff;
    margin-top: 10px;
    padding-bottom: 10px;
    .plus {
          display: flex;
          justify-content: center;
          align-items: center;
        }
    .card-upload {
          position: relative;
          width: 80px;
          height: 80px;
          border: 1px dashed #dcdcdd;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-top: 12px;
          margin-left: 16px;
          //float: left;

          .close {
            /* position: relative;
             color: #F96F68;
             margin-top: -100%;
             margin-left: -10%;*/
            position: absolute;
            color: #F96F68;
            top: -6px;
            right: -6px;

            img {
              width: 14px;
              height: 14px;
            }
          }

          img {
            /*width: 88px;
            height: 88px;*/
            width: 100%;
            height: 100%;
          }

          .upload-btn {
            width: 24px;
            height: 24px;
          }
        }
  }
  .house:last-child {
    margin-top: 0;
    div {
      float: left;
    }
  }

  .upload-box {
        display: flex;
        justify-content: center;
        margin-top: 15px;
        div {
          width: 172px;
          height: 120px;
          border: 1px dashed #dcdcdd;
          text-align: center;
          font-size: 14px;
          color: #b4b4b5;
          .front,
          .back {
            width: 172px;
            height: 120px;
          }
        }
        div:nth-of-type(2) {
          margin-left: 7px;
        }
        img {
          margin-top: 32px;
          width: 58px;
          height: 45px;
        }
        p {
          margin-top: 12px;
          font-size: 13px;
        }
      }
}
</style>
