<template>
  <div>
    <QueryListPage ref="queryListPage" :pager-config="pagerConfig" :query-form="queryForm" :query-list="queryList" />
    <training-draft
      ref="draftTrain"
      :skin-code-list="skinCodeList"
      :training-type-list="trainingTypeList"
      :training-operate-type-map="trainingOperateTypeMap"
      @refresh="reloadTable"
    />
    <div class="draft">
      <el-button-group>
        <el-button type="primary" @click="turnback">{{ $t('global.back') }}</el-button>
      </el-button-group>
    </div>
  </div>
</template>

<script>
import { pageQueryTraining } from '@/api/jmap/training';
import { trainingNotify } from '@/api/simulation';
import { getCommodityMapProduct, getProductList } from '@/api/management/mapprd';
import { launchFullscreen } from '@/utils/screen';
import { getSkinCodeList } from '@/api/management/mapskin';
import { UrlConfig } from '@/router/index';
import TrainingDraft from './draft';
import localStore from 'storejs';

export default {
	name: 'TrainingGeneration',
	components: {
		TrainingDraft
	},
	data() {
		return {
			skinCodeList: [],
			trainingTypeList: [],
			prdTypeList: [],
			trainingOperateTypeMap: {},
			pagerConfig: {
				pageSize: 'pageSize',
				pageIndex: 'pageNum'
			},
			queryForm: {
				labelWidth: '120px',
				queryObject: {
					prdCode: {
						type: 'select',
						label: this.$t('lesson.product'),
						change: this.prdChoose,
						config: {
							data: []
						}
					},
					type: {
						type: 'select',
						label: this.$t('lesson.trainingType'),
						change: this.typeChoose,
						config: {
							data: []
						}
					},
					operateType: {
						type: 'select',
						label: this.$t('lesson.operationType'),
						config: {
							data: []
						}
					},
					generateType: {
						type: 'select',
						label: this.$t('lesson.automaticOrManual'),
						config: {
							data: [{ value: '02', label: this.$t('lesson.manual') }, { value: '01', label: this.$t('lesson.automatic') }]
						}
					},
					name: {
						type: 'text',
						label: this.$t('lesson.trainingName')
					}
				}
			},
			queryList: {
				query: this.queryFunction,
				selectCheckShow: false,
				indexShow: true,
				columns: [
					{
						title: this.$t('lesson.trainingName'),
						prop: 'name'
					},
					{
						title: this.$t('lesson.skinType'),
						prop: 'skinCode',
						type: 'tag',
						columnValue: (row) => { return this.$convertField(row.skinCode, this.skinCodeList, ['code', 'name']); },
						tagType: (row) => { return ''; }
					},
					{
						title: this.$t('lesson.product'),
						prop: 'prdCode',
						type: 'tag',
						columnValue: (row) => { return this.$convertField(row.prdCode, this.prdTypeList, ['code', 'name']); },
						tagType: (row) => { return 'success'; }
					},
					{
						title: this.$t('lesson.trainingType'),
						prop: 'type',
						type: 'tag',
						columnValue: (row) => { return this.$convertField(row.type, this.trainingTypeList, ['code', 'name']); },
						tagType: (row) => { return 'success'; }
					},
					{
						title: this.$t('lesson.operationType'),
						prop: 'operateType',
						type: 'tag',
						columnValue: (row) => { return this.$convertField(row.operateType, this.trainingOperateTypeMap[row.type], ['code', 'name']); },
						tagType: (row) => { return 'success'; }
					},
					{
						title: this.$t('lesson.minDuration'),
						prop: 'minDuration'
					},
					{
						title: this.$t('lesson.maxDuration'),
						prop: 'maxDuration'
					},
					{
						title: this.$t('lesson.remarks'),
						prop: 'remarks'
					},
					{
						type: 'button',
						title: this.$t('global.operate'),
						width: '250',
						buttons: [
							{
								name: this.$t('lesson.demonstration'),
								handleClick: this.demoDisplay,
								type: ''
							},
							{
								name: this.$t('lesson.trainingRecord'),
								handleClick: this.trainingRecord,
								type: ''
							}
						]
					}
				],
				actions: [
					{ text: this.$t('lesson.generateTraining'), btnCode: 'employee_auto', handler: this.autoMaticTrainging },
					{ text: this.$t('lesson.updateTraining'), btnCode: 'employee_edit', handler: this.editTrainingByType, type: 'warning'},
					{ text: this.$t('lesson.deleteTraining'), btnCode: 'employee_delete', handler: this.delAutoMaticTrainging, type: 'danger'},
					{ text: this.$t('lesson.addTraining'), btnCode: 'employee_add', handler: this.addingTraining, type: 'primary' }
				]
			},

			currentModel: {}
		};
	},
	async created() {
		await this.loadInitData();
		const json = localStore.get(this.$route.path);
		json.type = '';
		json.prdCode = '';
		json.operateType = '';
	},
	methods: {
		async loadInitData() {
			this.skinCodeList = [];
			this.queryForm.queryObject.prdCode.config.data = [];
			getSkinCodeList().then(response => {
				this.skinCodeList = response.data;
			});
			getCommodityMapProduct(this.$route.params.skinCode).then((response) => {
				const productList = response.data;
				if (productList && productList.length > 0) {
					productList.forEach(elem => {
						// 过滤综合演练产品
						if (elem.prdType != '03') {
							this.queryForm.queryObject.prdCode.config.data.push({ value: elem.code, label: elem.name });
						}
					});
				}
			});

			this.prdTypeList = [];
			getProductList({ pageSize: 500, pageNum: 1 }).then(res => {
				const list = res.data.list;
				if (list && list.length > 0) {
					this.prdTypeList = list.filter(elem => { return elem.prdType != '03'; });
				}
			});

			// 获取实训类型
			this.trainingTypeList = [];
			this.$Dictionary.trainingType().then(list => {
				this.trainingTypeList = list;
				list.forEach(elem => {
					this.queryForm.queryObject.type.config.data.push({ value: elem.code, label: elem.name });
				});
			});

			this.trainingOperateTypeMap = {};
			const list01 = await this.$Dictionary.stationControl();
			this.trainingOperateTypeMap['01'] = list01; // 控制权实训
			const list02 = await this.$Dictionary.signalOperation();
			this.trainingOperateTypeMap['02'] = list02; // 信号机实训
			const list03 = await this.$Dictionary.switchOperation();
			this.trainingOperateTypeMap['03'] = list03; // 道岔实训
			const list04 = await this.$Dictionary.sectionOperation();
			this.trainingOperateTypeMap['04'] = list04; // 区段实训
			const list05 = await this.$Dictionary.stationStandOperation();
			this.trainingOperateTypeMap['05'] = list05; // 站台实训
			const list06 = await this.$Dictionary.trainPlanOperation();
			this.trainingOperateTypeMap['06'] = list06; // 行车计划实训
			const list07 = await this.$Dictionary.trainOperation();
			this.trainingOperateTypeMap['07'] = list07; // 列车实训
			const list08 = await this.$Dictionary.limitOperation();
			this.trainingOperateTypeMap['08'] = list08; // 限速实训
			this.reloadTable();
		},
		prdChoose(form) {
			form.type = '';
			form.operateType = '';
		},
		typeChoose(form) {
			this.queryForm.queryObject.operateType.config.data = [];
			form.operateType = '';
			if (form && form.type) {
				this.trainingOperateTypeMap[form.type].forEach(elem => {
					this.queryForm.queryObject.operateType.config.data.push({ value: elem.code, label: elem.name });
				});
			}
		},
		autoMaticTrainging() {
			this.$refs.draftTrain.show({ event: '01', title: this.$t('lesson.automaticGenerationOfTraining') });
		},
		editTrainingByType() {
			this.$refs.draftTrain.show({ event: '02', title: this.$t('lesson.modifyTrainingByCategory') });
		},
		delAutoMaticTrainging() {
			this.$refs.draftTrain.show({ event: '03', title: this.$t('lesson.deleteAutoGeneratedTraining') });
		},
		addingTraining() {
			this.$refs.draftTrain.show({ event: '04', title: this.$t('lesson.addTraining') });
		},
		demoDisplay(index, node) {
			trainingNotify({ trainingId: node.id }).then(resp => {
				/** 区分演示和正式，需要在演示时设置lessonId为0*/
				const query = { group: resp.data, trainingId: node.id, lessonId: 0 };
				this.$router.push({ path: `${UrlConfig.display}/manage`, query: query });
				launchFullscreen();
			}).catch(error => {
				this.$messageBox(this.$t('error.createSimulationFailed') +error.message);
			});
		},
		reloadTable() {
			this.queryList.reload();
		},
		turnback() {
			this.$router.go(-1);
		},
		trainingRecord(index, node) {
			trainingNotify({ trainingId: node.id }).then(resp => {
				this.group = resp.data;
				this.$router.push({ path: `${UrlConfig.design.trainingRecord}/${node.id}/${node.name}`, query: { group: resp.data } });
			}).catch(error => {
				this.$messageBox(`${this.$t('error.createSimulationFailed')}: ${error.message}`);
			});
		},
		queryFunction(params) {
			params['mapId'] = this.$route.query.mapId;
			return pageQueryTraining(params);
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .draft {
        width: 400px;
        text-align: center;
        margin: 20px auto;
    }
</style>
