<script>
const _ = require('lodash');
import jwt from 'jsonwebtoken';
import {
  mapState,
  mapMutations,
  createNamespacedHelpers,
} from 'vuex';
const {
  mapActions: companyBaoanWork
} = createNamespacedHelpers('company_baoan_work');
const {
  mapActions: companyBaoanDispatch
} = createNamespacedHelpers('company_baoan_dispatch');
const {
  mapActions: securityGuardBase
} = createNamespacedHelpers('security_guard_base');
export default {
  globalData: {
    version: plus.runtime.version
  },
  onLaunch: function () {
    this.checkVersion();
    if (process.env.VUE_APP_PLATFORM === 'app-plus') {
      // plus.screen.lockOrientation('portrait-secondary');
      plus.screen.lockOrientation('portrait-primary');
    }
    // 定时器
    setInterval(() => {
      this.toPrepare();
    }, 10000);
  },
  onShow: function () {
    this.checkUser();
    // console.log('App Show')
  },
  onHide: function () {
    // console.log('App Hide')
  },
  methods: {
    ...mapMutations(['setUser']),
    ...companyBaoanWork(['fetch']),
    ...companyBaoanDispatch({ getDispatch: 'fetch' }),
    ...securityGuardBase({ getSGB: 'fetch' }),
    // 准备数据
    async toPrepare() {
      if (!this.user.id) return; // 没有用户信息,不继续进行
      // 组织数据,获取定位,上传定位
      const { id } = this.user;
      let obj = _.pick(this.user, ['name', 'card']);
      obj.user_id = this.user.id;
      // 1.查询这个人是否在岗
      const sgb = await this.getSGB({ id })
      if (this.$checkRes(sgb)) {
        obj.is_class = _.get(sgb, 'data.is_class'); // 是文字,不是码
      }
      if (obj.is_class === '下班' || obj.is_class === '1') return; // 没打卡,不需要继续进行(如果24小时定位,则把这个判断隐藏)
      // 2.查询入职信息,填充进去
      const cbw = await this.fetch({ security_guard_id: id, is_quit: '0' })
      if (this.$checkRes(cbw)) {
        obj.company_name = _.get(cbw, 'data.company_name');
        obj.company_id = _.get(cbw, 'data.company_id');
      }
      // 3.查询派遣信息,填充进去
      const dispatch = await this.getDispatch({ security_guard_id: id, status: '0' });
      if (this.$checkRes(dispatch)) {
        obj.company_service_object_id = _.get(dispatch, 'data.service_target_id');
        obj.company_service_object_name = _.get(dispatch, 'data.service_target');
      }
      // 获取定位信息
      const position = await this.toGetLocation();
      obj = { ...obj, ...position };
      // 上传
      this.sendPosition(obj);
    },
    // 获取定位
    async toGetLocation() {
      const [err, posRes] = await uni.getLocation({ type: 'gcj02' });
      if (err) return;
      return { latitude: posRes.latitude, longitude: posRes.longitude };
    },
    // 发送定位
    async sendPosition(data) {
      const [err, res] = await uni.request({ url: 'http://baoan.fwedzgc.com:8090/api/position', method: 'post', data })
      if (err) {
        console.error(err);
      } else console.log('已上传定位');
    },
    // 检查用户
    async checkUser() {
      if (this.user.id) return;
      const token = uni.getStorageSync('token');
      if (!token) {
        uni.redirectTo({
          url: '/pages/login/index'
        })
      } else {
        const tokenObject = jwt.decode(token);
        const res = await this.getSGB({
          id: tokenObject.id
        })
        if (this.$checkRes(res)) {
          this.setUser(res.data);
          uni.redirectTo({
          url: '/pages/home/index'
        })
        }
      }
    },
    //检查版本
    checkVersion() {
      uni.request({
        method: 'get',
        url: 'http://baoan.fwedzgc.com:8090/files/baoanbase/appVersion.json',
        success: (res) => {
          const { version, url } = res.data;
          if (getApp().globalData.version === version) return;
          uni.showModal({
            title: '更新',
            content: "有新版本,是否下载?",
            success: (res) => {
              if (res.confirm) {
                // 下载app
                this.toUpdateAPK(url);
              }
            }
          })
        }
      })
    },
    // 更新
    toUpdateAPK(url) {
      if (!url) return;
      uni.showLoading({
        title: '更新中……'
      })
      uni.downloadFile({
        url,
        success: res => {
          uni.hideLoading();
          console.log(res);
          if (res.statusCode == 200) {
            uni.showModal({
              title: '',
              content: '更新成功，确定现在重启吗？',
              confirmText: '重启',
              confirmColor: '#EE8F57',
              success: modalRes => {
                if (modalRes.confirm) {
                  plus.runtime.install(
                    res.tempFilePath,
                    { force: true },
                    function (res) {
                      plus.runtime.restart();
                    })
                }
              }
            })
          }
        },
      })



      // const task = plus.downloader.createDownload(url, {}, function (d, status) {
      //   console.log(d, status); 
      //   if (status === 200) {
      //     // 安装
      //     plus.runtime.install(
      //       plus.io.convertLocalFileSystemURL(d.filename, {}, {}, function (error) {
      //         uni.showToast({
      //           title: '更新失败',
      //           mask: false,
      //         })
      //       })
      //     )
      //   }
      // });
      // task.start();
    }


  },
  computed: {
    ...mapState(['user']),
  },
}
</script>

<style lang="scss">
@import 'uview-ui/index.scss';
@import '@/static/icon/iconfont.css';
/*每个页面公共css */
</style>
