<template>
  <div class="record-detail">
    <nav-bar></nav-bar>
    <div class="page-container">
      <!--   基本信息   -->
      <div class="card">
        <van-panel >
            <template #header>
              <span></span>
            </template>
          <div class="panel-box">
            <van-cell title="来访人员" :value="selectedUser.userName"></van-cell>
            <van-cell title="介绍信类型" :value="getDictLabel(selectedUser.letterType,'out_in_type')"></van-cell>
            <van-cell title="来访事由" :value="selectedUser.letterReasons"></van-cell>
            <van-cell title="来访单位" :value="selectedUser.companyName"></van-cell>
            <van-cell title="证件类型" :value="getDictLabel(selectedUser.idType,'letter_id_type')"></van-cell>
            <van-cell title="证件号码" :value="selectedUser.idCard"></van-cell>
            <div class="upload-box" v-if="selectedUser.imgFile && selectedUser.imgFile.length > 0">
              <span>证件图片</span>
              <van-cell >
                <div
                  class="nfc-img van-hairline--surround"
                  v-for="(v, i) in selectedUser.imgFile"
                  :key="v"
                  @click="preView(selectedUser.imgFile)">
                  <img :src="imgUrl(v)" alt="" />
                </div>
              </van-cell>
            </div>

            <div class="upload-box" v-if="selectedUser.letterFile && selectedUser.letterFile.length > 0">
              <span>介绍信附件</span>
              <van-cell >
                <div
                  class="nfc-img van-hairline--surround"
                  v-for="(v, i) in selectedUser.letterFile"
                  :key="v"
                  @click="preView(selectedUser.letterFile)">
                  <img :src="imgUrl(v)" alt="" />
                </div>
              </van-cell>
            </div>

            <div class="upload-box" v-if="selectedUser.checkImage && selectedUser.checkImage.length > 0">
              <span>核验结果</span>
              <van-cell >
                <div
                  class="nfc-img van-hairline--surround"
                  v-for="(v, i) in selectedUser.checkImage"
                  :key="v"
                  @click="preView(selectedUser.checkImage)">
                  <img :src="imgUrl(v)" alt="" />
                </div>
              </van-cell>
            </div>
            <div class="upload-box" v-if="canRecord() && !selectedUser.departureTime && !selectedUser.checkImage">
              <span class="required">核验结果</span>
              <van-cell>
                <uploader :maxCount="2" v-model="formData.checkImage"/>
              </van-cell>
            </div>
            <van-cell v-if="selectedUser.accompanyingPerson" title="陪同人员" :value="selectedUser.accompanyingPerson"></van-cell>
            <!-- <date-cell v-if="selectedUser.approveStatus==1 && !selectedUser.accompanyingPerson" required title="到达时间" :max-date="maxData" :min-date='minDate' :is-row="true"  v-model="formData.arrivalTime" date-type="datetime" /> -->
            <van-field
              v-if="canRecord() && !selectedUser.accompanyingPerson"
              v-model="formData.accompanyingPerson"
              rows="1"
              autosize
              required
              :maxlength="200"
              placeholder="请输入陪同人员姓名"
              label="陪同人员"></van-field>
            <van-cell title="到达时间" v-if="selectedUser.arrivalTime" :value="dayjs(selectedUser.arrivalTime).format('YYYY-MM-DD HH:mm')"></van-cell>
            <van-cell title="离开时间" v-if="selectedUser.departureTime" :value="dayjs(selectedUser.departureTime).format('YYYY-MM-DD HH:mm')"></van-cell>
            <div class="upload-box" v-if="selectedUser.submitSign">
              <span>登记签名</span>
              <van-cell >
                <div
                  class="nfc-img van-hairline--surround"
                  :key="selectedUser.submitSign"
                  @click="preView(selectedUser.submitSign)">
                  <img :src="imgUrl(selectedUser.submitSign)" alt="" />
                </div>
              </van-cell>
            </div>
            <date-cell v-if="canRecord() && !selectedUser.arrivalTime" required title="到达时间" :max-date="maxData" :min-date='minDate' :is-row="true"  v-model="formData.arrivalTime" date-type="datetime" />
            <date-cell v-if="canRecord() && selectedUser.arrivalTime && !selectedUser.departureTime" required title="离开时间" :max-date="maxData" :min-date='minDate' :is-row="true"  v-model="formData.departureTime" date-type="datetime" />
          </div>

          <van-action-sheet v-model="showSign" title="签名" class="sheet">
            <writingPad ref="esign" :old-signature-seal="oldSignatureSeal" @resultImg="resultImg" @cancelSign="cancelSign"></writingPad>
          </van-action-sheet>
          <div v-if="canRecord() &&!selectedUser.departureTime" class="big-btn-box" >
            <van-button  type="info" size="large" @click="onSubmit">确认登记</van-button>
          </div>
        </van-panel>
        <van-dialog v-model="confirmShow" title="引入签名" show-cancel-button @confirm="confirmSignImg">
          <van-image :src="this_window + oldSignatureSeal" />
        </van-dialog>
      </div>

    </div>
  </div>
</template>

<script>

import DateCell from "@/components/dateCell/index.vue";
import Uploader from "@/components/upload/gxuploader.vue";
import {formatDate} from "@/filters/filter";
import {mapGetters} from "vuex";
import {imgUrl} from "@/utils";
import { ImagePreview } from 'vant'
import writingPad from '@/components/writingPad/index.vue'
import imgCom from '@/components/imgCom/index.vue'
import { base64ToBlob } from '@/utils/base64TurnImg.js'
import { upload } from '@/api/public'
import {userDetails, userDepart} from './api'
import dayjs from 'dayjs'
import { compatibleWithIOSStringToDate } from '@/utils/date.js'
export default {
  components: {Uploader, DateCell,writingPad,imgCom},
  data(){
    return {
      maxData:new Date(),
      minDate:null,
      visitId:null,
      userList:[],
      selectedUser:{},
      showSign:false,
      prop:{
        label:'userName',
        value:'id'
      },
      formData:{
        arrivalTime:null,
        departureTime:null,
        checkImage:null,
        accompanyingPerson:null,
      },
      dicts:['out_in_approve_status','out_in_type','letter_id_type'],
      oldSignatureSeal:"",
      confirmShow:false,
      this_window: process.env.NODE_ENV === 'development' ? '/dev' : window.origin,
    }
  },
  computed:{
    ...mapGetters(['orgId','id','dictionary']),
  },
  created(){
    this.visitId = this.$route.query.id;
    this.getUserInfo();
  },
  mounted() {
    this.oldSignatureSeal = JSON.parse(window.sessionStorage.getItem('SET_MASTER_SIGNATURE_SEAL')) + '';
  },
  methods:{
    dayjs,
    imgUrl,formatDate,
    canRecord(){
      return this.selectedUser.approveStatus==1 && this.selectedUser.status!=3
    },
    onSubmit(){
      let {arrivalTime,departureTime,accompanyingPerson,checkImage} = this.formData;
      if(!this.selectedUser.checkImage && !checkImage){
        this.$toast('请上传审核结果');
        return
      }

      if(!this.selectedUser.accompanyingPerson && !accompanyingPerson){
        this.$toast('请输入陪同人员姓名');
        return
      }

      if(!this.selectedUser.arrivalTime && !arrivalTime){
        this.$toast('请选择到达时间');
        return
      }

      if(this.selectedUser.arrivalTime && !this.selectedUser.departureTime && !departureTime){
        this.$toast('请选择离开时间');
        return
      }

      if(departureTime){
        this.signatureHandler();
      }
      else{
        this.submitRecordData(arrivalTime,departureTime,accompanyingPerson,checkImage);
      }
    },
    submitRecordData(arrivalTime,departureTime,accompanyingPerson,checkImage,signImgUrl)
    {
        let data = {
          id:this.selectedUser.id,
          // accompanyingPerson:this.selectedUser.accompanyingPerson?this.selectedUser.accompanyingPerson:accompanyingPerson,
          // arrivalTime: this.selectedUser.arrivalTime ? this.selectedUser.arrivalTime:arrivalTime,
          // departureTime,
        }
        if(arrivalTime)
        {
          data.arrivalTime=arrivalTime;
        }
        if(departureTime)
        {
          data.departureTime=departureTime;
        }
        if(accompanyingPerson)
        {
          data.accompanyingPerson=accompanyingPerson;
        }
        if(checkImage)
        {
          data.checkImage=checkImage.map(v=>{return v.imgPath}).toString(',');
        }
        if(signImgUrl)
        {
          data.submitSign=signImgUrl;
        }
        //alert(JSON.stringify(data))
        userDepart(data).then(res=>{
          this.$toast.success('提交成功');
          this.$router.replace({
            name:'visitRecord',
            path:'/visitRecord',
            params:{event:'refresh'},
          });
        })
    },
    signatureHandler() {
      this.showSign = true
    },
    cancelSign()
    {
      this.showSign=false;
    },
    confirmSignImg(){
      this.cancelSign();
      //this.submitSign(this.oldSignatureSeal);
      let {arrivalTime,departureTime,accompanyingPerson,checkImage} = this.formData;
      let signImgUrl = this.oldSignatureSeal;
      this.submitRecordData(arrivalTime,departureTime,accompanyingPerson,checkImage,signImgUrl);
    },
    //上传签名图到服务器
    resultImg(img,oldImgUrl) {
      if (oldImgUrl !== "" && oldImgUrl !== null && oldImgUrl !== "null"){
        //this.submitSign(oldImgUrl)
        this.confirmShow =true;
        this.oldSignatureSeal = oldImgUrl;
      }else {
        let obj = base64ToBlob(img)
        let formData = new FormData()

        obj.name = '签名.jpg'
        formData.append('file', base64ToBlob(img))

        upload(formData, 'image')
          .then(res => {
            console.log(process.env.NODE_ENV)
            /*上传成功*/
            let signImgUrl = process.env.NODE_ENV === 'development' ? res.data.url : res.data.url
            // this.submitSign(imgUrl)
            let {arrivalTime,departureTime,accompanyingPerson,checkImage} = this.formData;
            this.submitRecordData(arrivalTime,departureTime,accompanyingPerson,checkImage,signImgUrl);
            // this.$emit("imgUrl", res.data.url);
          })
          .catch(err => {
            /*上传失败*/
          })
      }
    },
    getUserInfo(){
      userDetails(this.visitId).then(res=>{

        let checkImage = "";
        if(res.data.checkImage)
        {
          checkImage= res.data.checkImage.split(',')
        }
        let imgFile = res.data.imgFile.split(',');
        let letterFile = [];
        if(res.data.letterFile && res.data.letterFile.length > 0){
            letterFile = res.data.letterFile.map(v=>{
              let data = JSON.parse(v);
            return data.imgPath;
          })
        }
        this.selectedUser = res.data;
        this.selectedUser.checkImage = checkImage;
        this.selectedUser.imgFile = imgFile;
        this.selectedUser.letterFile = letterFile;
        //设置最小时间
        let minDate = this.selectedUser.arrivalTime;

        // this.minDate = compatibleWithIOSStringToDate(this.selectedUser.arrivalTime)
        if(minDate)
        {
          this.minDate = new Date(this.dayjs(minDate));
          // this.minDate = new Date(minDate)
          // // 苹果手机下 某些版本 new Date(minDate) 对格式有严格要求
          // if(!this.minDate){
          //   let objStart=minDate.replace(/-/g,"/");
          //   this.minDate = Date.parse(new Date(objStart));
          //   console.log("111",this.minDate)
          // }

          // let objStart=minDate.replace(/-/g,"/");
          // console.log("111",objStart,new Date(minDate))
          // this.minDate = Date.parse(new Date(objStart));
          // console.log("1112",this.minDate)
        }
        else{
          this.minDate = new Date(null);
        }
      })
    },
    previewFile(file){
      this.openFilePreview(file);
    },
    preView(val) {
      if(Array.isArray(val)){
        let arr = val.map(v=>{
          return imgUrl(v);
        })
        ImagePreview(arr);
      }else {
        ImagePreview([imgUrl(val)]);
      }
    },
  }
}
</script>
<style lang="scss">
.record-detail{
  .van-card{
    padding: 20px;
  }
  .card-cell-box{
    width: 70%;
    .van-cell{
      padding: 10px;
      &::after{
        left:10px;
        right:10px;
      }
    }
    .van-cell__title{
      flex:.25;
    }
    .van-cell__value{
      flex:.75;
    }
  }
}
</style>
<style scoped lang="scss">
.record-detail{
  height: 100%;
  overflow: hidden;
}
.page-container{
  height: calc(100vh - 94px);
  overflow: auto;
  padding: 20px;

}
.flex-box{
  display: flex;
  justify-content: space-between;
  align-items: center;
  >span{
    margin: 0 20px;
  }
}
.card{
  margin-bottom: 20px;
  box-shadow: 0 10px 10px #eaeaea;
}
.card:last-child{
  margin-bottom: 0;
}
.panel-box{
  -padding:0 20px;
}
.panel-box-item{
  height: 36px;
  line-height: 36px;
}
.item-label{
  width: 100%;
  display: flex;
  justify-content: right;
  align-items: center;
}
.item-value{
  width: 100%;
  display: flex;
  justify-content: left;
  align-items: center;
}
.upload-box{
  padding: 20px 30px;
  display: flex;
  >span{
    display: inline-block;
    height: 160px;
    width: 200px;
    line-height: 160px;
    font-size: 28px;
    color:#999;
    >i{
      font-style: normal;
      color: #ee0a24;
    }
  }
  .required::before{
    content: '*';
    color: #ee0a24;
    position: absolute;
    left: 14px;
  }
}
.goods-card{
  width: 100%;
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  .card-img-box{
    width: 200px;
    height: 200px;
    margin-right: 10px;
    >img{
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 10px;
    }
  }
}
.big-btn-box{
  padding: 20px;
}
.file-box{
  width: 70%;
  display: flex;
  justify-content: flex-end;
  color:#008cd6;
}
.nfc-img {
  display: inline-block;
  width: 140px;
  height: 140px;
  margin: 0 10px;
  position: relative;
  > img {
    width: 100%;
    height: 100%;
    border: none;
  }
  > span {
    position: absolute;
    padding: 0 10px;
    bottom: 0;
    left: 0;
    display: block;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.2);
    color: #eaeaea;
    font-size: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 30px;
    height: 30px;
  }
}
.sheet {
  height: 45%;
}
</style>
