<template>
  <el-dialog
    v-dialogDrag
    class="planEdit__tool add-task"
    :title="title"
    :visible.sync="dialogShow"
    width="1000px"
    :before-close="doClose"
    :z-index="2000"
    top="50px"
    :modal="false"
    :close-on-click-modal="false"
  >
    <el-row>
      <el-col :span="4">
        <el-row>
          <el-col :span="9" class="lineHeight">
            <span>{{ $t('planMonitor.modifying.tripNumber') }}</span>
          </el-col>
          <el-col :span="15">
            <el-select v-model="editModel.tripNumber" size="mini" style="display: inline-block" :placeholder="$t('planMonitor.modifying.pleaseSelect')">
              <el-option
                v-for="item in tripNumberList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="2">
        <el-row>
          <el-col :offset="8" class="lineHeight">
            <el-checkbox v-model="editModel.trainManual">{{ $t('planMonitor.modifying.manual') }}</el-checkbox>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="6">
        <el-row>
          <el-col :span="11" :offset="1" class="lineHeight">
            <span>{{ $t('planMonitor.modifying.defaultStopTime') }}</span>
          </el-col>
          <el-col :span="12">
            <el-select
              v-model="editModel.defaultStopTime"
              style="display: inline-block"
              size="mini"
              :placeholder="$t('planMonitor.modifying.pleaseSelect')"
            >
              <el-option
                v-for="item in defaultStopTimeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="5">
        <el-row>
          <el-col :span="9" :offset="2" class="lineHeight">
            <span>{{ $t('planMonitor.modifying.serviceNumber') }}</span>
          </el-col>
          <el-col :span="13">
            <el-input v-model="editModel.serviceNumber" size="mini" />
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="7" class="lineHeight">
        <el-row>
          <el-col :span="22" :offset="2">
            <el-row>
              <el-col :span="6">
                <el-checkbox v-model="editModel.clearGuest">{{ $t('planMonitor.modifying.clearGuest') }}</el-checkbox>
              </el-col>
              <el-col :span="8">
                <el-checkbox v-model="editModel.continuationPlan">{{ $t('planMonitor.modifying.continuationPlan') }}</el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-checkbox v-model="editModel.firstTrain">{{ $t('planMonitor.modifying.firstTrain') }}</el-checkbox>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="4">
        <el-row>
          <el-col :span="9" class="lineHeight">
            <span>{{ $t('planMonitor.modifying.serialNumber') }}</span>
          </el-col>
          <el-col :span="15">
            <el-select v-model="editModel.serialNumber" size="mini" style="display: inline-block" :placeholder="$t('planMonitor.modifying.pleaseSelect')">
              <el-option
                v-for="item in serialNumberList"
                :key="item.value"
                :label="item.label"
                :value="editModel.value"
              />
            </el-select>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="2">
        <el-row>
          <el-col :offset="8" class="lineHeight">
            <el-checkbox v-model="editModel.serialManual" size="mini">{{ $t('planMonitor.modifying.manual') }}</el-checkbox>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="6" class="lineHeight">
        <el-row>
          <el-col :span="11" :offset="1">
            <span>{{ $t('planMonitor.modifying.defaultRunLevel') }}</span>
          </el-col>
          <el-col :span="12">
            <el-select
              v-model="editModel.defaultSpeedLevel"
              style="display: inline-block"
              size="mini"
              :placeholder="$t('planMonitor.modifying.pleaseSelect')"
            >
              <el-option
                v-for="item in defaultSpeedLevelList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="5" class="lineHeight">
        <el-row>
          <el-col :span="9" :offset="2">
            <span>{{ $t('planMonitor.modifying.startTime') }}：</span>
          </el-col>
          <el-col :span="13">
            <el-time-picker
              v-model="editModel.startTime"
              :placeholder="$t('planMonitor.modifying.selectTime')"
              value-format="HH:mm:ss"
              size="mini"
              :clearable="false"
            />
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="7" class="lineHeight">
        <el-row>
          <el-col :span="22" :offset="2">
            <el-row>
              <el-col :span="6">
                <el-checkbox v-model="editModel.inStock">{{ $t('planMonitor.modifying.inStock') }}</el-checkbox>
              </el-col>
              <el-col :span="8">
                <el-checkbox v-model="editModel.outStock">{{ $t('planMonitor.modifying.outStock') }}</el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-checkbox v-model="editModel.lastTrain">{{ $t('planMonitor.modifying.lastTrain') }}</el-checkbox>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row style="margin-bottom: 5px;">
      {{ $t('planMonitor.modifying.route') }}
    </el-row>
    <el-row>
      <el-table :data="editModel.routingList" border :height="140">
        <el-table-column prop="startStationCode" :label="$t('planMonitor.modifying.startingStation')">
          <template slot-scope="scope">
            {{ formatName(scope.row.startStationCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="startSectionCode" :label="$t('planMonitor.modifying.startSection')" />
        <el-table-column prop="endStationCode" :label="$t('planMonitor.modifying.endStationTitle')">
          <template slot-scope="scope">
            {{ formatName(scope.row.endStationCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="endSectionCode" :label="$t('planMonitor.modifying.endSection')" />
        <el-table-column prop="remarks" :label="$t('planMonitor.modifying.description')" :width="315" />
        <!-- <el-table-column :width="40" /> -->
      </el-table>
    </el-row>
    <el-row style=" margin-bottom: 5px;margin-top: 10px;">
      {{ $t('planMonitor.modifying.detail') }}
    </el-row>
    <el-row>
      <el-table :data="editModel.arriveConfigList" border :height="260">
        <el-table-column prop="stationCode" :label="$t('planMonitor.modifying.station')">
          <template slot-scope="scope">
            {{ formatName(scope.row.stationCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="sectionCode" :label="$t('planMonitor.modifying.section')">
          <template slot-scope="scope">
            {{ formatName(scope.row.sectionCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="arriveTime" :label="$t('planMonitor.modifying.arrivalTime')" />
        <el-table-column prop="stopTime" :label="$t('planMonitor.modifying.stopTime')" />
        <el-table-column prop="departureTime" :label="$t('planMonitor.modifying.departureTime')" />
        <el-table-column prop="speedLevel" :label="$t('planMonitor.modifying.runLevel')" />
      </el-table>
    </el-row>
    <el-row>
      <el-col :offset="16">
        <el-checkbox v-model="editModel.default">{{ $t('planMonitor.modifying.showDefaultTime') }}</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 { getRoutingBySDTNumber, querySectionListByRouting, updatePlanTrip, getMapStationRun } from '@/api/runplan';
import { formatTime, formatName } from '@/utils/runPlan';

export default {
    name: 'ModifyingTask',
    components: {
    },
    props: {
        loadRunPlanId: {
            type: String,
            default() {
                return '';
            }
        }
    },
    data() {
        return {
            dialogShow: false,
            loading: false,
            isPlan: false,
            PlanConvert: {},
            stopStationMap: {},
            editModel: {
                taskIndex: '',
                routingCode: '',
                defaultStopTime: '',
                defaultSpeedLevel: '',
                tripNumber: '',
                serviceNumber: '',
                startTime: '00:00:00',
                endTime: '',
                routingList: [],
                arriveConfigList: [],

                serialNumber: '',
                trainManual: false,
                serialManual: false,
                clearGuest: false,
                continuationPlan: false,
                firstTrain: false,
                lastTrain: false,
                inStock: false,
                outStock: false
            },
            tripNumberList: [{ value: '', label: this.$t('planMonitor.modifying.automatic') }],
            defaultStopTimeList: [{ value: '', label: this.$t('planMonitor.modifying.default') }],
            defaultSpeedLevelList: [{ value: '', label: this.$t('planMonitor.modifying.default') }],
            serialNumberList: []
        };
    },
    computed: {
        title() {
            return this.$t('planMonitor.modifying.modifyTask');
        },
        isNewMap() {
            return this.$route.path.includes('displayNew');
        }
    },
    watch: {
        'editModel.startTime': function () {
            this.computedDetailList();
        },
        'editModel.defaultStopTime': function () {
            this.computedDetailList();
        },
        'editModel.defaultSpeedLevel': function () {
            this.computedDetailList();
        }
    },
    methods: {
        formatTime(time) {
            return formatTime(time);
        },
        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['l3']) {
                        runTime = parseInt(stopStationObj['l3']);
                    } else {
                        this.$alert(`${this.$t('planMonitor.tipOperationTime')}`, {
                            confirmButtonText: this.$t('global.confirm'),
                            callback: action => {
                                this.doClose();
                            }
                        });
                    }
                }
            }

            return runTime;
        },
        computedDetailList() {
            this.editModel.arriveConfigList = [];
            if (this.editModel.routingCode) {
                querySectionListByRouting({ planId: this.$route.query.planId || this.loadRunPlanId, routingCode: this.editModel.routingCode }).then(rest => {
                    const list = rest.data;
                    const waitTime = this.editModel.defaultStopTime || 30; // 默认三十秒
                    let tempTime = this.computedTimeByString(this.editModel.startTime) / 1000 - 30;
                    const runLevel = this.editModel.defaultSpeedLevel || 'l3'; // 默认等级三
                    list.forEach((elem, index) => {
                        elem.arriveTime = index ? formatTime(tempTime) : '';
                        elem.departureTime = index == list.length - 1 ? '' : formatTime(tempTime + waitTime);
                        elem.stopTime = this.editModel.defaultSpeedLevel || this.$t('planMonitor.modifying.default');
                        elem.speedLevel = this.editModel.defaultStopTime || this.$t('planMonitor.modifying.default');
                        tempTime = tempTime + waitTime + this.compuntedRunTime(list, index, runLevel);
                    });
                    if (this.editModel.routingList && this.editModel.routingList.length > 0) {
                        const row = this.editModel.routingList[0];
                        const startSection = this.$store.getters['map/getDeviceByCode'](row.startSectionCode);
                        if (startSection && startSection.isReentryTrack) {
                            list.shift();
                        }

                        const endSection = this.$store.getters['map/getDeviceByCode'](row.endSectionCode);
                        if (endSection && endSection.isReentryTrack) {
                            list.pop();
                        }
                    }

                    this.editModel.arriveConfigList = list;
                    this.editModel.endTime = formatTime(tempTime - waitTime);
                });
            }
        },
        loadInitData(params) {
            const lineCode = this.$route.query.lineCode;
            const mapId = this.$route.query.mapId;
            this.isPlan = params.isPlan;
            this.editModel.taskIndex = params.taskIndex;
            this.editModel.serviceNumber = params.serviceNumber;
            this.editModel.tripNumber = params.tripNumber;
            this.PlanConvert = this.$theme.loadPlanConvert(lineCode);
            const editData = this.$store.state.runPlan.draftEditData[this.editModel.serviceNumber];
            if (editData) {
                const tripNumberList = Object.keys(editData.trainMap).sort((a, b) => { return editData.trainMap[a].oldIndex - editData.trainMap[b].oldIndex; });
                const trainInfo = editData.trainMap[tripNumberList[0]];
                this.editModel.startTime = formatTime(trainInfo.stationTimeList[0].secondTime + this.PlanConvert.TranslationTime);
            }
            if (mapId) {
                getMapStationRun(mapId).then(resp => {
                    const list = resp.data;
                    list.forEach(elem => {
                        this.stopStationMap[[elem.startSectionCode, elem.endSectionCode].toString()] = elem;
                    });
                });
            }
            const model = {
                planId: this.$route.query.planId || this.loadRunPlanId,
                SDTNumber: `${this.editModel.serviceNumber}${this.editModel.tripNumber}`
            };

            this.editModel.routingList = [];
            getRoutingBySDTNumber(model).then(resp => { // 根据车次号查询交路
                const routingObj = resp.data;
                this.editModel.routingCode = routingObj.code;
                this.editModel.routingList.push(routingObj);
                this.computedDetailList();
            });
        },
        doShow(params) {
            this.loadInitData(params);
            this.dialogShow = true;
        },
        doClose() {
            this.loading = false;
            this.dialogShow = false;
        },
        buildModel() {
            return {
                planId: this.$route.query.planId || this.loadRunPlanId,
                routingCode: this.editModel.routingCode,
                tripNumber: this.editModel.tripNumber,
                startTime: this.editModel.startTime,
                endTime: this.editModel.endTime,
                arriveConfigList: this.editModel.arriveConfigList,
                SDTNumber: `${this.editModel.serviceNumber}${this.editModel.tripNumber}`
            };
        },
        handleCommit() {
            if (this.isPlan) {
                // 计划修改任务
            } else {
                // 直接修改
                updatePlanTrip(this.buildModel()).then(resp => {
                    this.$emit('refresh');
                    this.$message.success(this.$t('planMonitor.modifying.modifyTaskSuccess'));
                }).catch(() => {
                    this.$messageBox(this.$t('planMonitor.modifying.modifyTaskFailed'));
                });
            }
            this.doClose();
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    @import "src/styles/mixin.scss";

    .lineHeight{
        height: 28px;
        line-height: 28px;
    }
    /deep/ {
        .el-row {
            margin-bottom: 5px !important;
        }
    }
    .add-task{
      /deep/ {
        .el-dialog__body{
          padding: 0 20px;
        }
        .el-dialog .el-input {
            width: 120px !important;
        }
        .dialog-footer{
            display: flex;
            justify-content: center;
        }
      }
    }
</style>
