<template>
	<view>
		<view class="cu-card">
      <uniSection class="mb-10" :title="$t('入库')" type="line"></uniSection>
      <view class="group-card">
        <view class="item-card" v-for="(item, index) in warehousingList" :key="index" @tap="() => toDetail(item)" >
          <!-- <uni-icons :type="item.icon" size="40"></uni-icons> -->
		  <image :src='item.icon' mode="widthFix"></image>
          <text class="card-text">{{ item.title }}</text>
        </view>
      </view>
      <uniSection class="mb-10" :title="$t('出库')" type="line"></uniSection>
      <view class="group-card">
        <view class="item-card" v-for="(item, index) in ExWarehouse" :key="index" @tap="() => toDetail(item)" >
          <!-- <uni-icons :type="item.icon" size="40"></uni-icons> -->
		  <image v-if="item.icon" :src='item.icon' mode="widthFix"></image>
          <text class="card-text">{{ item.title }}</text>
        </view>
      </view>
      <!-- <uniSection class="mb-10" title="仓内" type="line">
        <view class="group-card">
          <view class="item-card" v-for="(item, index) in warehouseInside" :key="index" @tap="() => toDetail(item)" >
            <uni-icons :type="item.icon" size="40"></uni-icons>
            <text class="card-text">{{ item.title }}</text>
          </view>
        </view>
      </uniSection> -->
		</view>
		<view class="logout-container">
			<button type="primary" class="logout" @click="logout">{{$t('登出')}}</button>
		</view>
		<!-- #ifdef APP -->
		<view class="ver" @click="getVeData(1)">
			<text class="ver-text">V{{version}}<text class="redtext" v-if="veData">{{$t('有新版本可更新')}}</text></text>
		</view>
		<!-- #endif -->
		<uni-popup ref="vepopup" type="center" :mask-click="false">
			<view class="ad-conten">
				<image v-if="!forceUpdate" @click="closeVe" class="ad-bg" src='../../static/images/index_close.png'></image>
				<view class="ad-title">V{{appVersion}}{{$t('新版本更新')}}</view>
				<view class="ad-info">
				    <rich-text :nodes="veData"></rich-text>
				</view>
				<view class="ad-btns">
					<view class="ad-btn" @click="toupdate">
						<view>{{$t('立即更新')}}</view>
					</view>
					<view class="ad-btn" v-if="!forceUpdate" @click="closeVe">
						<view>{{$t('关闭弹窗')}}</view>
					</view>
				</view>
				<view class="progress" v-if="showdownLine">
					<progress :percent="downloadNum" show-info stroke-width="3" />
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
  import { uniSection, uniIcons } from '@dcloudio/uni-ui';
  import {getUserPermission, getUserProfile, getVesionData} from '../../api/system'
  import path from '../../static/images/rucang.png'
  import path1 from '../../static/images/xiegui.png'
  import path2 from '../../static/images/tiaobo.png'
  import path3 from '../../static/images/tuichang.png'
  import path4 from '../../static/images/fenggui.png'
  import path5 from '../../static/images/tiaobos.png'
  import { apiBaseUrl} from '@/util/config.js'
  import path6 from '../../static/images/icon/kongyundaocang.png'
  import path7 from '../../static/images/icon/kongyunbeihuo.png'
  import path8 from '../../static/images/icon/lihuo.png'
  import path9 from '../../static/images/icon/kongyunchucang.png'
  import path10 from '../../static/images/icon/hebaochaxun.png'
  import path11 from '../../static/images/icon/zhuanggui.png'
  import path12 from '../../static/images/icon/diaobochucang.png'

	export default {
    components: {
      uniSection,
      uniIcons
    },
		data() {
			return {
        permissions: [],
        warehouseInside : [{
						title: this.$t('打包'),
						icon: '../../static/images/rucang.png',
						color: '#39b54a',
						url: '../warehousing/list'
					},
					{
						title: this.$t('盘点'),
						icon: '../../static/images/rucang.png',
						color: '#e54d42',
						url: '../loading/list'
					},
					{
						title: this.$t('订单找货'),
						icon: '../../static/images/rucang.png',
						color: '#e54d42',
						url: '../loading/list'
					}
				],
				appUrl:'',
				veData:'',
				version:'',
				appVersion:'',
				forceUpdate:0,
				showdownLine:false,
				downloadNum:0,//下载百分比
				totalSize:0//下载总量
			};

		},
    onShow() {
      this.$store.dispatch('dict/loadDictDatas')
      getUserProfile()
      getUserPermission().then(r => {
        this.permissions = r.permissions
      })
    },
	onLoad(){
		setTimeout(()=>{
			this.getVersion()
			//#ifdef APP
			this.getVeData(2)
			//#endif
		},200)

		uni.setNavigationBarTitle({
			title:this.$t('捷道WMS')
		})
	},
		computed: {
      warehousingList(){
        return [
          {
            permission: 'pda:warehousing',
            title: this.$t('海运入仓'),
            icon:path,
            color: '#39b54a',
            url: '../warehousing/list'
          },
          {
            permission: 'pda:unloadCabinet',
            title: this.$t('卸柜到仓'),
            icon: path1,
            color: '#e54d42',
            url: '../unloadCabinet/list'
          },
          {
            permission: 'pda:warehouseAdjustment',
            title: this.$t('调拨到仓'),
            icon: path2,
            color: '#39b54a',
            url: '../warehouseAdjustment/list'
          },
          {
            permission: 'pda:ExitWarehouse',
            title: this.$t('海运退场到仓'),
            icon: path3,
            color: '#e54d42',
            url: '../ExitWarehouse/list'
          },
          {
            permission: 'pda:warehousingAir',
            title: this.$t('空运入仓'),
            icon:path,
            color: '#39b54a',
            url: '../warehousingAir/list'
          },
          {
            permission: 'pda:airUnloadCabinet',
            title: this.$t('空运到仓'),
            icon: path6,
            color: '#39b54a',
            url: '../airUnloadCabinet/airUnloadCabinet'
          },
          {
            permission: 'pda:stocking',
            title: this.$t('空运备货'),
            icon: path7,
            color: '#e54d42',
            url: '../stocking/index'
          },
          {
            permission: 'pda:ExitWarehouseAir',
            title: this.$t('空运退场到仓'),
            icon: path3,
            color: '#e54d42',
            url: '../ExitWarehouseAir/list'
          }
        ].filter(e => this.permissions.includes(e.permission))
      },
      ExWarehouse() {
        return [
          {
            permission: 'pda:loading',
            title: this.$t('装柜'),
            icon: path11,
            color: '#39b54a',
            url: '../loading/list'
          },
          {
            permission: 'pda:transferWarehouseOut',
            title: this.$t('调拨出仓'),
            icon: path12,
            color: '#e54d42',
            url: '../transferWarehouseOut/list'
          },
          {
            permission: 'pda:tally',
            title: this.$t('海运理货'),
            icon: path8,
            color: '#e54d42',
            url: '../tally/list'
          },
          {
            permission: 'pda:airWarehouseOut',
            title: this.$t('空运出仓'),
            icon: path9,
            color: '#e54d42',
            url: '../airWarehouseOut/list'
          },
          {
            permission: 'pda:packTogetherSearch',
            title: this.$t('合包查询'),
            icon: path10,
            color: '#e54d42',
            url: '../packTogetherSearch/packTogetherSearch'
          },
          {
            permission: 'pda:certificateSearch',
            title: this.$t('证件查询'),
            icon: require('@/static/images/idcard.png'),
            color: '#e54d42',
            url: '../certificateSearch/certificateSearch'
          },
          {
            permission: 'pda:tallyAir',
            title: this.$t('空运理货'),
            icon: path8,
            color: '#e54d42',
            url: '../tallyAir/list'
          },
          {
            permission: 'pda:mergePkg',
            title: this.$t('合包装箱'),
            icon: path8,
            color: '#e54d42',
            url: '../mergePkg/index'
          }
        ].filter(e => this.permissions.includes(e.permission))
      }
    },
		methods: {
			getVersion(){
				this.version = uni.getStorageSync('appversion');
				this.versionCode = uni.getStorageSync('versionCode');

				let split = apiBaseUrl.match(/([a-z0-9-]+)/g)
				const append = split[1] === 'api' ? split[2] : split[1]
				this.version = `${this.version}.${append}`
			},
			toupdate(){
				// ios需要跳转到对应的地址
				if(uni.getSystemInfoSync().osName=='ios'){
					return plus.runtime.openURL(this.appUrl)
				}
				// #ifdef APP-PLUS
				let that = this
				if(that.showdownLine) return
				uni.showLoading({
					title: that.$t("下载中..."),
				})

				that.showdownLine = true
				var dtask = plus.downloader.createDownload(
					that.appUrl,
					{
						timeout:60,
						retry: 1,
						retryInterval: 3
					}, (d, status) => {
						uni.hideLoading()
						that.showdownLine = false
						if (status == 200) {
							that.closeVe()
							console.log("下载成功安装: " + d.filename);
							plus.runtime.install(d.filename, {}, () => {
			
							}, function(error) {
								plus.nativeUI.alert(that.$t("安装失败，请稍候重试"))
							})
						} else {
							plus.nativeUI.alert(that.$t("安装失败，请稍候重试"))
						}
					});

					try{
						dtask.start();
						dtask.addEventListener("statechanged", function (download, status) {
							if(that.downloadNum==100){
								uni.hideLoading();
							}
							switch (download.state) {
								case 2:
									break;
								case 3://进度条百分比 totalSize为总量，baifen为当前下载的百分比
									if(that.totalSize==0){
										that.totalSize=parseInt(download.totalSize);
									}
									if(parseInt(download.downloadedSize/that.totalSize*100)!=that.downloadNum){
										that.downloadNum=parseInt(download.downloadedSize/that.totalSize*100);
									}
									break;
								case 4:
									// mui.toast("下载完成");
									uni.hideLoading();
									break;
							}
						});
					}catch(err){
						uni.hideLoading();
						that.showdownLine = false
						that.closeVe()
						plus.nativeUI.alert(that.$t("安装失败，请稍候重试"))
					}
					
				// #endif
			},
			openVe(){
				this.$refs.vepopup.open()
			},
			closeVe(){
				uni.setStorageSync('isShowVersion', 2)
				this.$refs.vepopup.close()
			},
      /**
       * 获取更新信息
       * @param n 1.点击红字 2.页面onLoad
       */
			getVeData(n){
				let pages = getCurrentPages() // 获取栈实例
				
				if(uni.getStorageSync('isShowVersion')==2){
						return
				}
				var addType = uni.getSystemInfoSync().osName=='ios'?'pdaIos':'pdaAndroid'

				getVesionData({ appType: addType,versionCode:this.versionCode}).then(res => {
						if(res){
							this.veData = res.desp
							this.appUrl = res.appUrl
							this.appVersion = res.appVersion
							this.forceUpdate = res.forceUpdate
							// if(res.forceUpdate || n === 1){
								this.openVe()
							// }
						}else{
							if(n==1){
								uni.showToast({
									title:this.$t('当前已是最新版本'),
									icon:'none'
								})
							}
						}
				})
			},
			toDetail(item) {
				uni.navigateTo({
					url: item.url
				});
			},
			logout() {
				this.$store.commit('SET_USER_TOKEN', null)
				this.$store.commit('SET_USER_INFO', null)
				uni.reLaunch({
					url: '../login/login'
				})
			}
		}
	};
</script>

<style scoped lang="scss">
  .cu-card {
    padding-bottom: 74px;
    .group-card {
      display: flex;
      flex-wrap: wrap;
      .item-card {
        width: calc(50% - 31rpx);
        height: 150rpx;
        background: #fff;
        margin: 20rpx;
        display: flex;
        align-items: center;
        padding-left: 40rpx;
        .card-text {
          margin-left: 8rpx;
        }
		image{
			width:104rpx;
		}
      }
      .item-card:nth-child(even) {
        margin-left: 0;
      }
      .item-card:nth-child(n+3) {
        margin-top: 0;
      }
    }
    ::v-deep .uni-section {
      background: none;
    }
  }

	.logout-container {
		position: fixed;
		bottom: 60rpx;
		width: 100%;
		padding: 0 30rpx;
	}

	.ver {
		position: fixed;
		bottom: 5px;
		right: 10px;
		width: 100%;
		text-align: right;
	}

	.ver-text {
		font-size: 14px;
		color: #C0C0C0;
	}
	.ad-conten{
		width: 580upx;
		border-radius: 16upx;
		background-image: url(../../static/images/index_pbg.png);
		background-repeat: no-repeat;
		background-size: 100%;
		padding-top: 182upx;
		padding-bottom: 20upx;
	}
	.ad-bg{
		width: 60upx;
		height: 60upx;
		margin-top: -154upx;
		margin-right: 14upx;
		float: right;
	}
	.ad-title{
		width: 100%;
		text-align: center;
		font-size: 40upx;
		font-weight: 600;
	}
	.ad-btns{
		width: 90%;
		margin: 20rpx auto;
		display:flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
	}
	.ad-btn{
		width: 90%;
		color: #fff;
		text-align: center;
		padding: 40upx 0;
		background-image: url(../../static/images/btn_bg.png);
		background-size: 100%;
		background-repeat: no-repeat;
	}
	.ad-btn view{
		margin-top: -20upx;
		font-size: 36upx;
	}
	.ad-info{
		width: 92%;
		margin: 20upx auto;
		height: 260upx;
		overflow: auto;
	}
	.redtext{
		font-size: 26upx;
		color: #FF0000;
		margin-left:12upx;
	}
	.progress{
		width: 80%;
		margin: 20upx auto;
	}
</style>
