<template>
  <el-dialog
    v-dialogDrag
    class="planEdit__tool add-task"
    :title="title"
    :visible.sync="dialogShow"
    width="880px"
    :before-close="doClose"
    :z-index="2000"
    top="50px"
    :modal="false"
    :close-on-click-modal="false"
  >
    <el-row>
      <el-col :span="3" style="height: 28px;line-height: 28px;">
        <el-radio v-model="addModel.forward" :label="true">{{ $t('planMonitor.addToTheFront') }}</el-radio>
      </el-col>
      <el-col :span="3" style="margin-left: 10px;height: 28px;line-height: 28px;">
        <span>{{ $t('planMonitor.tripNumber')+$t('global.colon') }}</span>
      </el-col>
      <el-col :span="5">
        <el-select v-model="addModel.tripNumber" size="mini" :placeholder="this.$t('global.choose')">
          <el-option
            v-for="item in tripNumberList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-col :span="3" style="margin-left: 20px;height: 28px;line-height: 28px;">
        <span>{{ $t('global.startTime')+$t('global.colon') }}</span>
      </el-col>
      <el-col :span="5">
        <el-time-picker v-model="addModel.startTime" size="mini" value-format="HH:mm:ss" :clearable="false" />
      </el-col>
    </el-row>
    <el-row style="margin-top: 5px;height: 28px;line-height: 28px;">
      <el-col :span="3">
        <el-radio v-model="addModel.forward" :label="false">{{ $t('planMonitor.addToTheEnd') }}</el-radio>
      </el-col>
      <el-col :span="3" style="margin-left: 10px;height: 28px;line-height: 28px;">
        <span>{{ $t('planMonitor.defaultStopTime') }}</span>
      </el-col>
      <el-col :span="5">
        <el-input-number v-model="defaultStopTime" placeholder="请输入时间" size="mini" :controls="false" :min="0" />
        <!-- <el-select v-model="defaultStopTime" size="mini" :placeholder="this.$t('global.choose')">
          <el-option
            v-for="item in defaultStopTimeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
      </el-col>
      <el-col :span="3" style="margin-left: 20px;height: 28px;line-height: 28px;">
        <span>{{ $t('planMonitor.defaultRunLevel') }}</span>
      </el-col>
      <el-col :span="5">
        <el-select v-model="defaultSpeedLevel" size="mini" :placeholder="this.$t('global.choose')">
          <el-option
            v-for="item in defaultSpeedLevelList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>

    </el-row>
    <el-row style="margin-bottom: 5px;">
      {{ $t('planMonitor.crossRailway')+$t('global.colon') }}
    </el-row>
    <el-row>
      <el-table
        :data="routingList"
        border
        highlight-current-row
        :height="230"
        @row-click="handleClick"
      >
        <el-table-column
          prop="startStationCode"
          :label="this.$t('planMonitor.startingStation')"
          :filters="startStationFilters"
          :filter-method="filterStartStation"
          column-key="startStationCode"
        >
          <template slot-scope="scope">
            {{ formatName(scope.row.startStationCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="startSectionCode" :label="this.$t('planMonitor.startingSection')" width="95">
          <template slot-scope="scope">
            {{ formatName(scope.row.startSectionCode) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="endStationCode"
          :label="this.$t('planMonitor.terminal')"
          :filters="endStationFilters"
          :filter-method="filterEndStation"
          column-key="endStationCode"
        >
          <template slot-scope="scope">
            {{ formatName(scope.row.endStationCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="endSectionCode" :label="this.$t('planMonitor.endingSection')" width="95">
          <template slot-scope="scope">
            {{ formatName(scope.row.endSectionCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="remarks" :label="this.$t('planMonitor.description')" width="315" />
      </el-table>
    </el-row>
    <el-row style=" margin-bottom: 5px;margin-top: 10px;">
      {{ '经停转换轨 / 站台轨'+$t('global.colon') }}
    </el-row>
    <el-row>
      <el-table :data="addModel.arriveConfigList" border :height="230">
        <el-table-column prop="stationCode" :label="this.$t('planMonitor.station')" width="160">
          <template slot-scope="scope">
            {{ formatName(scope.row.stationCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="sectionCode" :label="this.$t('planMonitor.section')" width="95">
          <template slot-scope="scope">
            {{ formatName(scope.row.sectionCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="arriveTime" :label="this.$t('planMonitor.arriveTime')" width="100px" />
        <!-- prop="stopTime"  -->
        <el-table-column :label="this.$t('planMonitor.stopTime')" width="100px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.stopTime" placeholder="请输入时间" size="mini" @input="changeStopTime(scope.$index, scope.row.stopTime)" />
          </template>
        </el-table-column>
        <el-table-column prop="departureTime" :label="this.$t('planMonitor.departureTime')" width="100px" />
        <el-table-column :label="this.$t('planMonitor.runLevel')">
          <template slot-scope="scope">
            <span style="font-size:13px;">{{ scope.row.speedLevel }}</span>
            <el-input v-model="scope.row.speedLevelTime" style="width:70px" placeholder="请输入运行等级" size="mini" @input="changeSpeedLevelTime(scope.$index, scope.row.speedLevelTime)" />
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-col :offset="16">
        <el-checkbox v-model="showDefault">{{ $t('planMonitor.showDefaultStopTimeAndRunLevel') }}</el-checkbox>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button size="medium" @click="doClose">{{ $t('global.cancel') }}</el-button>
      <el-button type="primary" size="medium" @click="handleCommit">{{ $t('global.confirm') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getRoutingList, addPlanTrip, getMapStationRun } from '@/api/runplan';
import { formatTime, formatName } from '@/utils/runPlan';

export default {
    name: 'AddTask',
    components: {
    },
    data() {
        return {
            dialogShow: false,
            loading: false,
            isPlan: false,
            showDefault: true,
            stopStationMap: {},
            params: {},
            routingList: [],
            startStationFilters:[],
            endStationFilters:[],
            defaultStopTime: '30',
            defaultSpeedLevel: 'l3',
            addModel: {
                forward: false,
                routingCode: '',
                endStationCode: '',
                startStationCode: '',
                startTime: '00:00:00',
                endTime: '',
                arriveConfigList: [],
                tripNumber: '',
                planId: '',
                serviceNumber: ''
            },
            tripNumberList: [{ value: '', label: this.$t('planMonitor.automatic') }],
            // defaultStopTimeList: [{ value: '30', label: this.$t('planMonitor.default') }, { value: '0', label: '0' }],
            defaultSpeedLevelList: [
                { value: 'l1', label: '等级一' },
                { value: 'l2', label: '等级二' },
                { value: 'l3', label: '等级三'},
                { value: 'l4', label: '等级四' },
                { value: 'l5', label: '等级五' }
            ]
        };
    },
    computed: {
        title() {
            return this.$t('planMonitor.addTask');
        }
    },
    watch: {
        'addModel.routingCode': function (val) {
            if (val) {
                this.computedDetailList('routingCode');
            }
        },
        'addModel.startTime': function () {
            this.computedDetailList();
        },
        'defaultStopTime': function () {
            this.computedDetailList('defaultStopTime');
        },
        'defaultSpeedLevel': function () {
            this.computedDetailList('defaultSpeedLevel');
        }
    },
    methods: {
        loadInitData(params) {
            this.isPlan = params.isPlan;
            // this.addModel.taskIndex = getUID('task_');
            this.addModel.serviceNumber = params.serviceNumber;
            this.addModel.planId = this.$route.query.planId;
            this.addModel.arriveConfigList = [];
            const planId = this.$route.query.planId;
            if (planId) {
                getRoutingList(planId).then(resp => {
                    this.routingList = resp.data;
                    // debugger;
                    const startStationFilterMap = {};
                    const endStationFilterMap = {};
                    this.routingList.forEach(routing=>{
                        if (!startStationFilterMap[routing.startStationCode]) {
                            startStationFilterMap[routing.startStationCode] = {text:formatName(routing.startStationCode), value:routing.startStationCode};
                        }
                        if (!endStationFilterMap[routing.endStationCode]) {
                            endStationFilterMap[routing.endStationCode] = {text:formatName(routing.endStationCode), value:routing.endStationCode};
                        }
                        let length = routing.parkSectionCodeList.length;
                        if ( length >= 4) {
                            if (routing.parkSectionCodeList[0].stationCode == routing.parkSectionCodeList[1].stationCode) {
                                // routing.startSectionCode = routing.parkSectionCodeList[1].sectionCode;
                                routing.parkSectionCodeList.shift();
                            }
                            length = routing.parkSectionCodeList.length;
                            if (routing.parkSectionCodeList[length - 1].stationCode == routing.parkSectionCodeList[length - 2].stationCode) {
                                // routing.endSectionCode = routing.parkSectionCodeList[length - 2].sectionCode;
                                routing.parkSectionCodeList.pop();
                            }
                        }
                    });
                    this.startStationFilters = Object.values(startStationFilterMap);
                    this.endStationFilters = Object.values(endStationFilterMap);
                });
            }

            const mapId = this.$route.query.mapId;
            if (mapId) {
                getMapStationRun(mapId).then(resp =>{
                    const list = resp.data;
                    list.forEach(elem => {
                        this.stopStationMap[[elem.startSectionCode, elem.endSectionCode].toString()] = elem;
                    });
                    // if (list && list.length) {
                    //     list.forEach(elem => {
                    //         if (!elem.runPlanLevelVO) {
                    //             this.$alert(`${this.$t('planMonitor.tipOperationTime')}`, {
                    //                 confirmButtonText: this.$t('global.confirm'),
                    //                 callback: action => {
                    //                     this.doClose();
                    //                 }
                    //             });
                    //         }
                    //     });
                    // }
                });
            }
        },
        doShow(params) {
            this.loadInitData(params);
            this.dialogShow = true;
        },
        filterStartStation(value, row) {
            return row.startStationCode == value;
        },
        filterEndStation(value, row) {
            return row.endStationCode == value;
        },
        doClose() {
            this.loading = false;
            this.dialogShow = false;
        },
        formatName(code) {
            return formatName(code);
        },
        computedTimeByString(timeStr) {
            const bTime = +new Date(`2019-01-01 00:00:00`);
            const eTime = +new Date(`2019-01-01 ${timeStr}`);
            return Number(eTime) - Number(bTime);
        },
        compuntedRunTime(list, index, runLevel) {
            let runTime = 0;
            if (index < list.length - 1) {
                const stopStationObj = this.stopStationMap[[list[index].sectionCode, list[index + 1].sectionCode].toString()];
                if (stopStationObj) {
                    if (stopStationObj.runPlanLevelVO) {
                        runTime = parseInt(stopStationObj.runPlanLevelVO[runLevel]);
                    } else if (stopStationObj[runLevel]) {
                        runTime = parseInt(stopStationObj[runLevel]);
                    } else {
                        this.$messageBox(this.$t('planMonitor.addTaskHint1') + stopStationObj.startSectionCode + this.$t('planMonitor.addTaskHint2') + stopStationObj.endSectionCode + this.$t('planMonitor.addTaskHint3'));
                    }
                }
            }
            return runTime;
        },
        changeSpeedLevelTime(indexs, speedLevelTime) {
            const arriveConfigList = Object.assign([], this.addModel.arriveConfigList);
            let tempTime = this.computedTimeByString(this.addModel.startTime) / 1000;
            arriveConfigList.forEach((elem, index) => {
                elem.arriveTime = index ? formatTime(tempTime) : '';
                if (index == indexs) { elem.speedLevelTime = speedLevelTime ? Number(speedLevelTime) : 0; }
                elem.arriveTime = index ? formatTime(tempTime) : '';
                if (index > 0) {
                    elem.departureTime = index == arriveConfigList.length - 1 ? '' : formatTime(tempTime + elem.stopTime);
                } else {
                    elem.departureTime = formatTime(tempTime);
                }
                const realRunlevel = elem.speedLevelTime;
                if (index > 0) {
                    tempTime = tempTime + elem.stopTime + realRunlevel;
                } else {
                    tempTime = tempTime + realRunlevel;
                }
            });
            this.addModel.arriveConfigList = arriveConfigList;
            this.addModel.endTime = formatTime(tempTime - this.addModel.arriveConfigList[this.addModel.arriveConfigList.length - 1].stopTime);
        },
        changeStopTime(indexs, time) {
            let tempTime = this.computedTimeByString(this.addModel.startTime) / 1000;
            // const runLevel = this.defaultSpeedLevel || 'l3'; // 默认等级三
            const arriveConfigList = Object.assign([], this.addModel.arriveConfigList);
            arriveConfigList.forEach((elem, index) => {
                if (index == indexs) { elem.stopTime = time ? Number(time) : 0; }
                elem.arriveTime = index ? formatTime(tempTime) : '';
                // const runLevelObj = this.defaultSpeedLevelList.find(speedLevel=>{ return speedLevel.value == runLevel; });
                // elem.speedLevel = this.defaultSpeedLevel == 'l3' ? `${this.$t('planMonitor.default')}(${runLevelObj.label})` : runLevelObj.label;
                if (index > 0) {
                    elem.departureTime = index == arriveConfigList.length - 1 ? '' : formatTime(tempTime + elem.stopTime);
                } else {
                    elem.departureTime = formatTime(tempTime);
                }
                const realRunlevel = elem.speedLevelTime;
                if (index > 0) {
                    tempTime = tempTime + elem.stopTime + realRunlevel;
                } else {
                    tempTime = tempTime + realRunlevel;
                }
            });
            this.addModel.arriveConfigList = arriveConfigList;
            this.addModel.endTime = formatTime(tempTime - this.addModel.arriveConfigList[this.addModel.arriveConfigList.length - 1].stopTime);
        },
        computedDetailList(type = null) {
            if (this.addModel.routingCode) {
                const list = Object.assign([], this.addModel.arriveConfigList);
                let tempTime = this.computedTimeByString(this.addModel.startTime) / 1000;
                const runLevel = this.defaultSpeedLevel || 'l3'; // 默认等级三
                list.forEach((elem, index) => {
                    if (type == 'defaultStopTime' || type == 'routingCode') {
                        elem.stopTime = parseInt(this.defaultStopTime);
                    }
                    elem.arriveTime = index ? formatTime(tempTime) : '';
                    if (index > 0) {
                        elem.departureTime = index == list.length - 1 ? '' : formatTime(tempTime + elem.stopTime);
                    } else {
                        elem.departureTime = formatTime(tempTime);
                    }
                    const runLevelObj = this.defaultSpeedLevelList.find(speedLevel=>{ return speedLevel.value == runLevel; });
                    if (!elem.speedLevelTime || type == 'defaultSpeedLevel') {
                        const realRunlevel = this.compuntedRunTime(list, index, runLevel);
                        elem.speedLevelTime = realRunlevel;
                    }
                    elem.speedLevel = this.defaultSpeedLevel == 'l3' ? `${this.$t('planMonitor.default')}(${runLevelObj.label})` : runLevelObj.label;
                    if (index > 0) {
                        tempTime = tempTime + elem.stopTime + elem.speedLevelTime;
                    } else {
                        tempTime = tempTime + elem.speedLevelTime;
                    }

                });
                this.addModel.endTime = formatTime(tempTime - list[list.length - 1].stopTime);
            }
        },
        handleClick(row, column, event) {
            const arriveConfigList = [];
            row.parkSectionCodeList.forEach((parkSectionCode, index)=>{
                arriveConfigList.push({arriveTime:'', departureTime:'', sectionCode:parkSectionCode.sectionCode, stationCode:parkSectionCode.stationCode});
            });
            this.$set(this.addModel, 'arriveConfigList', arriveConfigList);
            // this.addModel.startStationCode = row.startStationCode;
            // this.addModel.endStationCode = row.endStationCode;
            // this.addModel.endSectionCode = row.endSectionCode;
            // this.addModel.startSectionCode = row.startSectionCode;
            this.addModel.routingCode = row.code;
            this.computedDetailList('routingCode');
        },
        handleCommit() {
            if (this.isPlan) {
                // 计划添加任务
                this.$emit('dispatchOperate', { dialogName: 'editPlanningTrain', operate: 'handleConfirmAddTask', params: Object.assign({}, this.addModel) });
                this.addModel.routingCode = '';
            } else {
                // 直接添加任务
                delete this.addModel.tripNumber;
                addPlanTrip(this.addModel).then(resp => {
                    // this.$emit('dispatchOperate', {
                    // 	dialogName: 'openRunPlan', operate: 'loadRunPlanData', params: Object.assign({refresh: true}, this.$route.query)
                    // });
                    this.$emit('refresh');
                    this.$message.success(this.$t('tip.addTaskSuccessfully'));
                }).catch(() => {
                    this.$messageBox(this.$t('tip.addTaskFailed'));
                });
            }

            this.doClose();
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    @import "src/styles/mixin.scss";

    /deep/ {
        .el-row {
            margin-bottom: 5px !important;
        }
    }

	.add-task{
		/deep/ {
			.el-dialog__body{
				padding: 0 20px;
			}
			.dialog-footer{
				display: flex;
				justify-content: center;
			}
		}
	}
</style>
