<template>
  <div class="common-page-auto-scroll-style page-bg">
    <d-p-cell title="任务编号" :value="taskNumber"></d-p-cell>
    <d-p-cell title="所属项目" :value="projectName"></d-p-cell>
    <d-p-cell title="业主姓名" :value="ownerName"></d-p-cell>
    <d-p-cell title="联系电话" :value="ownerPhone"></d-p-cell>
    <d-p-cell title="路址" :value="address"></d-p-cell>
    <d-p-cell title="物品类型" :value="itemType"></d-p-cell>
    <d-p-cell title="通行时间" :value="passTime"></d-p-cell>
    <d-p-cell title="物品内容" :value="itemDetail"></d-p-cell>
    <div v-if="type === 0">
      <div class="placeholder-area"></div>
      <textarea class="text-input-area" rows="8" v-model="passContent" :placeholder="textTips" ></textarea>
      <upload-pic></upload-pic>
      <div class="bottom-area">
        <div class="submit-btn common-submit-btn" @click.stop="uploadAll">提交</div>
      </div>
    </div>
    <div v-if="type === 1">
      <div class="placeholder-area"></div>
      <d-p-cell title="放行时间" :value="passageTime"></d-p-cell>
      <d-p-cell title="放行人" :value="pedestrians"></d-p-cell>
      <div class="placeholder-area"></div>
      <div class="pass-content">{{passportContent}}</div>
      <!-- 图片区域 -->
      <div class="passport-pic-area" v-if="attachments.length > 0">
        <img v-for="(obj,index) in attachments" :key="index" :src="obj.resPath">
        <div style="clear: both"></div>
      </div>
    </div>
    <loading v-model="loading" text="加载中"></loading>
  </div>
</template>

<script>
import DPCell from './../../components/itemPassport/DPCell'
import UploadPic from './../../components/UploadPic'
import util from './../../util/util.js'
import {
  queryItemPassportList,
  editItemPassport,
  uploadFileByWx,
  uploadFileByLocal
} from './../../service/itemPassportService.js'
export default {
  components: {
    DPCell,
    UploadPic
  },
  name: 'DecorationPassportDetail',

  data () {
    return {
      passportId: null,
      passportDetail: null,
      passContent: '', // 放行描述内容
      type: 0, // 类型 0-放行， 1-放行详情
      textTips: '请填写描述信息',
      loading: false,

      // 以下字段与图片上传有关
      pcPics: [],
      files: [],
      orderId: '', //订单号
      recordId: '',//记录Id
      localIds: [],
      serverIds: [],

      passportPics: ['http://wyservice.gzbfdc.com:5903/filemanager_micro/previewFile?fileId=60bbdd2c-c937-4b6e-8164-9cd169261fb6',
                    'http://wyservice.gzbfdc.com:5903/filemanager_micro/previewFile?fileId=60bbdd2c-c937-4b6e-8164-9cd169261fb6',
                    'http://wyservice.gzbfdc.com:5903/filemanager_micro/previewFile?fileId=60bbdd2c-c937-4b6e-8164-9cd169261fb6',
                    'http://wyservice.gzbfdc.com:5903/filemanager_micro/previewFile?fileId=60bbdd2c-c937-4b6e-8164-9cd169261fb6']
    }
  },

  created () {
    try {
      this.passportId = this.$route.query.id
      this.initData()
    } catch (error) {
      this.util.debugLog(error)
      this.showTips('放行条信息错误')
    }
  },

  beforeRouteLeave (to, from, next) {
    //has access to `this` component instance}
    this.cleanPicCache()
    next()
  },

  methods: {
    initData () {
      this.loading = true
      let that = this
      queryItemPassportList(this.makeQueryParams()).then((res) => {
        if (res.status === '200' || res.status === '10200') {
          let data = res.data
          if (data.records.length > 0) {
            that.passportDetail = data.records[0]
            that.initType()
          } else {
            that.showTips('放行条信息查询失败')
          }
        } else {
          that.showTips(res.message)
        }
        that.loading = false
      }).catch((error) => {
        that.util.debugLog(error)
        that.showTip('网络错误')
      })
    },

    initType () {
      if (this.util.isNotEmpty(this.passportDetail.pedestrians)) {
        this.type = 1
      } else {
        this.type = 0
      }
    },

    uploadAll () {
      this.loading = true
      this.uploadFile()
    },

    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 = {
                  imgData: b64,
                  imgType: type,
                  imgSize: b64.length,
                  mediaType: pic.mediaType,
                  count: self.count,
                }
                uploadFileByLocal(params).then(res => {
                  var resJson = self._x2js.xml2js(res);
                  if (resJson && resJson.list && resJson.list.result && resJson.list.result == 1) {
                    var dataRes = resJson.list.data;
                    if (dataRes) {
                      self.files.push(JSON.parse(dataRes));
                    }
                    localStorage.setItem('file_bases', JSON.stringify(self.pcPics));
                    self.count++;
                    self.uploadFile();
                  } else {
                    self.loading = false
                    self.$vux.alert.show({
                      title: '提示',
                      content: '提交失败',
                    })
                  }
                });
              }, () => {
                // 获取失败
                // self.hideLoading();
                self.loading = false
                self.$vux.alert.show({
                  title: '提示',
                  content: '文件处理错误',
                })
              });
            } else {
              self.submit();
            }
          }else {
            self.submit();
          }
        }
      },

    submit () {
      try {
        let attachArray = this.files.map(file => {
          let newObj = {}
          // newObj.fid = file.fileId
          newObj.fileName = file.fileName.split(".")[0]
          newObj.fullName = file.fileName
          newObj.resPath = file.filePath

          return newObj
        })

        let params = {
          releaseNumber: this.passportId,
          descriptionContent: this.passContent,
          pedestrians: localStorage.getItem('memberId'),
          pedestriansName: localStorage.getItem('fullName'),
          submitter: localStorage.getItem('memberId'),
          submitterName: localStorage.getItem('fullName'),
          passageTime: this.util.formatTime(new Date()),
          attachment: attachArray
        }

        let that = this
        editItemPassport(params).then((res) => {
          if (res.status === '200' || res.status === '10200') {
            that.showTips('提交成功')
            that.goBack()
          } else {
            that.showTips(res.message)
          }
          that.loading = false
        }).catch((err) => {
          that.showTips('网络错误')
          that.loading = false
        })
      } catch (error) {
        this.util.debuLog('信息错误')
        this.showTips('信息错误')
        that.loading = false
      }
    },

    makeQueryParams () {
      return {
        size: '10',
        Index: '1',
        releaseNumber: this.passportId
      }
    },

    goBack() {
      this.$router.go(-1)
    },

    /** 清空图片缓存 */
    cleanPicCache() {
      localStorage.setItem('file_bases', "");
      localStorage.setItem('wpt_localIds', "");
      localStorage.setItem('wpt_serverIds', "");
    },

    showTips (tip) {
      this.$vux.toast.show({
        type: 'text',
        text: tip,
        position: 'bottom'
      })
    }
  },

  computed: {
    attachments () {
      let arr = []

      try {
        arr = this.passportDetail.attachements
      } catch (error) {
        this.util.debugLog(error)
      }

      return arr
    },

    taskNumber () {
      let res = ''

      try {
        res = this.passportDetail.decpssCode
      } catch (error) {
        this.util.debugLog(error)
      }

      return res
    },

    projectName () {
      let res = ''

      try {
        res = this.passportDetail.projectNamne
      } catch (error) {
        this.util.debugLog(error)
      }

      return res
    },

    ownerName () {
      let res = ''

      try {
        res = this.passportDetail.ownerName
      } catch (error) {
        this.util.debugLog(error)
      }

      return res
    },

    ownerPhone () {
      let res = ''

      try {
        res = this.passportDetail.telephone
      } catch (error) {
        this.util.debugLog(error)
      }

      return res
    },

    address () {
      let res = ''

      try {
        res = this.passportDetail.address
      } catch (error) {
        this.util.debugLog(error)
      }

      return res
    },

    itemType () {
      let res = ''

      try {
        res = this.passportDetail.itemTypeDesc
      } catch (error) {
        this.util.debugLog(error)
      }

      return res
    },

    passTime () {
      let res = ''

      try {
        res = this.passportDetail.stimatedTime
      } catch (error) {
        this.util.debugLog(error)
      }

      return res
    },

    itemDetail () {
      let res = ''

      try {
        res = this.passportDetail.itemDetails
      } catch (error) {
        this.util.debugLog(error)
      }

      return res
    },

    passportContent () {
      let res = ''

      try {
        res = this.passportDetail.descriptionContent
      } catch (error) {
        this.util.debugLog(error)
      }

      return res
    },

    pedestrians () {
      let res = ''

      try {
        res = this.passportDetail.pedestriansName
      } catch (error) {
        this.util.debugLog(error)
      }

      return res
    },

    passageTime () {
      let res = ''

      try {
        res = this.passportDetail.passageTime
      } catch (error) {
        this.util.debugLog(error)
      }

      return res
    }
  }
}
</script>

<style lang="scss" scoped>
.page-bg {
  background-color: #fbf9fe
}

.placeholder-area {
  width: 100%;
  height: 10px;
  background-color: rgba($color: #000000, $alpha: 0)
}

.text-input-area {
  margin-top: 5px;
  width: 100%;
  padding: 10px 10px;
  resize: none;
}

.bottom-area {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 55px;
  background-color: rgba($color: #000000, $alpha: 0);
}

.submit-btn {
  width: 50%;
  margin-top: 10px;
}

.pass-content {
  width: 100%;
  padding: 10px 10px;
  color: #333;
  font-size: 14px;
  background-color: #fff;
}

.passport-pic-area {
  width: 100%;
  padding: 5px;
  background-color: #fff;
}

.passport-pic-area img {
  float: left;
  width: 80px;
  height: 80px;
  margin-right: 8px;
  margin-bottom: 8px;
}

.submit-btn {
  width: 50%;
  margin-top: 10px;
  background-color: #57a3ff;
  font-size: 16px;
  color: #fff;
  height: 44px;
  text-align: center;
  line-height: 44px;
  font-weight: bold;
  border-radius: 22px;
  margin-bottom: 10px;
}
</style>
