<template>
  <div style="width: 100%;height: 100%">
    <div style="position: absolute;top: 61px;width: 100%;background: #fff;z-index: 9;height: 90px;">
      <el-row>
        <div class="title-text">场景语音训练结果</div>
      </el-row>
      <el-row>
        <el-col :span="6" :offset="1">
          <span>用户：</span>
          <el-select v-model="userId" size="mini" filterable placeholder="请选择">
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-col>
        <el-col :span="4" :offset="13">
          <el-button size="mini" type="primary" @click="queryData">查询</el-button>
          <el-button size="mini" type="primary" @click="goBack">返回</el-button>
        </el-col>
      </el-row>
    </div>
    <el-table v-loading="loading" :data="actionList" border style="width:96%;margin: 90px auto 0;" :span-method="objectSpanMethod">
      <el-table-column label="动作id" width="70" prop="id" />
      <el-table-column label="动作内容" width="350">
        <template slot-scope="scope">
          <!-- v-model="scope.row.id"  -->
          <el-checkbox v-if="isModify" v-model="checkBoxActionList[scope.row.id].status" :disabled="checkBoxActionList[scope.row.id].disabled" class="checkBoxAction" @change="((val)=>{changeSelectActionId(val, scope.row.id, scope.$index)})" />
          <el-radio v-if="isOperate" v-model="radioBoxAction" :label="scope.row.id" name="operateAction" class="checkBoxAction" @change="((val)=>{changeSelectRadioActionId(val, scope.row.id, scope.$index)})">{{ '' }}</el-radio>
          <div>{{ covert(scope.row) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="语音识别关键词列表" width="350">
        <template v-if="scope.row.type=='Conversation'&&scope.row.memberId=='1'" slot-scope="scope">
          <div v-if="commandEvaluationRuleVOs[scope.row.id]&&commandEvaluationRuleVOs[scope.row.id].keyWords">
            <el-tag v-for="(tag,index) in commandEvaluationRuleVOs[scope.row.id].keyWords" :key="index" :disable-transitions="false">{{ tag }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="转译结果" prop="result" />
      <el-table-column label="错误关键字">
        <template slot-scope="scope">
          <el-tag v-for="(tag,index) in scope.row.wrongKeyWords" :key="index" :disable-transitions="false">{{ tag }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="错误发音">
        <template slot-scope="scope">
          <el-tag v-for="(tag,index) in scope.row.wrongTripNumbers" :key="index" :disable-transitions="false">{{ tag }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80">
        <template slot-scope="scope">
          <el-button v-if="scope.row.recordId" type="text" @click="checkAudio(scope.row,scope.$index)">重新校验</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {getScriptByIdNew} from '@/api/script';
import { getCompetitionPracticalSceneById } from '@/api/competition';
import { loadMapDataById } from '@/utils/loaddata';
import ConstConfig from '@/scripts/ConstConfig';
import Cookies from 'js-cookie';
import {covertOperate} from '@/views/newMap/displayNew/scriptDisplay/component/covertOperation';
import { audioFilesCheck, getHavaAudoUserList, audioFilesCheckAllSence } from '@/api/competition';
export default {
    name: 'VoiceTraining',
    data() {
        return {
            actionList:[],
            startArray: [],
            endArray: [],
            jsonData: '',
            stepVOs: {},
            memberList: [],
            isModify:false,
            isOperate:false,
            commandEvaluationRuleVOs:{},
            audioDataMap: {},
            userList: [],
            userId: '',
            resultMap: {},
            loading: false
        };
    },
    watch: {
        '$store.state.map.mapDataLoadedCount': function (val) {
            this.parseMember();
        }
    },
    mounted() {
        this.initFunction();
    },
    methods: {
        async initFunction() {
            this.loading = true;
            const userListData = await getHavaAudoUserList(this.$route.query.sceneId);
            this.userList = userListData.data;
            if (this.userList.length) {
                this.userId = this.userList[0].id;
                this.queryData();
            }
            const scriptData = await getScriptByIdNew(this.$route.query.scriptId);
            const dispatcher = scriptData.data.memberList.find(member => member.type === 'DISPATCHER');
            this.actionList = scriptData.data.actionList.filter(action => {
                action.wrongKeyWords = [];
                action.wrongTripNumbers = [];
                action.result = '';
                action.recordId = '';
                return action.type === 'Conversation' && action.memberId == dispatcher.id;
            });
            this.jsonData = scriptData;
            const competitionData = await getCompetitionPracticalSceneById(this.$route.query.sceneId);
            const commandEvaluationRuleVOs = {};
            if (competitionData.data.commandEvaluationRuleVOs) {
                competitionData.data.commandEvaluationRuleVOs.forEach(data=>{
                    commandEvaluationRuleVOs[data.actionId] = data;
                });
            }
            const stepVOs = {};
            if (competitionData.data.stepVOs) {
                competitionData.data.stepVOs.forEach(data=>{
                    stepVOs[data.startActionId] = data;
                    const dataIndex = this.actionList.findIndex((value, index, arr)=>{ return value.id == data.startActionId; });
                    const dataIndex1 = this.actionList.findIndex((value, index, arr)=>{ return value.id == data.endActionId; });
                    this.startArray.push(dataIndex);
                    this.endArray.push(dataIndex1);
                });
            }
            this.commandEvaluationRuleVOs = commandEvaluationRuleVOs;
            this.stepVOs = stepVOs;
            loadMapDataById(scriptData.data.mapId, 'parse');
        },
        queryData() {
            if (this.userId) {
                this.loading = true;
                audioFilesCheckAllSence(this.$route.query.sceneId, this.userId).then(resp => {
                    (resp.data || []).forEach(elem => {
                        this.actionList.forEach(item => {
                            if (elem.actionId === item.id) {
                                item.result = elem.result;
                                item.wrongKeyWords = elem.keyWords;
                                item.wrongTripNumbers = elem.tripNumbers;
                                item.recordId = elem.recordId;
                            }
                        });
                    });
                    this.loading = false;
                }).catch(() => {
                    this.loading = false;
                    this.$message.error('获取校验数据异常！');
                });
            } else {
                this.$message.error('请选择语音录制用户！');
            }
        },
        parseMember() {
            const stationMap = {};
            const stationList = this.$store.state.map.map.stationList;
            stationList.forEach(station=>{
                stationMap[station.code] = station;
            });
            let lastData = JSON.stringify(this.jsonData.data.memberList);
            const roleTypeList = ConstConfig.ConstSelect.roleTypeNew;
            roleTypeList.forEach(function(element) {
                const rolename = element.value;
                if (Cookies.get('user_lang') == 'en') {
                    lastData = lastData.replace(new RegExp(rolename, 'g'), element.enLabel);
                } else {
                    lastData = lastData.replace(new RegExp(rolename, 'g'), element.label);
                }
            });
            lastData = JSON.parse(lastData);
            const lastMemberList = {};
            lastData.forEach((member, index)=>{
                const userName = member.userName ? '-' + member.userName : '';
                const name = member.name ? '-' + member.name : '';
                if (member.deviceCode && member.type == '行值') {
                    const device = stationMap[member.deviceCode];
                    member.deviceName = device.name;
                    member.label = member.type + member.deviceName + name + userName;
                    member.normalName = member.type + member.deviceName + name;
                } else if (member.deviceCode && member.type == '司机') {
                    member.deviceName = member.deviceCode;
                    member.label = member.type + member.deviceName + name + userName;
                } else {
                    member.deviceName = '';
                    member.label = member.type + name + userName;
                    member.normalName = member.type + name;
                }
                lastMemberList[member.id] = member;
                this.memberList = lastMemberList;
            });
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (this.startArray.length > 0) {
                if (columnIndex === 0) {
                    let rowspan = 1;
                    let colspan = 1;
                    for (var i = 0; i < this.startArray.length; i++) {
                        if (rowIndex == this.startArray[i]) {
                            rowspan = this.endArray[i] - this.startArray[i] + 1;
                            colspan = 1;
                        } else if (rowIndex > this.startArray[i] && rowIndex <= this.endArray[i]) {
                            rowspan = 0;
                            colspan = 0;
                        }
                    }
                    return {
                        rowspan:rowspan,
                        colspan:colspan
                    };
                }
            }
        },
        checkAudio(row, index) {
            this.loading = true;
            const commandEvaluationRule = this.commandEvaluationRuleVOs[row.id];
            const params = {
                id: commandEvaluationRule.id,
                actionId: commandEvaluationRule.actionId,
                actionVO: {content: row.content},
                keyWords: commandEvaluationRule.keyWords
            };
            audioFilesCheck(row.recordId, params).then(resp => {
                this.actionList[index].result = resp.data.result;
                this.actionList[index].wrongKeyWords = resp.data.keyWords;
                this.actionList[index].wrongTripNumbers = resp.data.tripNumbers;
                this.loading = false;
            }).catch((e) => {
                this.loading = false;
                this.$message.error('校验语音数据失败！');
            });
        },
        goBack() {
            this.$router.go(-1);
        },
        covert(element) {
            const member = this.memberList[element.memberId] || {};
            let resultData = '';
            if (element.type == 'Accept_Conversation_Invitation') {
                resultData = member.label + '请接受会话邀请';
            } else if (element.type == 'Conversation') {
                resultData = member.label + '说：' + element.content;
            } else if (element.type == 'Operation') {
                resultData = covertOperate(element.operationType, element.operationParamMap);
                resultData = resultData.replace('请', member.label);
                // this.scriptTipMessage = '请找到' + deviceName + '，执行【' + operateName.label + '】操作';
            } else if (element.type == 'Exit_Conversation') {
                resultData = member.label + '结束当前会话';
            } else if (element.type == 'Start_Conversation' ) {
                const inviteMember = [];
                // this.$emit('allowCreatCoversition');
                if (element.communicationObject) {
                    if (element.communicationObject == 'ALL_STATION') {
                        inviteMember.push('所有车站');
                    } else if (element.communicationObject == 'ALL_TRAIN') {
                        inviteMember.push('所有司机');
                    }
                } else {
                    element.conversationMemberIds.forEach(id=>{
                        if (element.memberId != id) {
                            inviteMember.push((this.memberList[id] || {label: ''}).label);
                        }
                    });
                }
                resultData = member.label + '创建会话,选择' + inviteMember.toString();
            } else if (element.type == 'Command') {
                const targetName = this.memberList[element.commandInitiateVO.targetMemberId];
                const CommandList = {
                    Drive_Ahead:'确认运行至前方站',
                    Route_Block_Drive:'进路闭塞法行车',
                    Drive_Through_The_Guide_Signal:'越引导信号行驶',
                    Drive_Through_The_Red_Light:'越红灯行驶',
                    Drive_In_Urm_Mode:'URM模式驾驶',
                    Set_Speed_Limit:'设置限速',
                    Open_Or_Close_Door:'开关门',
                    Switch_Hook_Lock: '道岔钩锁'
                };
                resultData = member.label + '对【' + targetName.label + '】下达【' + CommandList[element.commandInitiateVO.commandType] + '】指令';
            } else if (element.type == 'Drive') {
                if (element.targetSectionCode) {
                    const section = this.$store.getters['map/getDeviceByCode'](element.targetSectionCode);
                    if (section && section.name) {
                        resultData = member.label + '把车开到区段' + section.name;
                    }
                }
            }
            return resultData;
        },

        getUrl(el) {
            return `https://oss.joylink.club/oss/joylink${el.filePath}`;
        },
        covertTime(time) {
            const date = new Date(time);
            let hour = date.getHours();
            let minute = date.getMinutes();
            let second = date.getSeconds();
            hour = hour > 9 ? hour : '0' + hour;
            minute = minute > 9 ? minute : '0' + minute;
            second = second > 9 ? second : '0' + second;
            return hour + ':' + minute + ':' + second;
        }
    }
};
</script>

<style lang="scss" scoped>
	.record_progress_bar{
		width: 40px;
		height: 40px;
		position: absolute;
		left: 0;
		top: 0;
		border-radius: 50%;
	}
	.userHeader{margin-bottom: 2px;}
	.userChatTime{font-size: 12px;display:inline-block;}
	.chatContentInClass{
		display: inline-block;
		width: 100%;
		border: 1px solid #f1f1f1;
	}
	.leftUser{
		float: left;
		margin-left: 10px;
		margin-top: 10px;
		display: inline-block;
	}
	.chat-box-footer-create{
		font-size: 16px;
		text-align: center;
		color: #fff;
		position: relative;
		left: 5px;
		top: 6px;
		line-height: 30px;
		cursor: pointer;
		width: 40px;
		height: 40px;
		border-radius: 50%;
		background: green;
		border: none;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.chat-box-footer-send{
		background: #F2F2F2;
		right: 55px;
		cursor: pointer;
		.icon-yuyin{
			color: #333;
			font-size: 24px;
			margin: 0;
		}
		&.active{
			.icon-yuyin{
				color: green;
			}
		}
		.close_icon{
			position: absolute;
			top: 8px;
			left: 45px;
			font-size: 16px;
			color: #333;
			font-weight: 600;
			padding: 3px;
		}
	}
	.deleteRecord{}
	.title-text{
		font-size: 26px;
		height: 50px;
		line-height: 50px;
		width: 100%;
		text-align: center;
	}
</style>
