<template>
  <div class="visit-add">
    <nav-bar></nav-bar>
    <div class="page-container">
      <!--   基本信息   -->
      <div class="card">
        <van-panel >
          <template #header>
            <van-cell title="介绍信信息"></van-cell>
          </template>
          <div class="panel-box">
            <select-cell
              title="介绍信类型"
              is-row
              :prop="prop"
              v-model="visitType"
              :data-list="typeList"
              @change="changeType"
              required>
            </select-cell>
            <van-field
              label="介绍信编号"
              :required="visitType == 2"
              v-model="formData.letterNo"
              placeholder="请输入"
              :maxlength="15"/>
            <van-field
              label="出入事由"
              required
              rows="1"
              autosize
              type="textarea"
              v-model="formData.reasons"
              placeholder="请输入"
              show-word-limit
              :maxlength="100"/>
            <date-cell
              v-if="visitType=='2'"
              is-row
              :required="visitType == 2"
              v-model="formData.startTime"
              @change="startTimeChangedhandler"
              title="开始日期">
            </date-cell>
            <van-cell
              v-else
              is-row
              v-model="formData.startTime"
              title="开始日期">
            </van-cell>
            <date-cell
              v-if="visitType=='2'"
              is-row
              :required="visitType == 2"
              v-model="formData.endTime"
              @change="endTimeChangedhandler"
              title="截止日期">
            </date-cell>
            <van-cell v-else
              is-row
              v-model="formData.endTime"
              title="截止日期">
            </van-cell>
            <van-cell
              title="有效天数"
              :required="visitType == 2">
              <van-stepper :disabled="visitType == 3" @change="effectiveDaysChangedHandler" integer :min="1" v-model="formData.effectiveDays" step="1" />
            </van-cell>
<!--            <select-cell-->
<!--              :required="visitType == 2"-->
<!--              title="有效天数"-->
<!--              is-row-->
<!--              :label="formData.effectiveDays"-->
<!--              is-link-->
<!--              @click="showCalendar">-->
<!--            </select-cell>-->
            <div class="upload-box">
              <span :class="{'required':visitType == 2}">上传介绍信</span>
              <van-cell>
                <uploader :maxCount="5" v-model="formData.letterFile"/>
              </van-cell>
            </div>
            <van-field
              v-model="formData.description"
              rows="1"
              autosize
              :maxlength="200"
              label="备注信息"
              type="textarea"
              show-word-limit
              placeholder="请输入"/>
            <van-cell required title="添加人员">
              <template #right-icon>
                <div class="flex-box">
                  <van-button  type="info" size="mini" @click="openPicker">点击添加</van-button>
                </div>
              </template>
            </van-cell>
          </div>
        </van-panel>
      </div>

      <!--  人员列表   -->
      <div class="card" v-for="(v,i) in pList" :key="v.uuid">
        <van-swipe-cell>
          <div class="goods-card">
           <div class="card-img-box" @click="preView(v.imgFile)">
             <img :src="imgUrl(v.imgFile[0].imgPath)" alt="">
           </div>
           <div class="card-cell-box">
            <van-cell title="申请单位" :value="v.companyName"></van-cell>
            <van-cell title="出入人员" :value="v.userName"></van-cell>
            <van-cell title="证件类型" :value="getDictLabel(v.idType,'letter_id_type')"></van-cell>
            <van-cell title="证件号码" :value="v.idCard"></van-cell>
           </div>
          </div>
          <template #left>
            <van-button style="height: 100%;" square text="编辑" type="info" @click="editPerson(v,i)" class="delete-button" />
          </template>
          <template #right>
            <van-button style="height: 100%;" square text="删除" type="danger" @click="deletePerson(v,i)" class="delete-button" />
          </template>
        </van-swipe-cell>
      </div>

      <div class="big-btn-box" >
        <van-button  type="info" size="large" @click="onSubmit">保存</van-button>
      </div>
    </div>
<!--    <van-calendar-->
<!--      v-model="showCalendar"-->
<!--      :allow-same-day="true"-->
<!--      type="range"-->
<!--      :show-confirm="false"-->
<!--      @confirm="onConfirm"/>-->
    <calendar-picker ref="CalendarPicker" @change="getDate"></calendar-picker>
    <org-picker
      :show="showPicker"
      @cancel="cancelPicker"
      @confirm="changeOrg">
    </org-picker>

    <!-- 添加人员弹窗 -->
    <van-popup
        class="add-picker"
        v-model="showAddPicker"
        :close-on-click-overlay="false"
        position="top">


      <!--  添加人员信息    -->
      <div class="card" >
<!--        <van-cell title="人员信息">-->
<!--          <template #right-icon>-->
<!--            <van-button type="info" v-if="isAdd" icon="plus" size="mini" @click="onAdd">添加</van-button>-->
<!--            <van-button type="info" v-else icon="edit" size="mini" @click="onEdit">确认</van-button>-->
<!--          </template>-->
<!--        </van-cell>-->
        <div class="panel-box">
          <van-form validate-first @failed="onFailed">
            <van-field
                required
                v-model="personnel.companyName"
                rows="1"
                autosize
                :maxlength="20"
                label="申请单位"
                :rules="[{ pattern:/^(.+)$/, message: '请输入' }]"
                placeholder="请输入"/>
            <van-field
                required
                v-model="personnel.userName"
                rows="1"
                autosize
                :maxlength="20"
                label="出入人员"
                :rules="[{ pattern:/^(.+)$/, message: '请输入' }]"
                placeholder="请输入"/>
            <select-cell
                title="证件类型"
                is-row
                v-model="personnel.idType"
                :data-list="getDictItem('letter_id_type')"
                required>
            </select-cell>
            <van-field
                required
                v-model="personnel.idCard"
                rows="1"
                autosize
                :maxlength="20"
                label="证件号码"
                placeholder="请输入"/>
          </van-form>
          <div class="upload-box" >
            <span class="required">{{personnel.idType==0?'证件正反面':'上传证件照'}}</span>
            <van-cell>
              <uploader :maxCount="2" v-model="personnel.imgFile"/>
            </van-cell>
          </div>
          <p class="tip-text" >注：证件号码将作为唯一识别码</p>
        </div>

        <div class="header-line">
          <div class="cancel" @click="onCancel">取消</div>
<!--          <div class="title">添加人员</div>-->
          <div v-if="isAdd" class="sure" @click="onAdd">添加</div>
          <div v-else class="sure" @click="onEdit">确定</div>
        </div>

      </div>


    </van-popup>
  </div>
</template>

<script>

import SelectCell from "@/components/selectCell/index.vue";
import DateCell from "@/components/dateCell/index.vue";
import Uploader from "@/components/upload/gxuploader.vue";
import OrgPicker from "@/components/OrgPicker/index.vue";
import CalendarPicker from "@/components/CalendarPicker/index.vue";
import {formatDate} from "@/filters/filter";
import {mapGetters} from "vuex";
import {imgUrl} from "@/utils";
import { ImagePreview } from 'vant'
import {visitAdd} from './api'
import dayjs from "dayjs";
export default {
  components: {SelectCell,Uploader,DateCell,CalendarPicker,OrgPicker},
  data(){
    return {
      visitType:2,
      checked:false,
      visitInfo: {},
      formData:{
        receptionOrgIds:null,
        reasons:null,
        letterNo:null,
        letterFile:null,
        description:null,
        startTime:null,
        effectiveDays:null,
        endTime:null,
      },
      personnel:{
        companyName:null,
        userName:null,
        idCard:null,
        idType:null,
        imgFile:[],
      },
      pList:[],
      isAdd:true,
      showPicker:false,
      openCalendar:false,
      prop:{
        label:'name',
        value:'value'
      },
      typeList:[
        {
          name:'纸质',
          value:2
        },
        {
          name:'紧急',
          value:3
        }
      ],
      dicts:['letter_id_type'],
      showAddPicker:false,
    }
  },
  computed:{
    ...mapGetters(['orgId','id','dictionary'])
  },
  methods:{
    imgUrl,formatDate,
    onCancel() {
      this.showAddPicker = false;
    },
    onConfirm() {
      if(!this.selected.length){
        this.$toast('请选择')
        return;
      }
      this.showAddPicker = false;
    },
    openPicker(){
      this.showAddPicker = true;
    },
    changeType(){
      this.formData.startTime = dayjs(new Date()).format('YYYY-MM-DD');
      this.formData.effectiveDays = 1;
      this.formData.endTime = dayjs(new Date()).format('YYYY-MM-DD');
      // console.log("changeType",this.formData.endTime)
    },
    onSubmit(){
      // if(this.visitType ==  '1'){
      //   if(!this.formData.receptionOrgIds){
      //     this.$toast('请选择出入机构');
      //     return;
      //   }
      //   if(!this.formData.letterNo){
      //     this.$toast('请输入介绍信编号');
      //     return;
      //   }
      //   if(!this.formData.letterFile){
      //     this.$toast('请上传介绍信');
      //     return;
      //   }
      // }
      try{

        if (!this.visitType) {
          this.$toast('请选择介绍信类型');
          return;
        }
        if(this.visitType ==  '2') {
          if (!this.formData.letterNo) {
            this.$toast('请输入介绍信编号');
            return;
          }
          if (!this.formData.reasons) {
            this.$toast('请输入出入事由');
            return;
          }
          if (!this.formData.startTime) {
            this.$toast('请选择开始日期');
            return;
          }
          if (!this.formData.endTime) {
            this.$toast('请选择截止日期');
            return;
          }
          // if (!this.formData.startTime) {
          //   this.$toast('请选择有效天数');
          //   return;
          // }
          if (!this.formData.letterFile) {
            this.$toast('请上传介绍信');
            return;
          }
          if (this.pList.length == 0) {
            this.$toast('请添加人员信息');
            return;
          }
        }
        if(this.visitType ==  '3') {
          if (!this.formData.reasons) {
            this.$toast('请输入出入事由');
            return;
          }
          if (this.pList.length == 0) {
            this.$toast('请添加人员信息');
            return;
          }
        }
         const startDate = dayjs(this.formData.startTime);
        const endDate = dayjs(this.formData.endTime);
        if (startDate.isAfter(endDate)){
          this.$toast("开始日期不能大于截止日期！");
          return;
        }
        //判断介绍信是否过期
        // const inputDate = dayjs(this.formData.startTime);
        const newEndDate = endDate.endOf('day');
        const currentDate = dayjs();
        if (!newEndDate.isAfter(currentDate)){
          this.$toast("介绍信已过有效期，请重新选择有效起止日期或有效天数！");
          return;
        }

        this.formData.status = 1;
        this.formData.type = this.visitType;
        this.formData.receptionOrgIds = [this.orgId];
        this.formData.userInfos = JSON.parse(JSON.stringify(this.pList));
        let data = this.formData;
        if(this.formData.letterFile && this.formData.letterFile.length > 0){
          data.letterFile = this.formData.letterFile.map(v=>{
            return JSON.stringify(v);
          })
        }
        data.userInfos = this.pList.map(user=>{
          let urlArr = user.imgFile.map(v=>{
            return v.imgPath
          })
          user.imgFile = urlArr.join(',');
          return user
        })
        //alert(JSON.stringify(data));
        // return;
        visitAdd(data).then(res=>{
          this.$toast.success('保存成功');
          this.$router.replace({
            name:'visitRegister',
            path:'/visitRegister',
            params:{event:'refresh'},
          });
        })
      }catch (e) {
        alert(e)
      }
    },
    onFailed(errorInfo) {
      console.log('failed', errorInfo);
    },
    getDate(date){
      const [start, end] = date;
      this.formData.range = date;
      this.formData.date = `${start} ~ ${end}`;
    },
    showCalendar(){
      this.$refs.CalendarPicker.show = true;
    },
    editPerson(v,i){
      this.showAddPicker = true;
      this.isAdd = false;
      this.personnel = JSON.parse(JSON.stringify(v));
    },
    deletePerson(v,i){
      this.pList.splice(i,1);
    },
    onEdit(){
      if(!this.personnel.companyName || !this.personnel.userName || !this.personnel.idType || !this.personnel.idCard || !this.personnel.imgFile){
        this.$toast('请完善人员信息');
        return;
      }
      let strObj = JSON.parse(JSON.stringify(this.personnel));
      let index = this.pList.findIndex(v=>{return v.uuid === strObj.uuid});
      this.pList.splice(index,1,strObj);
      this.personnel = {
        companyName:null,
        userName:null,
        idType:null,
        idCard:null,
        imgFile:[],
      };
      this.isAdd = true;
      this.showAddPicker = false;
    },
    onAdd(){
      //测试模拟
      // if(!this.personnel.idCard){
      //   this.personnel.imgFile = [{
      //     url:'askjdkajsdjajkdsa',
      //     imgPath:'asjkdklaslkdasdlasld',
      //     name:'asdasdasd'
      //   },
      //     {
      //       url:'asdaaskjdkajsdjajkdsa',
      //       imgPath:'dsaasjkdklaslkdasdlasld',
      //       name:'asdasdasd'
      //     }
      //   ];
      //   this.personnel.userName = '张三';
      //   this.personnel.idCard = '123456789012345678'
      //   this.personnel.companyName = '测试单位';
      // }
      if(!this.personnel.companyName || !this.personnel.userName || !this.personnel.idType || !this.personnel.idCard || !this.personnel.imgFile){
        this.$toast('请完善人员信息');
        return;
      }
      let strObj = JSON.parse(JSON.stringify(this.personnel));
      //判断是否已添加
      let flag  = this.pList.some(v=> {return v.idCard === strObj.idCard});
      if(flag) {
        this.$toast('该人员信息已添加');
        return;
      };
      strObj.uuid = `${new Date().getTime()}`;
      this.pList.push(strObj);
      this.personnel = {
        companyName:null,
        userName:null,
        idType:null,
        idCard:null,
        imgFile:[],
      };
      this.showAddPicker = false;
    },
    showOrg(){
      this.showPicker = true;
    },
    changeOrg(selected){
      this.showPicker = false;
      this.formData.orgName = selected[0].text;
      this.formData.receptionOrgIds = [selected[0].id];
    },
    cancelPicker(){
      this.showPicker = false;
    },
    preView(val) {
      if(Array.isArray(val)){
        let arr = val.map(v=>{
          return imgUrl(v.imgPath);
        })
        ImagePreview(arr);
      }else {
        ImagePreview([imgUrl(val)]);
      }
    },
    endTimeChangedhandler()
    {
      console.log("endTimeChangedhandler")
      if(this.formData.startTime && this.formData.endTime)
      {
        this.formData.effectiveDays = dayjs(this.formData.endTime).diff(dayjs(this.formData.startTime), 'day')+1;
      }
    },
    startTimeChangedhandler()
    {
      console.log("startTimeChangedhandler")
      if(this.formData.startTime && this.formData.endTime)
      {
        this.formData.effectiveDays =  dayjs(this.formData.endTime).diff(dayjs(this.formData.startTime), 'day')+1;    
      }
    },
    effectiveDaysChangedHandler()
    {
      if(this.formData.startTime)
      {
        this.formData.endTime= dayjs(this.formData.startTime).add(this.formData.effectiveDays-1, 'day').format("YYYY-MM-DD");
      }
    }
  }
}
</script>
<style lang="scss">
.visit-add{
  .van-card{
    padding: 20px;
  }
  .card-cell-box{
    width: 70%;
    .van-cell{
      padding: 4px;
      &::after{
        left:10px;
        right:10px;
      }
    }
    .van-cell__title{
      flex:.25;
    }
    .van-cell__value{
     flex:.75;
    }
  }
}
</style>
<style scoped lang="scss">
.visit-add{
  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;
  background-color: #fff;
}
.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: 0 30px;
  display: flex;
  >span{
    display: inline-block;
    height: 160px;
    width: 200px;
    line-height: 160px;
    font-size: 28px;
    color:#999;
    position: relative;
  }
}
.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;
    }
  }
}
.tip-text{
  line-height: 60px;
  color:red;
  background-color: #fff;
}
.big-btn-box{
  padding-bottom: 20px;
}
.add-picker{
  .header-line {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 90px;
  }
  .header-line .cancel {
    padding: 0 30px;
    font-size: 28px;
    color: #969799;
  }
  .header-line .title {
    font-weight: 500;
    font-size: 30px;
    color: #343434;
  }
  .header-line .sure {
    padding: 0 30px;
    font-size: 28px;
    color: #1989fa;
  }
  .lists {
    padding: 10px 20px 20px 20px;
    min-height: 300px;
    max-height: 700px;
    overflow: auto;
    touch-action: pan-y;
  }
  .tip {
    color: #666;
    padding-bottom: 5px;
  }
  .van-empty{
    padding: 0;
  }
}
</style>
