<template>
  <div class="app-container">
    <el-descriptions class="margin-top" :title="ruleInfo.ruleName" :column="3" border>
      <template slot="extra">
        <el-dropdown split-button type="primary" @command="handleClick">
          更多操作
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="add">版本添加</el-dropdown-item>
            <el-dropdown-item command="updIsActivate">激活状态</el-dropdown-item>
            <el-dropdown-item command="updStatus">版本状态</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
        <el-descriptions-item label="规则名称">{{ruleInfo.ruleName}}</el-descriptions-item>
        <el-descriptions-item label="引擎编码">{{ruleInfo.ruleCode}}</el-descriptions-item>
        <el-descriptions-item label="规则级别">
          <dict-tag :options="dict.type.rule_engine_level" :value="ruleInfo.ruleLevel"></dict-tag>
        </el-descriptions-item>
        <el-descriptions-item label="规则类型">
          <dict-tag :options="dict.type.rule_engine_type" :value="ruleInfo.ruleType"></dict-tag>
        </el-descriptions-item>
        <el-descriptions-item label="是否激活">
            <dict-tag :options="dict.type.rule_engine_activate_status" :value="ruleInfo.ruleIsActivate"></dict-tag>
        </el-descriptions-item>
        <el-descriptions-item label="规则状态">
          <span v-if="ruleInfo.ruleStatus === 'Y'">在用</span>
          <span v-if="ruleInfo.ruleStatus === 'N'">停用</span>
        </el-descriptions-item>
      </el-descriptions>

  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>规则引擎版本</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="12" v-for="edition in editionList">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>{{edition.name+"_"+edition.versionCode}}</span>
              <el-dropdown style="float: right; padding: 3px 0" @command="checkRuleEngineVersion">
                <span class="el-dropdown-link">
                  更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="{event: 'select', rule: edition}">规则详情</el-dropdown-item>
                  <el-dropdown-item :command="{event: 'test', rule: edition}"
                                    :disabled="edition.editionStatus === '-1'"
                  >测试规则</el-dropdown-item>
                  <el-dropdown-item :command="{event: 'status', rule: edition}" :disabled="edition.editionStatus !== '1'">
                    {{editionList.ruleIsTest !== '0' ? "禁用" : "激活"}}规则
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="{event: 'publish', rule: editionList}"
                    v-if="editionList.editionStatus === '1' && edition.ruleIsTest === '1'">
                    发布规则
                  </el-dropdown-item>
                  <el-dropdown-item :command="{event: 'delete', rule: edition}">规则删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          <el-descriptions class="margin-top" :column="2" border>
            <el-descriptions-item label="版本类" :span="2">{{edition.versionClass}}</el-descriptions-item>
            <el-descriptions-item label="版本名称">{{edition.name}}</el-descriptions-item>
            <el-descriptions-item label="版本编码">{{edition.versionCode}}</el-descriptions-item>
            <el-descriptions-item label="是否激活">
              <dict-tag :options="dict.type.rule_engine_activate_status" :value="edition.ruleStatus"></dict-tag>
            </el-descriptions-item>
            <el-descriptions-item label="规则状态">
              <dict-tag :options="dict.type.rule_engine_edition_status" :value="edition.editionStatus"></dict-tag>
            </el-descriptions-item>
            <el-descriptions-item label="是否测试">
              <dict-tag :options="dict.type.rule_engine_is_test" :value="edition.ruleIsTest"></dict-tag>
            </el-descriptions-item>
            <editor style="margin-top: 10px" :read-only="true" v-model="edition.editionContent"></editor>
          </el-descriptions>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
    <!-- 添加或修改规则引擎版本对话框 -->
    <el-dialog title="添加数据" :visible.sync="open" width="75%" append-to-body>
      <el-card class="box-card">
        <el-button style="float: right; padding: 3px 0" type="text" @click="genEngineVersion">生成引擎版本类</el-button>
      </el-card>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
        <el-col :span="24">
          <el-form-item label="版本类">
            <el-input v-model="form.versionClass" disabled placeholder="点击类生成自动生成类版本"  />
          </el-form-item>
        </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="版本名称">
              <el-input v-model="form.name" placeholder="请输入版本名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本编码">
              <el-input v-model="form.versionCode" placeholder="请输入版本编码" />
            </el-form-item>
          </el-col>
        </el-row>
          <el-form-item label="内容">
            <editor v-model="form.editionContent" :min-height="180"/>
          </el-form-item>
      </el-form>
      <el-card class="box-card" v-if="form.ruleContent != ''">
        <div slot="header" class="clearfix">
          <span>引擎编码</span>
        </div>
        <encoding style="height: 800px" v-model="form.ruleContent"></encoding>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

<!--    查看详情-->
    <el-drawer title="查看详情" size="80%" :before-close="ruleEngineVersionInfoStatusClose"
               :visible.sync="oppten"
               :direction="'rtl'">
      <div>
        <el-descriptions v-if="selectList != null" class="margin-tog" :column="2" border>
          <el-descriptions-item label="版本类" :span="2">{{selectList.versionClass}}</el-descriptions-item>
          <el-descriptions-item label="版本名称">
            <input v-model="selectList.name">
            </el-descriptions-item>
          <el-descriptions-item label="版本编码">{{selectList.versionCode}}</el-descriptions-item>
          <el-descriptions-item label="引擎状态">
            <dict-tag :options="dict.type.rule_engine_edition_status" :value="selectList.editionStatus"></dict-tag>
          </el-descriptions-item>
          <el-descriptions-item label="是否激活">
            <dict-tag :options="dict.type.rule_engine_activate_status" :value="selectList.ruleStatus"></dict-tag>
          </el-descriptions-item>
          <el-descriptions-item label="是否测试">
            <dict-tag :options="dict.type.rule_engine_is_test" :value="selectList.ruleIsTest"></dict-tag>
          </el-descriptions-item>
        </el-descriptions>
        <editor style="margin-top: 10px" :min-height="100" v-model="selectList.editionContent"></editor>
        <el-row style="margin-top: 10px">
            <el-button @click="saveCoding(selectList)">保存代码</el-button>
        </el-row>
        <encoding style="height: 800px; margin-top: 20px" v-model="selectList.ruleContent"></encoding>
      </div>
    </el-drawer>
<!--    规则测试  -->
    <el-drawer title="规则版本测试" size="80%" :before-close="ruleEngineVersionInfoStatusClose"
               :visible.sync="openRuleTest" :direction="'rtl'">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-descriptions v-if="selectList!=null" class="margin-tog" :column="2" border>
            <el-descriptions-item label="版本类" :span="2">{{selectList.versionClass}}</el-descriptions-item>
            <el-descriptions-item label="版本名称">{{selectList.name}}</el-descriptions-item>
            <el-descriptions-item label="版本编码">{{selectList.versionCode}}</el-descriptions-item>
            <el-descriptions-item label="引擎状态">
            <dict-tag :options="dict.type.rule_engine_edition_status" :value="selectList.editionStatus"></dict-tag>
            </el-descriptions-item>
            <el-descriptions-item label="是否激活">
              <dict-tag :options="dict.type.rule_engine_activate_status" :value="selectList.ruleStatus"></dict-tag>
            </el-descriptions-item>
            <el-descriptions-item label="是否测试">
              <dict-tag :options="dict.type.rule_engine_is_test" :value="selectList.ruleIsTest"></dict-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="12">
          <editor style="margin-top: 10px" :read-only="true" :min-height="105" v-model="selectList.editionContent"></editor>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <encoding style="margin-top: 20px" v-model="selectList.ruleContent"></encoding>
        </el-col>
          <el-col :span="12">
              <el-col :span="primaryId == null ? 24:12">
                  <el-card class="box-card">
                      <div slot="header" class="clearfix">
                          <span>选择资产结构</span>
                      </div>
                      <el-select v-model="primaryId" style="width: 100%">
                          <el-option v-for="asses in primary"
                                     :key="asses.tableLists"
                                     :value="asses.tableLists"
                                     :label="asses.name+'('+asses.databaseName+')'">
                          </el-option>
                      </el-select>
                  </el-card>
              </el-col>
              <el-col :span="12" v-if="primaryId != []">
                  <el-card class="box-card">
                      <div slot="header" class="clearfix">
                          <span>选择资产模型</span>
                      </div>
                      <el-select v-model="tableLisrs" style="width: 100%;">
                          <el-option v-for="model in primaryId"
                                     :key="model.id+model.tableName"
                                     :value="model.id+model.tableName"
                                     :label="model.databaseName+'('+model.tableName+')'"
                          ></el-option>
                      </el-select>
                  </el-card>
              </el-col>
              <el-col :span="24" v-if="tableLisrs != null">
                  <el-card class="box-card" v-if="ruleInfo.ruleLevel === 1">
                      <div slot="header" class="clearfix">
                          <span>任务</span>
                      </div>
                  </el-card>
                  <el-card class="box-card" v-if="ruleInfo.ruleLevel === 2">
                      <div slot="header" class="clearfix">
                          <span>数据集</span>
                      </div>
                      <el-table ref="multipleTable" :data="columnOne2" max-height="200px">
                        <el-table-column type="selection" width="55"></el-table-column>
<!--                        <el-table-column v-for="dataModel in columnOne2" :label="dataModel.comment" :prop="dataModel.name"/>-->
                        <el-table-column v-for="(val, key) in columnOne2[0]" :key="key" :label="key" :prop="key"></el-table-column>
                      </el-table>
                      <div style="margin-top: 20px">
                        <el-button @click="toggleSelection()">清空选择</el-button>
                      </div>
                  </el-card>
                <el-card class="box-card" v-if="ruleInfo.ruleLevel === 3">
                      <div slot="header" class="clearfix">
                          <span>记录</span>
                      </div>
                      <el-table :data="columnOne2" max-height="200px">
                        <el-table-column v-for="(val, key) in columnOne2[0]" :key="key" :label="key" :prop="key"></el-table-column>
                        <el-table-column label="操作">
                          <template slot-scope="scope">
                            <el-button type="text" @click="dataRecordSelect(scope.row)">选择</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                  <el-descriptions title="字段" :column="3" border>
                    <el-descriptions-item  ></el-descriptions-item>
                  </el-descriptions>
                  </el-card>
                  <el-card class="box-card" v-if="ruleInfo.ruleLevel === 4">
                      <div slot="header" class="clearfix">
                          <span>数据字段</span>
                      </div>
                      <button @click="dield(tableLisrs,ruleInfo.ruleLevel)">随机</button>
                      <el-descriptions title="字段" :column="3" border>
                          <el-descriptions-item v-for="tab in fields" :label="tab.key">{{tab.val}}</el-descriptions-item>
                      </el-descriptions>
                  </el-card>
              </el-col>
          </el-col>
      </el-row>
    </el-drawer>
  </div>
</template>

<script>
import { selectRuleEngineOne, updateRuleIsActivate, updateRuleStatus, spliceNameToCode  } from "@/api/goods/engine";
import { selectListRuleId, getEdition, delEdition, addEdition, updateEdition } from "@/api/goods/edition";
import { selectFrimary } from "@/api/system/accredit";
import { getRabdomData, getColumn } from "@/api/test/testData";
import Encoding from "@/components/Encoding/index.vue";

export default {
  name: "Edition",
  components: {Encoding},
  dicts: ['rule_engine_level', 'rule_engine_activate_status', 'rule_engine_type', 'rule_engine_edition_status', 'rule_engine_is_test'],

  data() {
    return {
      // 接收数据
      ruleId: this.$route.params && this.$route.params.ruleId,
      //接收规则
      ruleInfo: {},
      selectList: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 规则引擎版本表格数据
      editionList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 详情弹出层
      oppten: false,
      //测试弹出层
      openRuleTest: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      //测试表单
      ruleEngineTest:{},
      primary: [],
      //数据模型
      dataModelList: [],
      //复选列
      columns: [],
      //单选列
      columnOne: [],
      columnOne2: [],
      //复选字段
      fields: [],
      fieldd: [],
      //父类列
      primaryId: [],
      tableLisrs: null,
      // 表单参数
      form: {
        versionClass: "",
        name: "",
        versionCode: "",
        editionContent: "",
        ruleContent: ""
      },
      // 表单校验
      rules: {
      }
    };
  },
  watch: {
    // 监控conditionVar变量
    tableLisrs(newVal, oldVal) {
      if (newVal !== null && newVal !== oldVal) {
        this.executeApi(); // 当tableLists不为null且变化时，执行接口请求的方法
      }
  },
},
  created() {
    this.getList();
  },
  methods: {
    // 关闭
    ruleEngineVersionInfoStatusClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.ruleEngineVersionInfoAndTest = {};
          done();
        })
        .catch(_ => {});
    },
    /**
     * 随机字段
     * @param id
     */
    dield(tableLisrs,ruleLevel) {
        console.log(tableLisrs)
        var id = parseInt(tableLisrs.split('')[0]);
        var tableName = tableLisrs.slice(1)
      getRabdomData(id,tableName,ruleLevel).then(res => {
        this.fields = res.data;
        console.log(res.data)
      })
    },
    //显示队列
    executeApi() {
      var id = parseInt(this.tableLisrs.split('')[0]);
      var tableName = this.tableLisrs.slice(1)
      getColumn(id,tableName,this.ruleInfo.ruleLevel).then(res => {
        this.columnOne = res.data
        var list = this.columnOne;
        var list2 = [];
        list.forEach(function (sublist) {
          var dict2 = {}
          sublist.forEach(function (item) {
            dict2[item["key"]] = item["val"];
          })
          list2.push(dict2)
        })
        this.columnOne2 = list2;
        console.log(list2)
        console.log(res.data)
        console.log(this.columnOne2)
      })
    },
    toggleSelection() {
      this.$refs.multipleTable.clearSelection();
    },
    //读取队列
    dataRecordSelect(row) {
      console.log(row)
      this.fieldd = row
    },
    /** 查询规则引擎版本列表 */
    getList() {
      this.form.ruleId = this.ruleId
      selectFrimary().then(res => {
        this.primary = res.data
      })
      selectRuleEngineOne(this.ruleId).then(res => {
        this.ruleInfo = res.data;
      })
      selectListRuleId(this.ruleId).then(res => {
        this.editionList = res.data
        this.loading = false;
      })
      this.loading = true;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    saveCoding(row) {
      updateEdition(row).then(res => {
        this.$message.success(res.data)
      })
    },
    // 执行操作
    playEngineVersion(slickType){
      switch (slickType.event){
        case "update"://修改
          this.form = slickType.rule
          this.open = true
          break;
        case "status"://激活状态
          break;
      }
    },
    // 引擎版本操作
    checkRuleEngineVersion(clickType) {
      switch (clickType.event){
        case "delete"://删除
          if (confirm("确认删除吗")){
            delEdition(clickType.rule.id)
          }
          this.getList()
          break;
        case "select"://详情
          this.selectList = clickType.rule
          this.oppten = true
          break;
        case "test"://测试
          this.openRuleTest = true
          this.selectList = clickType.rule
          break;
        case "status"://激活状态
        break;
      }
    },
    // 维护操作
    handleClick(clickType) {
      if (clickType === "add"){
        this.open = true;
      }else if (clickType === "updIsActivate"){
        updateRuleIsActivate(this.ruleInfo).then(res => {
          this.$message.success(res.data)
          this.getList()
        })
      }else if (clickType === "updStatus"){
        updateRuleStatus(this.ruleInfo).then(res => {
          this.$message.success(res.data)
          this.getList()
        })
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ruleId: null,
        editionName: null,
        versionClass: null,
        name: null,
        versionCode: null,
        editionStatus: null,
        ruleStatus: null,
        ruleIsTest: null,
        editionContent: null,
        ruleContent: null
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加规则引擎版本";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEdition(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改规则引擎版本";
      });
    },
    genEngineVersion(){
      if (this.form.name == null || this.form.name === "") {
        this.$message.error('规则名称不可为空');
        return false;
      }
      if (this.form.versionCode == null || this.form.versionCode === "") {
        this.$message.error('版本编码不可为空');
        return false;
      }
      spliceNameToCode(this.ruleInfo.ruleCode,this.form.versionCode,this.ruleInfo.ruleLevel).then(res => {
        this.form.versionClass = res.data.val;
        this.form.ruleContent = res.data.code
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEdition(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEdition(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除规则引擎版本编号为"' + ids + '"的数据项？').then(function() {
        return delEdition(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 获取代码模板
    getCodeIng(){
      let packageName = "com.muyu.rule.engine";
      let customName = "custom";
      let templateName = "template";
      let parentClass = "DataModelEngine";
      let ruleContent = `package ${packageName}.${customName};

import com.muyu.engine.action.ActionDiscard;
import com.muyu.engine.scope.${parentClass};

/**
 * @Author: DongZeLiang
 * @date: 2024/5/6
 * @Description: ${this.form.name}-${this.form.versionCode}
 * @Version: 1.0
 */
public class ${this.form.versionCode} extends ${parentClass} {
    @Override
    public void execution () {
        Object value = getValue();

        if (value == null || "".equals(value) || "null".equals(value)) {
            throw new ActionDiscard();
        }
    }
}`;
      return ruleContent;
    }
  }
};
</script>
