<template>
  <app-dialog
    v-model="visible"
    :loading="loading"
    title="执行参数配置"
    append-to-body
    class="detail-dialog"
    width="600px"
    @cancel="onCancel"
    @confirm="onConfirm"
  >
    <el-form ref="formJson" :model="formJson" :rules="rules" label-width="120px">
      <div class="form-content">
        <el-table ref="paramTable" :data="formJson.tableData" border height="300px" style="width: 100%">
          <el-table-column align="center" label="序号" width="50" type="index" />
          <el-table-column align="center" label="名称" min-width="160" resizable>
            <template slot="header">
              <span>
                <span class="fs-14" style="color: #f56c6c">*</span>
                参数名称
              </span>
            </template>
            <template slot-scope="scope">
              <app-filter-item :prop="`tableData.${scope.$index}.key`" :rules="rules.key" :span="24">
                <el-input v-model="scope.row.key" placeholder="请输入参数名称" />
              </app-filter-item>
            </template>
          </el-table-column>
          <el-table-column align="center" min-width="160" resizable>
            <template slot="header">
              <span>
                <span class="fs-14" style="color: #f56c6c">*</span>
                参数值
              </span>
            </template>
            <template slot-scope="scope">
              <app-filter-item :prop="`tableData.${scope.$index}.value`" :rules="rules.value" :span="24">
                <el-input v-model="scope.row.value" placeholder="请输入参数值" />
              </app-filter-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="100">
            <template slot-scope="scope">
              <el-button class="control-icon" circle type="primary" size="mini" icon="el-icon-plus" @click="handleAdd"></el-button>
              <el-button class="control-icon" circle type="danger" size="mini" icon="el-icon-minus" @click="handleDel(scope.$index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
  </app-dialog>
</template>

<script>
import dialogMixin from '@/mixins/dialog.js';

export default {
  name: 'paramDialog',
  mixins: [dialogMixin],
  props: {},
  data() {
    var checkey = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('参数名称不能为空'));
      } else {
        if (this.formJson.tableData.filter((item) => item.key === value).length > 1) {
          callback(new Error('参数名称不能重复!'));
        } else {
          callback();
        }
      }
    };
    return {
      formJson: {
        tableData: [
          {
            key: '',
            value: '',
          },
        ],
      },
      rules: {
        key: [
          { required: true, message: '参数名称不能为空' },
          { validator: checkey, trigger: 'blur' },
        ],
        value: [{ required: true, message: '参数值不能为空' }],
      },
      loading: false,
    };
  },
  mounted() {},
  methods: {
    /**
     * @description: dialog每次显示时触发的init方法
     * @param {*} data 传入data
     * @return {*}
     */
    initData(data) {
      if (data.data) {
        this.formJson.tableData = [
          {
            key: '',
            value: '',
          },
        ];
        let JsonOBJ = JSON.parse(data.data) || {};

        let tempArr = [];
        for (const [key, value] of Object.entries(JsonOBJ)) {
          let formatObj = {};
          formatObj.key = key;
          formatObj.value = value;
          tempArr.push(formatObj);
        }

        this.formJson.tableData = [...tempArr];
      }
      this.$nextTick(() => {
        this.$refs.formJson.clearValidate();
      });
    },

    onCancel() {
      this.formJson.tableData = [
        {
          key: '',
          value: '',
        },
      ];
      this.visible = false;
      this.loading = false;
    },

    onConfirm() {
      this.loading = true;
      this.$refs.formJson.validate(async (valid, object) => {
        if (valid) {
          let JsonOBJ = {};
          this.formJson.tableData.forEach((item) => {
            JsonOBJ[item.key] = item.value;
          });

          this.$emit('confirm', JSON.stringify(JsonOBJ));
          this.formJson.tableData = [
            {
              key: '',
              value: '',
            },
          ];
          this.loading = false;
          this.visible = false;
        } else {
          this.$message.warning(`有${Object.keys(object).length}个字段未通过校验，请正确填写表单。`);
          this.loading = false;
        }
      });
    },
    handleAdd() {
      const newData = {
        key: '',
        value: '',
      };
      this.formJson.tableData.splice(this.formJson.tableData.length, 1, newData);
    },
    handleDel(index) {
      if (this.formJson.tableData.length === 1) {
        this.$message.warning('至少保留一条数据！');
        return;
      }
      this.formJson.tableData.splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep {
  .app-dialog-content {
    height: 400px !important;
  }
  .control-icon {
    padding: 8px !important;
  }
}
.form-content {
  width: 96%;
  margin: 0 auto;
}
</style>
