<template>
  <div class="dictionary_box">
    <div class="joylink-card">
      <data-form ref="dataform" :form="form" :form-model="formModel" :rules="rules" />
      <div style="overflow: hidden; margin-bottom: 20px;">
        <div class="param-title">条件参数:</div>
        <el-table :data="formModel.conditionList" border class="param-table">
          <el-table-column prop="name" label="参数名" />
          <el-table-column prop="value" label="参数值" />
          <el-table-column :label="this.$t('global.operate')" width="180">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="editConditionData(scope.$index, scope.row)">修改</el-button>
              <el-button type="text" size="small" @click="delCondition(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="button-box">
          <el-button type="primary" size="small" round @click="addConditionData">添加</el-button>
        </div>
      </div>
      <div style="overflow: hidden;">
        <div class="param-title">指令参数:</div>
        <el-table :data="formModel.paramList" border class="param-table">
          <el-table-column prop="name" label="参数名" />
          <el-table-column :label="this.$t('global.operate')" width="180">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="editParam(scope.$index, scope.row)">修改</el-button>
              <el-button type="text" size="small" @click="delParam(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="button-box">
          <el-button type="primary" size="small" round @click="addParam">添加</el-button>
        </div>
      </div>
    </div>
    <div class="dialog-footer">
      <el-button type="primary" @click="doSave">{{ $t('global.confirm') }}</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>

    <command-edit ref="create" type="ADD" @addData="addData" />
    <command-edit ref="edit" type="EDIT" @editData="editData" />
    <edit-condition ref="addCondition" type="ADD" @addData="addCondition" />
    <edit-condition ref="editCondition" type="EDIT" @editData="editCondition" />
  </div>
</template>

<script>
import { createCommand, editCommand, getCommandDetail } from '@/api/management/dictionary';
import CommandEdit from './editParam';
import { getLineCodeList } from '@/api/management/mapline';
import EditCondition from './editCondition';
import Commands from '@/scripts/plugin/Commands';

export default {
    name: 'DictionaryEdit',
    components: {
        CommandEdit,
        EditCondition
    },
    props: {
    },
    data() {
        return {
            taskStatusList: [],
            deviceTypeList: [],
            operateList: [],
            type: 'add',
            editIndex: 0,
            formModel: {
                id: '',
                simulationRole: '',
                controlMode: '',
                lineCode: '',
                operateObject: '',
                operate: '',
                paramList: [],
                conditionList: []
            }
        };
    },
    computed: {
        form() {
            const form = {
                labelWidth: '120px',
                items: [
                    { prop: 'lineCode', label: this.$t('system.lineCode'), type: 'select', options: this.taskStatusList },
                    { prop: 'simulationRole', label: this.$t('system.simulationRole'), type: 'select', options: this.$ConstSelect.simulationRole },
                    { prop: 'controlMode', label: this.$t('system.controlMode'), type: 'select', options: this.$ConstSelect.controlMode },
                    { prop: 'operateObject', label: this.$t('system.deviceType'), type: 'select', options: this.$ConstSelect.deviceTypeList, change: true, onChange: this.deviceChange },
                    { prop: 'operate', label: this.$t('system.instructionType'), type: 'select', options: this.operateList }
                ]
            };
            return form;
        },
        rules() {
            return {
                controlMode: [
                    { required: true, message: this.$t('rules.pleaseSelectStatus'), trigger: 'change' }
                ],
                operateObject: [
                    { required: true, message: this.$t('rules.pleaseSelectStatus'), trigger: 'change' }
                ],
                lineCode: [
                    { required: true, message: this.$t('rules.pleaseSelectStatus'), trigger: 'change' }
                ],
                simulationRole: [
                    { required: true, message: this.$t('rules.pleaseSelectStatus'), trigger: 'change' }
                ],
                operate: [
                    { required: true, message: this.$t('rules.pleaseSelectStatus'), trigger: 'change' }
                ]
            };
        }
    },
    mounted () {
        this.loadInitData();
        this.init();
    },
    methods: {
        async loadInitData() {
            try {
                this.taskStatusList = [];
                const list = await getLineCodeList();
                list.data.forEach(elem => {
                    elem.value = elem.code;
                    elem.label = elem.name;
                });
                this.taskStatusList = list.data;
            } catch (error) {
                console.log(error);
            }
        },
        init() {
            this.type = this.$route.query.type;
            if (this.$route.query.id) {
                getCommandDetail(this.$route.query.id).then(res => {
                    this.formModel = res.data;
                    this.operateList = Object.values(Commands[this.formModel.operateObject]);
                });
            }
        },
        deviceChange(code) { // 操作对象变化
            this.operateList = Object.values(Commands[code]);
        },
        doSave() {
            this.$refs.dataform.validateForm(() => {
                if (this.type == 'add') {
                    this.create();
                } else {
                    this.update();
                }
            });
        },
        create() {
            createCommand(this.formModel).then(response => {
                this.$message.success(this.$t('system.createSuccess'));
                this.handleBack();
            }).catch(error => {
                console.log(error);
                this.$message.error('创建指令失败');
            });
        },
        update() {
            editCommand(this.formModel).then(response => {
                this.$message.success(this.$t('system.updateSuccess'));
                this.handleBack();
            }).catch(error => {
                console.log(error);
                this.$message.error('更新指令失败');
            });
        },
        handleBack() {
            this.$router.push({ path: `/system/commands`, query: { } });
        },

        editData(data) {
            this.formModel.paramList.splice(this.editIndex, 1, data);
        },
        addData(data) {
            this.formModel.paramList.push(data);
        },
        addParam() {
            this.$refs.create.doShow();
        },
        editParam(index, row) {
            this.$refs.edit.doShow(row);
            this.editIndex = index;
        },
        delParam(index) {
            this.formModel.paramList.splice(index, 1);
        },

        editConditionData(index, row) {
            this.$refs.editCondition.doShow(row);
            this.editIndex = index;
        },
        addConditionData() {
            this.$refs.addCondition.doShow();
        },
        addCondition(Condition) {
            this.formModel.conditionList.push(Condition);
        },
        editCondition(Condition) {
            this.formModel.conditionList.splice(this.editIndex, 1, Condition);
        },
        delCondition(index) {
            this.formModel.conditionList.splice(index, 1);
        }
    }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
	.dictionary_box{
		margin: 40px auto 20px;
		width: 800px;

		.joylink-card{
			padding: 24px;

			.param-title{
				width: 120px;
				text-align: right;
				float: left;
				font-size: 14px;
				color: #606266;
				line-height: 40px;
				padding: 0 12px 0 0;
				box-sizing: border-box;
				font-weight: 700;
			}
			.param-table{
				width: calc(100% - 190px);
				min-height: 200px;
				float: left;
			}
			.button-box{
				float: left;
				margin-left: 10px;
			}
		}
		.dialog-footer{
			margin: 20px auto;
			display: flex;
			justify-content: center;
		}
	}
</style>
