<template>
  <div v-if="dialogVisible" v-quickMenuDrag class="reminder-drag">
    <div style="width: 100%;text-align: center;font-size: 18px;padding-top: 8px;">条件管理</div>
    <i style="position: relative;top: -25px;right: -370px;" class="el-icon-close" @click="handleClose" />
    <el-tabs v-model="activeName">
      <el-tab-pane label="列车触发" name="first">
        <div>
          <el-table
            :data="tableData"
            style="width: 100%"
            height="200px"
          >
            <el-table-column prop="code" label="触发列车" />
            <el-table-column prop="physicalCode" label="到达区段">
              <template slot-scope="scope">
                <span>{{ getSectionName(scope.row.physicalCode) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="stop" label="是否停车">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.stop? 'primary' : 'danger'"
                  disable-transitions
                >{{ scope.row.stop?'是':'否' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column width="150">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-form ref="form" label-width="80px" style="margin-top: 8px;padding: 10px;" :model="formModel" :rules="rules">
            <el-form-item label="触发列车" prop="code">
              <el-select v-model="formModel.code" size="small" filterable placeholder="请选择">
                <el-option
                  v-for="item in trainList"
                  :key="item.code"
                  :label="item.code"
                  :value="item.code"
                />
              </el-select>
              <el-button :type="field === 'triggerTrain'? 'danger': 'primary'" size="small" @click="hover('triggerTrain')">{{ $t('map.activate') }}</el-button>
            </el-form-item>
            <el-form-item label="到达区段" prop="physicalCode">
              <el-select v-model="formModel.physicalCode" size="small" filterable placeholder="请选择">
                <el-option
                  v-for="item in sectionList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
              <el-button :type="field === 'triggerSection'? 'danger': 'primary'" size="small" @click="hover('triggerSection')">{{ $t('map.activate') }}</el-button>
            </el-form-item>
            <el-form-item label="是否停车">
              <el-select v-model="formModel.stop" clearable size="small" placeholder="请选择">
                <el-option
                  v-for="item in stopList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="text-align: center;" label-width="0">
              <el-button v-if="!update" size="small" type="primary" @click="onCommit">添加</el-button>
              <el-button v-if="update" size="small" type="primary" @click="onUpdate">修改</el-button>
              <el-button v-if="update" size="small" @click="initData">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="延时触发" name="second">
        <div style="text-align: center;">
          <div style="display: inline-block;margin-right: 10px;font-size: 14px;">延时条件</div>
          <el-input-number v-model="delay" size="small" controls-position="right" :min="0" />
          <div style="margin-top: 10px;">
            <el-button type="primary" size="mini" @click="onUpdateDelay">修改</el-button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { updateActionCondition } from '@/api/script';
import { mapGetters } from 'vuex';
export default {
    name: 'ConditionManage',
    data() {
        return {
            dialogVisible: false,
            tableData: [],
            stopList: [
                {label: '是', value: 1},
                {label: '否', value: 0}
            ],
            formModel: {
                code: '',
                physicalCode: '',
                stop: 1
            },
            rules: {
                code: [
                    { required: true, message: '请选择触发列车', trigger: 'change' }
                ],
                physicalCode: [
                    { required: true, message: '请选择到达区段', trigger: 'change' }
                ]
            },
            actionId: '',
            update: false,
            updateIndex: '',
            field: '',
            delay: 0,
            activeName: 'first'
        };
    },
    computed: {
        ...mapGetters('map', [
            'trainList',
            'sectionList'
        ])
    },
    watch: {
        '$store.state.menuOperation.selectedCount':function(em) {
            const device = this.$store.state.menuOperation.selected;
            if (device.code) {
                this.deviceSelect(device);
            }
        }
    },
    methods:{
        doShow(actionInfo) {
            this.tableData = [];
            this.tableData = (actionInfo.condition || {}).trainStatuses || [];
            this.delay = ((actionInfo.condition || {}).delay || 0) / 1000;
            this.actionId = actionInfo.id;
            this.dialogVisible = true;
        },
        handleClose() {
            this.dialogVisible = false;
            this.initData();
        },
        getSectionName(code) {
            const section = this.$store.getters['map/getDeviceByCode'](code);
            return section.name;
        },
        handleEdit(index, row) {
            this.updateIndex = index;
            this.update = true;
            this.formModel.code = row.code;
            this.formModel.physicalCode = row.physicalCode;
            this.formModel.stop = row.stop;
        },
        handleDelete(index, row) {
            const data = [...this.tableData];
            data.splice(index, 1);
            updateActionCondition(this.$route.query.group, this.actionId, {trainStatuses: data, delay: this.delay * 1000}).then(resp => {
                this.tableData = data;
            }).catch(()=>{
                this.$message.error('删除条件失败');
            });
        },
        onUpdate() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    const data = [...this.tableData];
                    data[this.updateIndex] = this.formModel;
                    updateActionCondition(this.$route.query.group, this.actionId, {trainStatuses: data, delay: this.delay * 1000}).then(resp => {
                        this.tableData = data;
                    }).catch(()=>{
                        this.$message.error('修改条件失败');
                    });
                }
            });
        },
        onUpdateDelay() {
            updateActionCondition(this.$route.query.group, this.actionId, {trainStatuses: this.tableData, delay: this.delay * 1000}).then(resp => {
            }).catch(()=>{
                this.$message.error('修改条件失败');
            });
        },
        initData() {
            this.formModel = {
                code: '',
                physicalCode: '',
                stop: 1
            };
            this.update = false;
            this.updateIndex = '';
        },
        onCommit() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    const data = [...this.tableData];
                    data.push(this.formModel);
                    updateActionCondition(this.$route.query.group, this.actionId, {trainStatuses: data, delay: this.delay * 1000}).then(resp => {
                        this.tableData = data;
                    }).catch(()=>{
                        this.$message.error('添加条件失败');
                    });
                }
            });
        },
        hover(field) {
            if (this.field === field) {
                this.field = '';
            } else {
                this.field = field;
            }
        },
        deviceSelect(em) {
            if (this.field.toUpperCase() === 'triggerSection'.toUpperCase() && em._type.toUpperCase() === 'Section'.toUpperCase()) {
                this.formModel.physicalCode = em.code;
            } else if (this.field.toUpperCase() === 'triggerTrain'.toUpperCase() && em._type.toUpperCase() === 'Train'.toUpperCase()) {
                this.formModel.code = em.code;
            }
        }
    }
};
</script>

<style scoped>
	.reminder-drag{
		position: absolute;
		bottom: 10px;
		left: 15px;
		z-index: 200;
		padding: 5px;
		background: #FFF;
		width: 400px;
		height: 600px;
	}
</style>
