<template>
  <div>
    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="show"
      top="50px"
      width="95%"
      :before-do-close="doClose"
      :close-on-click-modal="false"
      :z-index="2000"
    >
      <div class="scheduling">
        <el-card class="scheduling_header">
          <el-form>
            <el-row>
              <el-col :span="6">
                <el-form-item :label="$t('display.schedule.scheduleSelect')">
                  <el-date-picker
                    v-model="formModel.planDate"
                    clearable
                    size="small"
                    type="date"
                    value-format="yyyy-MM-dd"
                    @change="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="$t('display.schedule.runDiagramName')">
                  <el-select v-model="formModel.runPlanName" size="small" style="display: inline-block">
                    <el-option
                      v-for="item in runPlanList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="$t('display.schedule.scheduleMode')">
                  <div>{{ formModel.mode }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item style="text-align: right">
                  <el-button-group>
                    <el-button size="small" type="warning" @click="handleCheck">{{ $t('display.schedule.check') }}</el-button>
                    <el-button size="small" type="primary" @click="handleSave">{{ $t('display.schedule.save') }}</el-button>
                  </el-button-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <div class="scheduling_body">
          <div class="scheduling_body-table">
            <edit-table ref="table" v-loading="loading" border stripe :table-data="tableData" :table-form="tableForm" :row-style="handleRowStyle" />
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { querySecheduling, generateScheduling, getSchedulingAllTrains, checkScheduling, saveScheduling, generateSchedulingAgain } from '@/api/scheduling';
import { hexColor } from '@/utils/runPlan';
import EditTable from '@/views/components/editTable/index';

// 排班计划弹窗列表
export default {
    name: 'AddQuest',
    components: {
        EditTable
    },
    props: {
        group: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            show: false,
            loading: false,
            runPlanList: [],
            groupNumberList: [],
            formModel: {
                id: '',
                mode: '',
                planDate: '',
                runPlanName: ''
            },
            tableForm: {
                index: true,
                columns: [
                    {
                        title: this.$t('display.schedule.driverNumber'),
                        prop: 'driverCode',
                        type: 'text'
                    },
                    {
                        title: this.$t('display.schedule.trainNumber'),
                        prop: 'trainCode',
                        type: 'select',
                        width: '150',
                        options: () => { return this.groupNumberList; },
                        editable: true,
                        editing: true
                    },
                    {
                        title: this.$t('display.schedule.onlineSection'),
                        prop: 'onlineSection',
                        type: 'text'
                    },
                    {
                        title: this.$t('display.schedule.onlineServerNumber'),
                        prop: 'onlineServerNumber',
                        type: 'text'
                    },
                    {
                        title: this.$t('display.schedule.onlineTargetNumber'),
                        prop: 'onlineTargetNumber',
                        type: 'text'
                    },
                    {
                        title: this.$t('display.schedule.onlineTime'),
                        prop: 'onlineTime',
                        type: 'text'
                    },
                    {
                        title: this.$t('display.schedule.onlineTripNumber'),
                        prop: 'onlineTripNumber',
                        type: 'text',
                        format: (row) => { return `${row.onlineDirectionCode}${row.onlineTripNumber}`; }
                    },
                    {
                        title: this.$t('display.schedule.outDepot'),
                        prop: 'outDepot',
                        type: 'text'
                    },
                    {
                        title: this.$t('display.schedule.outDepotStatus'),
                        prop: 'outStatus',
                        type: 'tag',
                        columnValue: (row) => { return this.$ConstSelect.translate(row.outStatus, 'Whether'); },
                        tagType: (row) => {
                            switch (row.outStatus) {
                            case true: return 'success';
                            case false: return 'danger';
                            }
                        }
                    },
                    {
                        title: this.$t('display.schedule.offlineSection'),
                        prop: 'offlineSection',
                        type: 'text'
                    },
                    {
                        title: this.$t('display.schedule.offlineServerNumber'),
                        prop: 'offlineServerNumber',
                        type: 'text'
                    },
                    {
                        title: this.$t('display.schedule.offlineTargetNumber'),
                        prop: 'offlineTargetNumber',
                        type: 'text'
                    },
                    {
                        title: this.$t('display.schedule.offlineTime'),
                        prop: 'offlineTime',
                        type: 'text'
                    },
                    {
                        title: this.$t('display.schedule.offlineTripNumber'),
                        prop: 'offlineTripNumber',
                        type: 'text',
                        format: (row) => { return `${row.offlineDirectionCode}${row.offlineTripNumber}`; }
                    },
                    {
                        title: this.$t('display.schedule.inDepot'),
                        prop: 'inDepot',
                        type: 'text'
                    },
                    {
                        title: this.$t('display.schedule.inDepotStatus'),
                        prop: 'inStatus',
                        type: 'tag',
                        columnValue: (row) => { return this.$ConstSelect.translate(row.inStatus, 'Whether'); },
                        tagType: (row) => {
                            switch (row.inStatus) {
                            case true: return 'success';
                            case false: return 'danger';
                            }
                        }
                    }
                ]
            },
            tableData: []
        };
    },
    computed: {
        title() {
            return this.$t('display.schedule.schedulePlan');
        }
    },
    created() {
        this.loadInitData();
    },
    methods: {
        doShow() {
            this.formModel.day = '';
            this.show = true;
        },
        doClose() {
            this.show = false;
        },
        loadInitData() {
            this.groupNumberList = [];
            getSchedulingAllTrains(this.group).then(resp => {
                this.groupNumberList = resp.data.map(elem => { return {value: elem.code, label: elem.groupNumber}; });
            });
        },
        handleQuery(day) {
            if (day) {
                this.loading = true;
                querySecheduling(this.group, {day}).then(resp => {
                    if (!resp.data) {
                        this.$confirm(this.$t('display.schedule.noSchedulePlan'), this.$t('global.tips'), {
                            confirmButtonText: this.$t('global.confirm'),
                            cancelButtonText: this.$t('global.cancel'),
                            type: 'warning'
                        }).then(() => {
                            this.handleGenerate(day);
                        }).catch(() => {
                            this.clearData();
                            this.loading = false;
                        });
                    } else {
                        this.tableData = this.initTableData(resp.data.planList || []);
                        this.formModel.id = resp.data.id;
                        this.formModel.planDate = resp.data.planDate;
                        this.formModel.runPlanName = resp.data.runPlanName;
                        this.$message.success(`${this.$t('display.schedule.loadData')} ${day} ${this.$t('display.schedule.schedulePlanSuccess')}`);
                        this.loading = false;
                    }
                }).catch(error => {
                    this.clearData();
                    if (error.code == 30002) {
                        this.handleReGenerate(day);
                    } else {
                        this.$messageBox(`${error.message}`);
                        this.loading = false;
                    }
                });
            }
        },
        handleGenerate(day) {
            generateScheduling(this.group, {day}).then(resp => {
                this.loading = false;
                this.tableData = this.initTableData(resp.data.planList || []);
                this.formModel.id = resp.data.id;
                this.formModel.planDate = resp.data.planDate;
                this.formModel.runPlanName = resp.data.runPlanName;
                this.$message.success(this.$t('display.schedule.createSchedulePlanSuccess'));
            }).catch(error => {
                this.loading = false;
                this.clearData();
                this.$messageBox(`${error.message}`);
            });
        },
        handleReGenerate(day) {
            generateSchedulingAgain(this.group).then(resp => {
                this.loading = false;
                this.tableData = this.initTableData(resp.data.planList || []);
                this.formModel.id = resp.data.id;
                this.formModel.planDate = resp.data.planDate;
                this.formModel.runPlanName = resp.data.runPlanName;
                this.$message.success(this.$t('display.schedule.regenerateSchedulePlanSuccess'));
            }).catch(error => {
                this.loading = false;
                this.clearData();
                this.$messageBox(`${error.message}`);
            });
        },
        handleCheck() {
            if (this.formModel.planDate) {
                checkScheduling(this.group, this.tableData).then(resp => {
                    const data = resp.data;
                    this.setConflictList(data.conflictList);
                    if (data.pass) {
                        this.$message.success(this.$t('display.schedule.checkPassed'));
                    } else {
                        this.$message.warning(this.$t('display.schedule.checkFailed'));
                    }
                }).catch(error => {
                    this.$messageBox(`${this.$t('display.schedule.checkSchedulePlanFailed')}: ${error.message}`);
                });
            } else {
                this.$messageBox(this.$t('display.schedule.selectSchedulePlan'));
            }
        },
        handleSave() {
            if (this.formModel.planDate) {
                saveScheduling(this.group, this.tableData).then(resp => {
                    this.$message.success(this.$t('display.schedule.saveSchedulePlanSuccess'));
                }).catch(() => {
                    this.$messageBox(this.$t('display.schedule.saveSchedulePlanFail'));
                });
            } else {
                this.$messageBox(this.$t('display.schedule.selectSchedulePlan'));
            }

        },
        handleRowStyle({rowIndex}) {
            const row = this.tableData[rowIndex];
            return row['$conflict'] ? `background: ${row['$conflict']}` : `background: #fff`;
        },
        setConflictList(list) {
            this.tableData.forEach(elem => { elem['$conflict'] = null; });
            if (list && list.length) {
                list.forEach(idList => {
                    const color = hexColor.colorRandom();
                    this.tableData.forEach(elem => {
                        if (idList.includes(parseInt(elem.id))) {
                            elem['$conflict'] = color;
                        }
                    });
                });
            }
            this.tableData = [...this.tableData];
        },
        initTableData(tableData) {
            tableData.forEach(elem => {
                elem['$conflict'] = null;
            });

            return tableData;
        },
        clearData() {
            this.formModel.planDate = '';
            this.tableData = [];
        }
    }
};
</script>
<style scoped rel="stylesheet/scss" lang="scss">
	.scheduling {
		&_header {
			background: #fff;
			padding: 30px 30px 0;
		}
		&_body {
			margin-top: 30px;
			background: #ffff;
			border: 1px solid #F1F1F1;
			width: 100%;
			overflow: auto;
		}
	}

	/deep/ .el-dialog__body {
		background: #fafafa;
	}

	/deep/ label {
		font-weight: 0;
	}
</style>
