<template>
  <el-card v-loading="loading">
    <div slot="header" style="text-align: center;">
      <span v-if="hasProduct"><b>仿真名称： {{ courseModel.name }}</b></span>
      <span v-else>无仿真产品</span>
    </div>
    <el-tabs
      type="border-card"
      :value="currentPrdCode"
      :style="{ height: height-50 +'px' }"
      @tab-click="handleLeave"
    >
      <el-tab-pane
        v-for="item in productList"
        :key="item.code"
        :name="item.code"
        :label="item.name"
        style="padding: 5px"
        :style="{ height: height-160 +'px' }"
      >
        <el-scrollbar wrap-class="scrollbar-wrapper" :style="{ height: height-170 +'px' }">
          <p class="list-item">
            <span class="list-label">产品说明：</span>
            <span class="list-elem">{{ courseModel.remarks }}</span>
          </p>
          <p class="list-item">
            <span class="list-label">权限列表：</span>
          </p>
          <limit-list :ref="`limit_${item.code}`" :course-model="courseModel" @initLoadPage="initLoadPage" />
        </el-scrollbar>
      </el-tab-pane>
      <div v-if="hasProduct" class="btn-buy">
        <el-button type="success" @click="buy">购买</el-button>
        <el-button v-if="hasPermssion" type="primary" @click="distribute">权限分发</el-button>
        <el-button v-if="hasPermssion" type="primary" @click="transfer">权限转赠</el-button>
        <el-button v-show="isStartDemon" type="primary" @click="start">开始仿真</el-button>
        <el-button v-show="isCreateRoom" type="primary" @click="start">创建房间</el-button>
        <el-button v-show="isInRoom" type="primary" @click="joinRoom">进入房间</el-button>
      </div>
    </el-tabs>
  </el-card>
</template>
<script>
import { getPublishMapInfo } from '@/api/jmap/map';
import { getGoodsTryUse } from '@/api/management/goods';
import { getCommodityMapProduct, getMapProductDetail } from '@/api/management/mapprd';
import { PermissionType } from '@/scripts/ConstDic';
import { launchFullscreen } from '@/utils/screen';
import { queryPermissionSimulation } from '@/api/management/author';
import { postCreateRoom, getjointTraining, checkRoomExist } from '@/api/chat';
import { UrlConfig } from '@/router/index';
import { simulationNotify } from '@/api/simulation';
import localStore from 'storejs';
import LimitList from '@/views/components/limits/index';
import WindowResizeHandler from '@/mixin/WindowResizeHandler';

export default {
	name: 'ExamDetailList',
	components: {
		LimitList
	},
	filters: {
		setTime(val) {
			if (val <= 1) {
				return `0分钟`;
			} else if (val > 1 && val <= 60) {
				return '1分钟';
			} else if (val > 60) {
				const time = parseInt(val / 60);
				return `${time}分钟`;
			}
		}
	},
	mixins: [
		WindowResizeHandler
	],
	data() {
		return {
			height: '',
			tryTime: 0,
			goodsId: '',
			tryUser: 0,
			loading: true,
			currentLessonId: '',
			currentPrdCode: '',
			productList: [],
			courseModel: {
				id: '',
				name: '',
				mapId: '',
<<<<<<< HEAD
				skinCode: '',
=======
				skinStyle: '',
>>>>>>> remotes/origin/master
				remarks: '',
				prdType: '',
				prdCode: '',
				pmsList: []
			},
			EffectiveTypeList: [],
			jointShow: false,
			jointGroup: ''
		};
	},
	computed: {
		hasProduct() {
			return this.productList.length;
		},
		hasPermssion() {
			let isShow = false;
			if (this.courseModel.pmsList.length) {
				isShow = true;
			}
			return isShow;
		},
		isStartDemon() {
			return this.courseModel.prdType !== '03' && (this.hasPermssion || this.tryTime > 0);
		},
		isCreateRoom() {
			return this.courseModel.prdType === '03' && this.hasPermssion && !this.jointShow;
		},
		isInRoom() {
			return this.courseModel.prdType == '03' && this.hasPermssion && this.jointShow;
		},
		mapId() {
			return this.$route.params.mapId;
		}
	},
	watch: {
		'$route': function (val) {
			this.loadInitData();
		},
		'currentPrdCode': function (code) {
			this.initLoadPage({ id: this.mapId, code: code });
		}
	},
	async mounted() {
		this.loadInitData();
	},
	methods: {
		async loadInitData() {
			this.$Dictionary.effectiveType().then(list => {
				this.EffectiveTypeList = list;
			});

			this.currentPrdCode = '';
			this.productList = [];
			try {
				if (parseInt(this.mapId)) {
					this.getJointTrainingList();
					const rest = await getPublishMapInfo(this.mapId);
					if (rest && rest.code == 200) {
<<<<<<< HEAD
						const resp = await getCommodityMapProduct(rest.data.skinCode);
=======
						const resp = await getCommodityMapProduct(rest.data.skinStyle);
>>>>>>> remotes/origin/master
						if (resp.data && resp.data.length) {
							this.productList = resp.data.sort((a, b) => {
								return Number(b.prdType) - Number(a.prdType);
							});

							this.currentPrdCode = localStore.get(this.$route.path) || this.productList[0].code;
						}
					}
				}
				this.loading = false;
			} catch (e) {
				this.$messageBox('获取产品列表失败');
			}
		},
		resizeHandler: function () {
<<<<<<< HEAD
			this.height = this._clientHeight;
=======
			this.height = this._clientHeight - 50;
>>>>>>> remotes/origin/master
		},
		async getJointTrainingList() {
			try {
				if (this.mapId) {
					const res = await checkRoomExist({ mapId: this.mapId });
					this.jointGroup = res.data;
					this.jointShow = false;
					if (res.data) {
						this.jointShow = true;
					}
				}
			} catch (error) {
				console.error(error, '获取是否拥有综合演练房间');
			}
		},
		async handleLeave(tab) {
			this.currentPrdCode = tab.name;
			localStore.set(this.$route.path, this.currentPrdCode);
		},
		async initLoadPage(data) {
			this.loading = true;
			if (data && parseInt(data.id) && data.code) {
				try {
					const resp = await getMapProductDetail(data.code);
					this.tryUser = 0;
					this.loading = false;
					this.courseModel = {
						id: resp.data.id,
						name: resp.data.name,
						mapId: data.id,
<<<<<<< HEAD
						skinCode: resp.data.skinCode,
=======
						skinStyle: resp.data.skinStyle,
>>>>>>> remotes/origin/master
						remarks: resp.data.remarks,
						prdType: resp.data.prdType,
						prdCode: resp.data.code,
						pmsList: resp.data.pmsList || [],
						PermissionType: PermissionType.SIMULATION
					};

					const rest = await queryPermissionSimulation({ mapId: this.courseModel.mapId, prdCode: this.courseModel.prdCode });
					this.courseModel.pmsList = rest.data;
					if (!this.courseModel.pmsList.length) {
						this.tryUser = 1;
						const paras = {
							mapId: data.id,
							mapProductCode: data.code,
							productType: PermissionType.SIMULATION
						};

						try {
							const resr = await getGoodsTryUse(paras);
							if (resr.data.tryTime <= 0) {
								this.tryTime = 0;
							} else {
								this.tryTime = resr.data.tryTime;
								this.goodsId = resr.data.goodsId;
							}
						} catch (error) {
							this.tryTime = 0;
						}
					}
				} catch (error) {
					this.loading = false;
					this.$messageBox('刷新失败');
				}
			} else {
				this.loading = false;
			}
		},
		async joinRoom() {
			await getjointTraining(this.jointGroup);
			const query = { skinCode: this.courseModel.skinCode, group: this.jointGroup };
			this.$router.push({ path: `/trainroom`, query: query });
		},
		async start() {
			if (this.courseModel.prdType == '03') {
				try {
					const param = {
						mapId: Number(this.mapId),
						prdCode: this.courseModel.prdCode
					};
					const res = await postCreateRoom(param);
					if (res && res.code == 200) {
						const query = { skinCode: this.courseModel.skinCode, group: res.data };
						this.$router.push({ path: `/trainroom`, query: query });
					}
				} catch (error) {
					if (error.code == 20001) {
						this.$confirm(`每个用户只能创建一个综合演练房间, 是否进入房间`, '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(() => { }).catch(() => { });
					}
					if (error.code == 500009) {
						this.$messageBox(error.message);
					}
				}
			} else {
				this.loading = this.$loading({
					lock: true,
					text: 'Loading',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				if (this.courseModel.pmsList.length) {
					this.jump();
				} else {
					if (this.tryTime <= 1) {
						this.loading.close();
						this.$confirm('您没有权限，请前往购买产品', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(() => {
							this.buy();
						}).catch(() => { });
					} else {
						this.jump();
					}
				}
			}
		},
		jump() {
			const data = { mapId: this.courseModel.mapId, code: this.currentPrdCode };
			simulationNotify(data).then(resp => {
				// try 0 有权限不走试用
				const query = { skinCode: this.courseModel.skinCode, group: resp.data, prdType: this.courseModel.prdType, mapId: this.courseModel.mapId, code: this.currentPrdCode, goodsId: this.goodsId, try: this.tryUser };
				this.$router.push({ path: `${UrlConfig.display}/demon`, query: query });
				launchFullscreen();
			}).catch(error => {
				this.$messageBox(`创建仿真失败: ${error.message}`);
			});
		},
		buy() {
			this.$router.push({
				path: `${UrlConfig.demonstration.pay}/${this.courseModel.id}`,
				query: { permissionType: PermissionType.SIMULATION, prdCode: this.courseModel.prdCode, mapId: this.courseModel.mapId }
			});
		},
		transfer() {
			if (this.$refs) {
				this.$refs[`limit_${this.currentPrdCode}`][0].transfer(this.courseModel);
			}
		},
		distribute() {
			if (this.$refs) {
				this.$refs[`limit_${this.currentPrdCode}`][0].distribute(this.courseModel);
			}
		}
	}
};
</script>
<style scoped>
    ::-webkit-scrollbar {
        width: 3px;
        height: 3px;
    }
</style>
<style>
    .title {
        font-weight: bold
    }

    .time-item {
        font-size: 24px;
        color: black !important;
    }

    .time-label {
        display: -moz-inline-box;
        display: inline-block;
        text-align: right;
        margin-left: 14px;
    }

    .time-elem {
        color: rgb(90, 89, 89) !important;
    }

    .list-item {
        font-size: 16px;
        margin-bottom: 20px;
        padding: 0px;
    }

    .list-label {
        display: -moz-inline-box;
        display: inline-block;
        text-align: left;
    }

    .list-elem {
        color: #808080 !important;
    }

    .btn-buy {
        position: relative;
        text-align: center;
        justify-content: center;
        transform: translateY(-20px);
    }

    .el-tabs--border-card>.el-tabs__header .el-tabs__item {
        font-weight: bold !important;
    }
</style>
