<template>
  <div class="app-container">
    <van-sticky style="position:relative;">
      <div class="bannerBg">
        <van-nav-bar
          style="background:transparent;border-bottom-width:0;margin-bottom:.5rem;"
          @click-left="goBack()"
          right-text ="首页"
          @click-right="goRightBack()"
        >
          <template #left>
            <van-icon name="arrow-left" size="18" color="#fff" />
          </template>
          <!-- <template #right>
          <van-icon name="map-marked" size="18" color="#fff" />
        </template>-->
          <template #title>
            <p style="color:#fff">入户调查</p>
          </template>
        </van-nav-bar>
      </div>
      <div style="width:95%;left:2.5%;position:absolute;background:#fff;border-radius:15px;box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.16);padding: .3rem;top:1.2rem">
        <van-row>
          <van-col span="4" :offset="1" style="text-align:center;" @click="$router.push({path:'/homesteadSurvey/add'})">
            <van-icon :name="require('../../assets/images/housesteadSurvey/zjd'+(active==1?'A':'D')+'.png')" size="1rem" style="margin-top:0px;"/>
            <p :style="{color:(active==1?'rgb(34, 183, 242)':'#000')}">宅基地</p>
          </van-col>
          <van-col span="2">
            <div style="border-top: 2px dashed #b5b4b4;margin-top: 20px;"></div>
          </van-col>
          <van-col span="4"  style="text-align:center;" @click="$router.push({path:'/homesteadSurvey/add2'})" >
            <van-icon :name="require('../../assets/images/housesteadSurvey/nhxx'+(active==2?'A':'D')+'.png')" size="1rem" style="margin-top:0px;"/>
            <p :style="{color:(active==2?'rgb(34, 183, 242)':'#000')}">使用权人</p>
          </van-col>
          <van-col span="2">
            <div style="border-top: 2px dashed #b5b4b4;margin-top: 20px;"></div>
          </van-col>
          <van-col span="4" style="text-align:center;" @click="$router.push({path:'/homesteadSurvey/add3'})" >
            <van-icon :name="require('../../assets/images/housesteadSurvey/fwxx'+(active==3?'A':'D')+'.png')" size="1rem" style="margin-top:0px;"/>
            <p  :style="{color:(active==3?'rgb(34, 183, 242)':'#000')}">房屋</p>
          </van-col>
          <van-col span="2">
            <div style="border-top: 2px dashed #b5b4b4;margin-top: 20px;"></div>
          </van-col>
          <van-col span="4" style="text-align:center;" @click="$router.push({path:'/homesteadSurvey/add4'})">
            <van-icon :name="require('../../assets/images/housesteadSurvey/fsss'+(active==4?'A':'D')+'.png')" size="1rem" style="margin-top:0px;"/>
            <p :style="{color:(active==4?'rgb(34, 183, 242)':'#000')}">附属物</p>
          </van-col>
        </van-row>
      </div>
    </van-sticky>
    <div style="margin:1.6rem auto 0;width: 95%;">
      <p class="title" style="position:relative;padding-left:10px;line-height:20px;font-size: 16px;margin-bottom: 5px;">自然幢</p>
    </div>
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      :immediate-check="false"
      @load="onRefreshZrz"
    >
      <van-swipe-cell v-for="(item,index) in zrzlist" :key="'zrz'+index" style="border-radius: 16px;box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.16); width:95%;margin:15px auto 0;background:#fff;">
        <div style="padding:15px;">
          <p style="display: flex;align-items: center;">
            <img src="../../assets/images/housesteadSurvey/add03.png" alt="" style="margin-right: 5px;">
            <span style="line-height: 1;font-size: 16px;">第{{index+1}}号</span>
          </p>
          <div style="display:flex;line-height:20px;margin-top: 15px;font-size: 14px;color: #999999;">
            <p style="flex:1;text-align:left;">自然幢号:</p>
            <p  style="flex:1;text-align:right;">{{item.zrzh}}</p>
          </div>
          <div style="display:flex;line-height:20px;margin-top: 5px;font-size: 14px;color: #999999;">
            <p style="flex:1;text-align:left;">总层数:</p>
            <p style="flex:1;text-align:right;">{{item.zcs}}</p>
          </div>
          <div style="text-align:center;overflow:auto;display: flex;justify-content: space-between;margin-top: 10px;">
            <p style="width:49%;display: flex;align-items: center;justify-content:center;border: 1px solid #22B7F2;padding: 3px 0;border-radius: 50px;" @click="showPopupzrz(item)">
              <img src="../../assets/images/housesteadSurvey/add02.png" alt="">
              <span style="font-size: 14px;color: #22B7F2;margin-left: 5px;">自然幢信息</span>
            </p>
            <p style="width:49%;display: flex;align-items: center;justify-content:center;border: 1px solid #22B7F2;padding: 3px 0;border-radius: 50px;" @click="shownmfwlist(item)">
              <img src="../../assets/images/housesteadSurvey/add02.png" alt="">
              <span style="font-size: 14px;color: #22B7F2;margin-left: 5px;">房屋列表</span>
            </p>
          </div>
        </div>
        <template #right>
          <van-row>
            <van-col>
              <van-button  square type="info" class="delete-button" style="position: relative;" @click="showUploadList(item.id)"><van-icon style="bottom: -3px;"  name="photo-o" size=".4rem" color="#FFFFFF"/>附件</van-button>
            </van-col>
            <van-col>
              <van-button  v-if="permission == 'true'" square  type="danger" class="delete-button" @click="deletezrz(item)"><img width="10px" src="../../assets/images/sunVillage_info/list_icon_7.png" alt="">删除</van-button>
            </van-col>
          </van-row>
        </template>
      </van-swipe-cell>
    </van-list>
      <div  v-if="permission == 'true'" style=" width:95%;margin:20px auto;display: flex;justify-content: center;">
        <div style="width:100%;text-align:center;overflow:auto;border-radius: 16px;box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.16);padding: 15px 0px;background: #ffffff;color: #22B7F2;">
          <p style="font-size: 16px;" @click="showPopupAddzrz()">+ 添加自然幢信息</p>
        </div>
      </div>
    <van-popup v-model:show="showImageList" position="bottom" style="height:40vh;padding:50px 10px 0" closeable
               close-icon="close">
      <p style="color:#000;position:absolute;top:0.426667rem;left:0.426667rem">图片上传</p>
      <div style="width:100%;height:calc( 40vh - 100px);overflow-y: scroll;">

        <van-uploader accept="image/*" v-model="uploadImgList" :after-read="beforeReadImageList" @delete="deleteFileImageList" multiple :max-count="50"  />
      </div>
      <van-row justify="space-around" style=" position:fixed;bottom:0;left:0;width:100%;height:50px;text-align: center;">
        <van-col span="12"><van-button type="primary" style="width:100px;" round  @click="qkClick">清空</van-button></van-col>
        <van-col span="12"><van-button type="primary" style="width:100px;" round  @click="submitUploadList(zjdId)">上传</van-button></van-col>
      </van-row>
    </van-popup>
    </div>
</template>

<script>
import MapGisDrawing from "@/components/Map/MapGisDrawing";
import {uploadFile} from "@/api/homesteadSurvey/zjdzd";
import {listZrz,delZrz} from "@/api/homesteadSurvey/zrz";
import {attachmentFind} from "@/api/sunVillage_info/homestead/application";
import {systemAttachment} from "@/api/onlineHome/bankAgriculture/paymentApproval";
import {base64Attach} from "@/api/user";
import { Notify, Dialog, Toast } from 'vant';
import axios from "axios";
export default {
  name: "homesteadAdd",
  components: { MapGisDrawing,},
  data() {
    return {
      active:3,
      loading:false,
      finished:false,
      permission:false,
      showImageList:false,
      zjdId:null,
      uploadImgList:[],
      uploadImgList1:[],
      countyhc:1,
      zjdzdxx:{},
      zrzlist:[]
    };
  },
  created(){
    this.zjdzdxx = JSON.parse(localStorage.getItem("zjdzdxxItem"));
    this.permission = localStorage.getItem("executePermission");
    if(this.zjdzdxx.zjddm != null ){
      this.getList();
    }
  },
  mounted(){

  },
  methods: {
    getList(){
      let params = {
        zjddm:this.zjdzdxx.zjddm,
        pageNum: 1,
        pageSize:10,
      }
      listZrz(params).then(response => {
        this.zrzlist = response.rows;
        if(response.rows.length>0&&response.rows.length<response.total){
          this.countyhc++
          this.loading = false
        }else{
          this.loading = false
          this.finished = true
        }
      });
    },
    goBack(){
      if(this.ztMap && this.enterMap ==1){
        if(this.form.id == null){
          this.backMap.backMapZjdAData.theGeom= "";
        }else{
          this.backMap.backMapZjdAData = this.form;
        }
        this.$cookies.set("search",this.backMap);
      } else {
        this.$cookies.set("search","");
      }
      this.$router.push({name: this.$router.back(-1)});
      // }
    },
    onRefreshZrz(){
      if(this.loading){
        let params = {
          "zjddm":this.zjdzdxx.zjddm,
          "pageNum": this.countyhc+1,
          "pageSize":10,
        }
        listZrz(params).then(response => {
          if(response.rows.length>0&&this.zrzlist.length<response.total){
            response.rows.map(res => {
              this.zrzlist.push(res)
            })
            this.countyhc++
            this.loading = false
          }else{
            this.loading = false
            this.finished = true
          }
        });
      }
    },
    getAttachments(id) {
      console.info(id);
      this.uploadImgList = [];
      let cond = {
        tableId: id,
        tableName: 't_homespace_zrz',
        fileType: 0,
      };
      attachmentFind(cond).then(resp => {
        this.uploadImgList = resp.data.map(function(item){
          return {id:item.id,url:'/api'+item.fileUrl,isImage: true}
        });
      });
    },
    deleteFileImageList(file){
      if(file.id !== undefined ){
        systemAttachment(file.id);
      }
    },
    // 图片上传前
    beforeReadImageList(file){
      let _this = this;
      if(file.length!=undefined){
        file.map(res => {
          let zjddm = res.file.name
          //zjddm=zjddm.substring(0,zjddm.lastIndexOf("\("));
          // 创建Canvas对象(画布)
          let canvas =  document.createElement('canvas')
          // 获取对应的CanvasRenderingContext2D对象(画笔)
          let context = canvas.getContext('2d')
          // 创建新的图片对象
          let img = new Image()
          // 指定图片的DataURL(图片的base64编码数据)
          img.src = res.content
          // 监听浏览器加载图片完成，然后进行进行绘制
          img.onload = () => {
            /*const h = img.height
            const w = img.width*/
            let ch = img.height/5
            let cw = img.width/5
            let canvas = document.createElement('canvas')
            let ctx = canvas.getContext('2d')
            canvas.height = ch
            canvas.width = cw
            ctx.clearRect(0,0,cw,ch)
            ctx.drawImage(img,0,0,cw,ch)
            let base_img = canvas.toDataURL('image/jpeg')
            let blobBin = atob(base_img.split(',')[1])
            let d = []
            for (let i=0;i<blobBin.length;i++){
              d.push(blobBin.charCodeAt(i))
            }
            let data2 = new FormData();
            data2.append("file", new Blob([new Uint8Array(d)],{type:'image/jpeg'}));
            uploadFile(data2);
          }
        })
      }else{
        let zjddm = file.file.name
        //zjddm=zjddm.substring(0,zjddm.lastIndexOf("\("));
        // 创建Canvas对象(画布)
        let canvas =  document.createElement('canvas')
        // 获取对应的CanvasRenderingContext2D对象(画笔)
        let context = canvas.getContext('2d')
        // 创建新的图片对象
        let img = new Image()
        // 指定图片的DataURL(图片的base64编码数据)
        img.src = file.content
        // 监听浏览器加载图片完成，然后进行进行绘制
        img.onload = () => {
          /*const h = img.height
          const w = img.width*/
          let ch = img.height/5
          let cw = img.width/5
          let canvas = document.createElement('canvas')
          let ctx = canvas.getContext('2d')
          canvas.height = ch
          canvas.width = cw
          ctx.clearRect(0,0,cw,ch)
          ctx.drawImage(img,0,0,cw,ch)
          let base_img = canvas.toDataURL('image/jpeg')
          let blobBin = atob(base_img.split(',')[1])
          let d = []
          for (let i=0;i<blobBin.length;i++){
            d.push(blobBin.charCodeAt(i))
          }
          let data2 = new FormData();
          data2.append("file", new Blob([new Uint8Array(d)],{type:'image/jpeg'}));
          uploadFile(data2);
        }
      }

    },
    qkClick(){
      this.uploadImgList1 = this.uploadImgList;
      for(let i = 0; i < this.uploadImgList1.length; i++){
        if(this.uploadImgList[i].id !== undefined ){
          systemAttachment(this.uploadImgList[i].id);
        }
      }
      this.uploadImgList = [];
    },
    submitUploadList(val){
      let f = []
      for (let i of this.uploadImgList){
        if(i.content !== undefined){
          f.push(i.content)
        }
      }
      if(f.length === 0){
        return this.$toast.fail("请上传照片");
      }
      this.$toast.loading({
        message: "数据处理中",
        forbidClick: true,
        duration: 10000000000,
      });
      let _this = this;
      let file = {
        tableId:val,
        tableName:"t_homespace_zrz",
        bizPath:"upload",
        fileType:"0",
        files: f
      };
      base64Attach(file).then((resp) => {
        this.$toast({
          icon: 'success', // 找到自己需要的图标
          message: '上传成功',
          duration:"1000",
          onClose:function(){
            _this.showImageList = false
          }
        })
      });
    },
    goRightBack(){
      this.$router.push({path:'/homesteadSurvey/list'});
    },
    showPopupzrz(val){
      this.$router.push({name:'zrzAdd',query:val});
    },
    showPopupAddzrz(){
      this.$router.push({name:'zrzAdd',query:{zjddm:this.zjdzdxx.zjddm,fwjg:"02",sjly:"04"}});
    },
    shownmfwlist(val){
      this.$router.push({name:'nmfwList',query:val});
    },
    showUploadList(id){
      this.getAttachments(id);
      this.showImageList = true;
      this.zjdId = id;
    },
    deletezrz(val){
      const ids = val.id || this.ids;
      Dialog.confirm({
        title: '系统提示',
        message: '是否确认删除自然幢号数据项?',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(function() {
          return delZrz(ids);
        }).then(() => {
        this.$notify({ type: 'success' , message: "删除成功" });
        location.reload(true);
      }).catch(() => {});
    },
  }
}
</script>

<style scoped>
>>> .bannerBg{
  width: 100%;
  color:#fff;
  padding:10px;
  background: linear-gradient(134deg,#7ac943 1%, #22b7f2);
}
>>> .van-hairline--bottom::after {
  border-bottom-width: 0;
}
>>> .title:before
{
  content:"";
  width: 6px;
  height: 20PX;
  background: #7ac943;
  border-radius: 3px;
  position:absolute;
  left:0;
  bottom:0;
}
>>> .delete-button {
  height: 100%;
}
>>> .van-row{
  height: 100%;
}
>>> .van-col{
  height: 100%;
}
>>> .van-swipe-cell__wrapper{
  margin-right:-3px;
}
>>> .label-class .van-collapse-item__title--expanded{
  font-weight: bold;
}
/deep/ .van-nav-bar__text {
  color: #fff;
}
</style>
