<template><!--机房登记-->
  <div class="page-box">
    <group gutter="0" label-width="4.5em" label-margin-right="2em" label-align="right">
      <popup-picker title="选择事由" :data="reasonData" v-model="valueReason" @on-change="changeReason" value-text-align="right"></popup-picker>
      <popup-picker title="同行人数" :data="numberData" v-model="valueNumber" @on-change="changeNumber" value-text-align="right"></popup-picker>
      <x-textarea title="备注信息" v-model="saveInfo.remarks" placeholder="请填写备注信息" :rows="5"></x-textarea>
    </group>
    <div class="upload-box">

      <upload-pic></upload-pic>

      <!--<p>上传图片</p>-->
      <!--<div class="demo-upload-list" v-for="(item, index) in uploadList" :key="index">-->
      <!--<img :src="item.resPath" :alt="item.fName" />-->
      <!--<div class="remove-icon" @click="handleRemove(index)">-->
      <!--<Icon type="md-remove-circle" color="#FF0000" size="16" />-->
      <!--</div>-->
      <!--</div>-->
      <!--<Upload ref="upload" multiple type="drag" v-show="showUpload"-->
      <!--:show-upload-list="false" -->
      <!--:on-success="handleSuccess" -->
      <!--:format="['jpg','jpeg','png']" -->
      <!--:on-format-error="handleFormatError" -->
      <!--:before-upload="handleBeforeUpload" -->
      <!--action="/wuyecrm/rest/uploadFileInfo/uploadMutiFile" style="display: inline-block;width:68px;">-->
      <!--<div style="width: 68px;height:68px;line-height: 68px;">-->
      <!--<Icon type="ios-camera" size="21"></Icon>-->
      <!--</div>-->
      <!--</Upload>-->
    </div>
    <div class="submit-btn">
      <Button type="primary" long size="large" @click="uploadFile">提交</Button>
    </div>
  </div>
</template>

<script>
  import { Group, PopupPicker, XInput, XTextarea } from 'vux';
  import UploadPic from './../../components/UploadPicShen'
  import {
    findReasonsForEntryMachineRoom, //获取进入机房的缘由列表信息
    findByUserIdAndMachineRoomCode, //根据进入机房的用户UserId（userId）获取需要离场的详情信息
    saveMachineRoomAccessRecord,
    editMachineRoomAccessRecord,
    uploadFileByLocal
  } from './service/getData.js';
  import util from './../../util/util.js'
  import {formatDate} from './assets/js/date.js';
  export default {
    name: '',
    directives: {
    },
    components: {
      UploadPic,
      Group,
      PopupPicker,
      XInput,
      XTextarea
    },
    data () {
      return {
        isEdit: false, //是否编辑状态

        reasonList: [], //事由字典数据
        reasonData: [], //data -- 事由
        valueReason: [], //value -- 事由

        numberData: [], //data -- 人数
        valueNumber: [], //value -- 人数

        saveInfo: { //保存数据
          recordId: '', //添加保存无需传值，修改编辑必传
          machineRoomCode: '', //机房编号，必传(APP) sjsssjsgc09c10kdjf000001
          belongMachineRoom: '', //机房名称，必传(APP) 39层S2消防楼梯间1
          userId: localStorage.memberId, //用户ID，必传
          userName: localStorage.nickname, //用户名称，必传
          companyId: localStorage.companyId, //公司id，必填
          areaId: localStorage.areaId, //区域id，必填
          projectId: localStorage.projectId, //项目ID，必填
          entryTime: '', //进入时间
          leaveTime: '', //离开时间
          enterReason: '', //进入机房事由，必传
          accompanyingNumber: '', //进入机房同行人数，必传
          remarks: '', //备注
          pictureName: '', //上传图片名称[多个用英文分号;隔开]，选填
          pictureUrl: '', //上传图片URL路径[多个用英文分号;隔开]，选填
        },

        maxLength: 5,
        showUpload: true, //是否显示上传图片入口
        uploadList: [], //上传的图片列表,
        // 以下字段与图片上传有关
        pcPics: [],
        files: [],
      }
    },
    created: function() {
      this.machineRoomCode = this.$route.query.code;
      this.belongMachineRoom = this.$route.query.codename;
      this.getReasonData();
      this.getNumberData();
      this.getRecordDetail();
    },
    methods: {
      getReasonData() { //获取事由字典数据
        var self = this;
        self.$Spin.show();
        findReasonsForEntryMachineRoom({}).then(res => {
          self.$Spin.hide();
          if(res.status == 200) {
            self.reasonList = res.data;
            if(self.reasonList.length > 0) {
              var tempReason = [];
              self.reasonList.forEach(item => {
                tempReason.push(item.detail_name);
              })
              self.reasonData = [tempReason];
            }
          }
        })
      },
      uploadFile() {
        var self = this;
        if (util.isWeixin()) {
          let localIds = localStorage.getItem('wpt_localIds');
          if (localIds!==null && localIds!=='') {
            self.localIds = JSON.parse(localStorage.getItem('wpt_localIds'));
            self.serverIds = JSON.parse(localStorage.getItem('wpt_serverIds'));
            if (self.serverIds.length > 0) {
              var pic = self.serverIds.shift();
              self.localIds.shift();
              var params = {
                mediaId: pic,
                projectType: localStorage.projectType
              }
              uploadFileByWx(params).then(res => {
                self.files.push(res.data);
                if (res.data) {
                  localStorage.setItem('wpt_localIds', JSON.stringify(self.localIds));
                  localStorage.setItem('wpt_serverIds', JSON.stringify(self.serverIds));
                  this.uploadFile();
                } else {
                  this.$vux.alert.show({
                    title: '提示',
                    content: '图片上传失败',
                  });
                }
              });
            } else {
              self.submit();
            }mapGetters
          } else {
            self.submit();
          }
        } else {
          let file_bases = localStorage.getItem('file_bases');
          if (!util.isStrEmpty(file_bases)) {
            this.pcPics = JSON.parse(file_bases);
            if (this.pcPics.length > 0) {
              var pic = this.pcPics.shift();
              EbeiPlugins.getFileBase64(pic.bigimageUrl, (b64) => {
                if (b64 == undefined) {
                  // self.hideLoading();
                  self.loading = false
                  self.$vux.alert.show({
                    title: '提示',
                    content: '图片异常',
                  })
                  return;
                }

                var typeArray = pic.bigimageUrl.split(".");
                var type = typeArray[typeArray.length - 1];
                var params = {
                  base64: b64,
                  type: type,
                }

                uploadFileByLocal(params).then(res => {
                  if (res){
                    if (res.status==200) {
                      var dataRes = {imgUrl:res.data,name:pic.bigimageName}
                      if (dataRes) {
                        self.files.push(dataRes);
                      }
                      localStorage.setItem('file_bases', JSON.stringify(self.pcPics));
                      // self.count++;
                      self.uploadFile();
                    } else {
                      self.loading = false
                      self.$vux.alert.show({
                        title: '提示',
                        content: '提交失败',
                      })
                    }
                  }else {
                    self.loading = false
                    self.$vux.alert.show({
                      title: '提示',
                      content: '提交失败',
                    })
                  }
                },(err)=>{
                  alert(err)
                });
              }, () => {
                // 获取失败
                // self.hideLoading();
                self.loading = false
                self.$vux.alert.show({
                  title: '提示',
                  content: '文件处理错误',
                })
              });
            } else {//提交
              self.submitData();
            }
          }else {
            self.submitData();
          }
        }
      },
      getNumberData() { //初始化人数选择数据
        var tempNum = [];
        for(var i=1; i<=50; i++) {
          tempNum.push(i);
        }
        this.numberData = [tempNum];
      },
      getRecordDetail() {
        var self = this;
        self.uploadList = [];
        var jsonData = {
          userId: localStorage.memberId,
          machineRoomCode: self.saveInfo.machineRoomCode
        };
        self.$Spin.show();
        findByUserIdAndMachineRoomCode(jsonData).then(res => {
          self.$Spin.hide();
          if(res.status == 200) {
            if(res.data.recordId && res.data.recordId!='') {
              self.isEdit = true;
              self.saveInfo.recordId = res.data.recordId;
              self.saveInfo.machineRoomCode = res.data.machineRoomCode;
              self.saveInfo.belongMachineRoom = res.data.belongMachineRoom;
              self.saveInfo.entryTime = res.data.entryTime;
              self.saveInfo.enterReason = res.data.enterReason;
              self.saveInfo.accompanyingNumber = res.data.accompanyingNumber;
              self.saveInfo.remarks = res.data.remarks;
              self.saveInfo.pictureUrl = res.data.pictureUrl;
              self.saveInfo.pictureName = res.data.pictureName;

              self.valueReason = [self.saveInfo.enterReason];
              self.valueNumber = [self.saveInfo.accompanyingNumber];
              if(self.saveInfo.pictureUrl != "") {
                var pictureUrls = self.saveInfo.pictureUrl.split(",");
                var pictureNames = self.saveInfo.pictureName.split(",");
                pictureUrls.forEach((item, index) => {
                  self.uploadList.push({
                    resPath: item,
                    fName: pictureNames[index]
                  })
                })
              }
            } else {
              self.isEdit = false;
            }
          }
        })
      },
      changeReason(value) { //change 事由
        this.saveInfo.enterReason = value[0];
        console.log("事由："+this.saveInfo.enterReason)
      },
      changeNumber(value) { //change 人数
        this.saveInfo.accompanyingNumber = value[0];
        console.log("人数："+this.saveInfo.accompanyingNumber);
      },
      handleRemove(index) {
        this.showUpload = true;
        this.uploadList.splice(index, 1);
      },
      handleSuccess(res, file) {
        this.$Spin.hide();
        if(res.result == 1) {
          file.url = res.fileInfo.resPath;
          file.name = res.fileInfo.fName;
          this.uploadList.push(res.fileInfo);
//					if(this.meetingPhotoData.length + this.uploadList.length < this.maxLength) {
//						this.showUpload = true;
//					} else {
//						this.showUpload = false;
//					}
        }
        else {
          this.$Message.warning(res.msg); //上传失败提示信息
        }
      },
      handleFormatError(file) {
        this.$Message.info("请上传图片");
      },
      handleBeforeUpload() {
        this.$Spin.show();
      },
      submitData() { //提交表单信息
        // this.uploadFile()
        var self = this;
        if(self.saveInfo.enterReason == "") {
          self.$Message.warning("请选择事由");
          return false;
        }
        else if(self.saveInfo.accompanyingNumber == "") {
          self.$Message.warning("请选择同行人数");
          return false;
        }
        if(self.files.length > 0) {
          var picUrls = [], picNames = [];
          self.files.forEach(item => {
            picUrls.push(item.imgUrl);
            picNames.push(item.name);
          });
          self.saveInfo.pictureName = picNames.toString();
          self.saveInfo.pictureUrl = picUrls.toString();
        }
        if(self.isEdit) { //出
          self.saveInfo.leaveTime = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
          editMachineRoomAccessRecord(self.saveInfo).then(res => {
            if(res.status == 200) {
              self.$Message.success("保存成功");
              self.$router.push("/computerRoomList");
            } else {
              self.$Message.warning(res.message);
            }
          })
        }
        else { //进
          self.saveInfo.entryTime = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
          saveMachineRoomAccessRecord(self.saveInfo).then(res => {
            if(res.status == 200) {
              self.$Message.success("保存成功");
              self.$router.push("/computerRoomList");
            } else {
              self.$Message.warning(res.message);
            }
          })
        }
      },
    }
  }
</script>

<style scoped="scoped">
  .upload-box {
    margin: 20px;
  }
  .upload-box p {color: #919191;font-size: 16px;margin-bottom: 10px;}

  .demo-upload-list {
    display: inline-block;
    width: 70px;
    height: 70px;
    text-align: center;
    line-height: 70px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
    margin-right: 10px;
  }

  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }
  .remove-icon {
    position: absolute;
    right: 0;
    top: 0;
    display: flex;
    background: #FFFFFF;
    border-radius: 100%;
  }

  .submit-btn {
    margin: 30px 20px 10px;
  }
</style>
