<template>
  <div>
    <el-card style="width: 95%;margin-left: 35px;margin-top: 10px">
      <div slot="header" class="clearfix">
        <span>引擎规则基本信息</span>
        <el-button style="float: right" @click="goBack" size="medium" type="text">返回</el-button>
      </div>
      <el-descriptions border :column="3">
        <el-descriptions-item label="规则名称">{{ruleInfo.ruleName}}</el-descriptions-item>
        <el-descriptions-item label="引擎编码">{{ruleInfo.ruleCode}}</el-descriptions-item>
        <el-descriptions-item label="规则级别">{{ruleInfo.ruleLevel}}</el-descriptions-item>
        <el-descriptions-item label="规则类型">{{ruleInfo.ruleType}}</el-descriptions-item>
        <el-descriptions-item label="是否激活">
          <el-tag size="small" v-if="ruleInfo.ruleIsActivate === 'Y'">是</el-tag>
          <el-tag size="small" v-if="ruleInfo.ruleIsActivate === 'N'">否</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="规则状态">
          <el-tag size="small" v-if="ruleInfo.ruleStatus === 'Y'">在用</el-tag>
          <el-tag size="small" v-if="ruleInfo.ruleStatus === 'N'">停用</el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-card :body-style="{ padding: '0.3px' }" class="versionContainer" style="width: 95%;margin-left: 35px;margin-top: 10px">
      <div slot="header" class="clearfix">
        <span>规则内容</span>
        <el-button style="float: right;margin-left: 5px" @click="handleDel" size="medium" type="text">删除此版本</el-button>
        <el-button style="float: right;margin-left: 5px" @click="handleAdd" size="medium" type="text">新增版本</el-button>
        <el-button style="float: right;margin-left: 5px" @click="()=>{this.visible=true;}" size="medium" type="text">测试规则</el-button>
        <el-button style="float: right;margin-left: 5px" @click="saveContent" size="medium" type="text">保存此版本</el-button>
      </div>
      <div style="padding: 0!important;overflow: hidden;position: relative;">
        <el-empty v-if="versionList.length===0" description="暂无规则内容" style="height: 450px"></el-empty>
        <el-tabs v-else type="border-card" v-model="activeName" >
          <el-tab-pane :key="index" v-for="(scope,index) in versionList" :label="scope.versionCode" :name="index+''">
            <encoding v-if="activeName===index.toString()" style="height: 600px" v-model="scope.ruleContent" ></encoding>
          </el-tab-pane>
        </el-tabs>
        <el-drawer
          title="规则测试"
          :visible.sync="visible"
          :before-close="handleClose"
          :lockScroll="false"
          :modal="false"
          direction="rtl"
          style="position: absolute;"
        >
          <el-form >
            <el-form-item label="测试数据" style="margin-left: 5px">
              <el-input type="textarea" v-model="testData" ></el-input>
            </el-form-item>
            <el-form-item label="测试结果" style="margin-left: 5px">
              <el-input type="textarea" v-model="resData" ></el-input>
            </el-form-item>
            <el-form-item style="margin-left: 5px">
              <el-button type="primary" size="small" @click="handleTest">测试</el-button>
            </el-form-item>
          </el-form>
        </el-drawer>
      </div>
    </el-card>
    <!-- 添加或修改引擎规则配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="版本编码" prop="versionCode">
          <el-input v-model="form.versionCode" placeholder="请输入版本编码" />
        </el-form-item>
        <el-form-item label="新增依据" prop="newBasis">
          <el-select v-model="form.newBasis" placeholder="请选择新增依据" style="width: 100%" @change="handlerChange">
            <el-option :key="-1" label="克隆公共配置" value="-1"></el-option>
            <el-option
              v-for="(item,index) in versionList"
              :key="index"
              :label="'克隆'+item.versionCode+'版本'"
              :value="index">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）,
// 例如：import 《组件名称》 from '《组件路径》,
import { selectRuleEngineByRuleId, selectRuleEngineOne } from "@/api/goods/engine";
import Encoding from "@/components/Encoding/index.vue";
import { listConfigEs, getConfig, addConfig, updateConfig, delConfig, textData, getScopeInfo, queryConfigInfo } from "@/api/goods/config";

export default {
  // import引入的组件需要注入到对象中才能使用"
  components: { Encoding },
  props: {},
  data() {
    // 这里存放数据"
    return {
      visible: false,
      // configId: this.$route.params && this.$route.params.configId,
      ruleId: this.$route.params && this.$route.params.ruleId,
      // ruleId: 1,
      ruleInfo: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 引擎表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        versionCode: null,
        ruleContent: null,
        ruleId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        versionCode: [
          { required: true, message: "版本编码不能为空", trigger: "blur" }
        ],
        newBasis: [
          { required: true, message: "新增依据不能为空", trigger: "blur" }
        ],
      },
      testData:'1424587994@163com,2949451835@qq.com',
      activeName: '0',
      baseRuleContent:'',
      versionList: [],
      resData: ''
    }
  },
  // 计算属性 类似于data概念",
  computed: {},
  // 监控data中的数据变化",
  watch: {},
  // 方法集合",
  methods: {
    init() {
      selectRuleEngineOne(this.ruleId).then(res => {
        this.ruleInfo = res.data
      })
      // selectRuleEngineByRuleId(this.ruleId).then(res => {
      //   this.ruleInfo = res.data
      // })
      listConfigEs(this.ruleId).then(res => {
        this.versionList = res.data
      })
      getScopeInfo(0).then(res => {
        console.log(res.data)
        this.baseRuleContent = res.data.code
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        versionCode: null,
        ruleContent: null,
        ruleId: null
      };
      this.resetForm("form");
    },
    // 更新依据
    handlerChange(val){
      if(val!=='-1'){
        this.form.ruleContent=this.versionList[Number(val)].ruleContent;
      }else {
        this.form.ruleContent=this.baseRuleContent;
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.init();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.ruleId=this.ruleInfo.ruleId;
      this.title = "添加引擎";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getConfig(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改引擎";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.init();
            });
          } else {
            addConfig(this.form).then(response => {
              console.log(this.form)
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.init();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDel(row) {
      const ids = row.id || this.ids;
      let data = this.versionList[Number(this.activeName)]
      this.$modal.confirm('是否确认删除引擎版本为"' + data.versionCode + '"的数据项？').then(function() {
        return delConfig(data.id);
      }).then(() => {
        this.init();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    saveContent() {
      updateConfig(this.versionList[Number(this.activeName)]).then(response => {
        this.$message.success("保存成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    },
    handleTest() {
      textData({id:this.versionList[Number(this.activeName)].id,list:this.testData.split(',')}).then(response=>{
        this.resData=response.data;
        this.$message.success("测试成功");
      })
    },
    handleClose() {
      this.visible=false;
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）",
  created() {
    this.init();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）",
  mounted() {
  },
  beforeCreate() {
  }, // 生命周期 - 创建之前",
  beforeMount() {
  }, // 生命周期 - 挂载之前",
  beforeUpdate() {
  }, // 生命周期 - 更新之前",
  updated() {
  }, // 生命周期 - 更新之后",
  beforeDestroy() {
  }, // 生命周期 - 销毁之前",
  destroyed() {
  }, // 生命周期 - 销毁完成",
  activated() {
  } // 如果页面有keep-alive缓存功能，这个函数会触发",
}
</script>
<style scoped>

</style>
