<template>
  <div class="app-container">
    <el-descriptions class="margin-top" :title="this.ruleMsg.ruleName" :column="3" border>
      <template slot="extra">
        <el-dropdown split-button type="primary">
          更多菜单
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="handleAdd">版本添加</el-dropdown-item>
            <el-dropdown-item split-button @click.native="startActivate">激活引擎</el-dropdown-item>
            <el-dropdown-item split-button @click.native="unstartActivate">关闭引擎</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
      <el-descriptions-item>
        <template slot="label">
          规则名称
        </template>
        <span>{{this.ruleMsg.ruleName}}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          规则类型
        </template>
        <span>
          <el-tag v-if="this.ruleMsg.ruleType==='Z'" type="success">自定义规则</el-tag>
          <el-tag v-if="this.ruleMsg.ruleType==='M'" type="primary">规则模板</el-tag>
        </span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          规则作用域
        </template>
        <span>
          <el-tag v-if="this.ruleMsg.ruleRegion==='F'">数据字段</el-tag>
          <el-tag v-if="this.ruleMsg.ruleRegion==='R'" type="info">记录</el-tag>
          <el-tag v-if="this.ruleMsg.ruleRegion==='C'" type="warning">数据集 </el-tag>
        </span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          引擎编码
        </template>
        <span>{{this.ruleMsg.ruleCoding}}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          激活状态
        </template>
        <span>
          <el-tag v-if="this.ruleMsg.ruleActivate==='S'" type="success">已启动</el-tag>
          <el-tag v-if="this.ruleMsg.ruleActivate==='U'" type="danger">未启动</el-tag>
        </span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          规则状态
        </template>
        <span>
          <el-tag v-if="this.ruleMsg.ruleStatus==='Y'" type="success">正常</el-tag>
          <el-tag v-if="this.ruleMsg.ruleStatus==='N'" type="info">停用</el-tag>
        </span>
      </el-descriptions-item>
      <el-form-item label="内容">

      </el-form-item>
      <el-descriptions-item>
        <template slot="label">
          规则描述
        </template>
        <span>
          <editor v-model="this.ruleMsg.ruleDescribe" :min-height="30" read-only/>
        </span>
      </el-descriptions-item>
    </el-descriptions>

    <el-card class="big-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 28px ;font-weight: bold">规则版本</span>
      </div>
      <div class="text item">
        <el-row :gutter="10">
          <el-empty description="暂无规则版本" v-if="versionList.length === 0"></el-empty>
          <el-col :span="8" v-for="versionMsg in versionList" v-if="versionList.length !== 0">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span style="font-size: 24px; font-weight: 900;" type="primary">{{versionMsg.ruleVersionName}}</span>
                <el-dropdown style="float: right" type="primary">
                  <el-button type="primary">
                    更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="selectByVersionId(versionMsg.ruleVersionId)">规则详情</el-dropdown-item>
                    <el-dropdown-item @click.native="testRule(versionMsg.ruleVersionId)">测试规则</el-dropdown-item>
                    <el-dropdown-item @click.native="startVersionActivate(versionMsg.ruleVersionId)" v-if="versionMsg.ruleVersionActivate==='U'" >激活规则</el-dropdown-item>
                    <el-dropdown-item @click.native="unstartVersionActivate(versionMsg.ruleVersionId)" v-if="versionMsg.ruleVersionActivate==='S'" >关闭规则</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <div>
                <el-descriptions class="margin-top" :column="1"  border>
                  <el-descriptions-item>
                    <template slot="label"> 版本类 </template>
                    {{versionMsg.ruleVersionType}}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label"> 版本名称 </template>
                    {{versionMsg.ruleVersionName}}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label"> 版本编号 </template>
                    {{versionMsg.ruleVersionCode}}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label"> 激活状态 </template>
                    <el-tag v-if="versionMsg.ruleVersionActivate==='S'" type="success">已启动</el-tag>
                    <el-tag v-if="versionMsg.ruleVersionActivate==='U'" type="danger">未启动</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label"> 版本状态 </template>
                    <el-tag v-if="versionMsg.ruleVersionTest==='I'" type="danger">初始化</el-tag>
                    <el-tag v-if="versionMsg.ruleVersionTest==='W'" type="danger">待发布</el-tag>
                    <el-tag v-if="versionMsg.ruleVersionTest==='A'" type="danger">已发布</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label"> 测试状态 </template>
                    <el-tag v-if="versionMsg.ruleVersionTest==='P'" type="danger">测试通过</el-tag>
                    <el-tag v-if="versionMsg.ruleVersionTest==='W'" type="danger">未测试</el-tag>
                    <el-tag v-if="versionMsg.ruleVersionTest==='U'" type="danger">测试中</el-tag>
                    <el-tag v-if="versionMsg.ruleVersionTest==='N'" type="danger">测试未通过</el-tag>
                  </el-descriptions-item>
                </el-descriptions>
                <editor class="remark" v-model="versionMsg.remark" :min-height="30" read-only/>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 添加规则版本对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="800px">
      <el-card class="add-card">
        <div slot="header" class="clearfix">
          <span>新增版本</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="executionGeneration">生成引擎版本类</el-button>
        </div>
        <div class="text item">
          <el-form ref="form" :model="form" :rules="rules" label-width="70px" :inline="true">
            <el-form-item label="版本类">
              <el-input v-model="form.ruleVersionType" class="versionType" style="width: 600px;" placeholder="点击类生成自动生成类名称" readonly/>
            </el-form-item>
            <el-form-item label="名称" prop="ruleVersionName" >
              <el-input v-model="form.ruleVersionName" style="width: 260px" placeholder="请输入版本名称"/>
            </el-form-item>
            <el-form-item label="编码" prop="ruleVersionCode" >
              <el-input v-model="form.ruleVersionCode" style="width: 260px" placeholder="请输入版本编码"/>
            </el-form-item>
            <el-form-item label="状态">
              <el-tag type="info">停用</el-tag>
            </el-form-item>
            <el-form-item label="是否激活" style="margin-left: 220px">
              <el-tag type="danger">未启动</el-tag>
            </el-form-item>
          </el-form>
          <editor v-model="form.remark" :min-height="60"/>
          <codemirror v-show="addCode" v-model="form.ruleVersionText" @input="changeClassName" style="margin-top: 10px" ref="codeMirrorEditor" :value="code" :options="cmOptions">
          </codemirror>
        </div>
      </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="规则版本详情"
      :visible.sync="drawer"
      :size="versionDrawer">
      <span>
        <el-descriptions class="margin-top" :column="3" border>
          <el-descriptions-item>
           <template slot="label"> 版本类 </template>
           {{ruleVersion.ruleVersionType}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 版本名称 </template>
            {{ruleVersion.ruleVersionName}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 版本编号 </template>
            {{ruleVersion.ruleVersionCode}}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 激活状态 </template>
            <el-tag v-if="ruleVersion.ruleVersionActivate==='S'" type="success">已启动</el-tag>
            <el-tag v-if="ruleVersion.ruleVersionActivate==='U'" type="danger">未启动</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label"> 版本状态 </template>
            <el-tag v-if="ruleVersion.ruleVersionTest==='I'" type="danger">初始化</el-tag>
            <el-tag v-if="ruleVersion.ruleVersionTest==='W'" type="danger">待发布</el-tag>
            <el-tag v-if="ruleVersion.ruleVersionTest==='A'" type="danger">已发布</el-tag>
          </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label"> 测试状态 </template>
              <el-tag v-if="ruleVersion.ruleVersionTest==='P'" type="danger">测试通过</el-tag>
              <el-tag v-if="ruleVersion.ruleVersionTest==='W'" type="danger">未测试</el-tag>
              <el-tag v-if="ruleVersion.ruleVersionTest==='U'" type="danger">测试中</el-tag>
              <el-tag v-if="ruleVersion.ruleVersionTest==='N'" type="danger">测试未通过</el-tag>
            </el-descriptions-item>
        </el-descriptions>
        <editor class="remark" v-model="ruleVersion.remark" :min-height="30" read-only/>
          <codemirror @input="changeClassName" v-model="ruleVersion.ruleVersionText" style="margin-top: 10px" ref="codeMirrorEditor" :value="code" :options="cmOptions"/>
        <el-button @click="saveVersionCode(ruleVersion)">保存代码</el-button>
      </span>
    </el-drawer>

    <!-- 测试规则版本对话框 -->
    <el-dialog :title="title" :visible.sync="openTest" append-to-body width="1000px">
      <div >
        <el-card class="add-card">
          <div slot="header" class="clearfix">
            <el-button style="float: right; padding: 3px 0" type="text" @click="selectData">选择测试数据</el-button>
          </div>
          <div slot="header" class="clearfix">
            <el-descriptions class="margin-top" :column="3" border>
              <el-descriptions-item>
                <template slot="label"> 版本类 </template>
                {{testRuleVersion.ruleVersionType}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 版本名称 </template>
                {{testRuleVersion.ruleVersionName}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 版本编号 </template>
                {{testRuleVersion.ruleVersionCode}}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 激活状态 </template>
                <el-tag v-if="testRuleVersion.ruleVersionActivate==='S'" type="success">已启动</el-tag>
                <el-tag v-if="testRuleVersion.ruleVersionActivate==='U'" type="danger">未启动</el-tag>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 版本状态 </template>
                <el-tag v-if="testRuleVersion.ruleVersionTest==='I'" type="danger">初始化</el-tag>
                <el-tag v-if="testRuleVersion.ruleVersionTest==='W'" type="danger">待发布</el-tag>
                <el-tag v-if="testRuleVersion.ruleVersionTest==='A'" type="danger">已发布</el-tag>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label"> 测试状态 </template>
                <el-tag v-if="testRuleVersion.ruleVersionTest==='P'" type="danger">测试通过</el-tag>
                <el-tag v-if="testRuleVersion.ruleVersionTest==='W'" type="danger">未测试</el-tag>
                <el-tag v-if="testRuleVersion.ruleVersionTest==='U'" type="danger">测试中</el-tag>
                <el-tag v-if="testRuleVersion.ruleVersionTest==='N'" type="danger">测试未通过</el-tag>
              </el-descriptions-item>
            </el-descriptions>
            <editor class="remark" v-model="testRuleVersion.remark" :min-height="30" read-only/>
            <codemirror @input="changeClassName" v-model="testRuleVersion.ruleVersionText" style="margin-top: 10px" ref="codeMirrorEditor" :value="code" :options="cmOptions">
            </codemirror>
          </div>
<!--        选择测试数据-->
          <div v-show="selectDataFrame">
            <el-card>
              <el-select v-model="tableData.databaseName" placeholder="请选择" @change="selectTable">
                <el-option
                  v-for="item in database"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name">
                </el-option>
              </el-select>
            </el-card>
          </div>
        </el-card>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="testData(testRuleVersion)">测 试</el-button>
        <el-button >取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）,
//例如：import 《组件名称》 from '《组件路径》,
import {
  compileLoad, extractDataName,
  findByRuleId,
  findByRuleVersionId, findSelectDataShow, generatedCode,
  getList, Load, row,
  save, saveCode,
  start,
  startVersion,
  unstart,
  unstartVersion
} from '@/api/rule/versions'
import codemirror from "codemirror/lib/codemirror";
require("codemirror/mode/clike/clike.js");
require("codemirror/addon/edit/closebrackets.js");
components: {
  codemirror;
}
import "codemirror/theme/eclipse.css";
import "codemirror/theme/darcula.css";
import "codemirror/theme/blackboard.css";

export default {
    //import引入的组件需要注入到对象中才能使用"
    components: {},
    props: {},
    data() {
      //这里存放数据"
      return {
        //规则引擎信息
        ruleMsg:{},
        versionList:[],
        // 是否显示弹出层
        open: false,
        openTest: false,
        // 弹出层标题
        title: "",
        // 表单参数
        form: {
          ruleId:0,
          ruleVersionStatus:"N",
          ruleVersionActivate:"U"
        },
        // 表单校验
        rules: {
          ruleVersionName: [
            {required: true, message: "规则名称不能为空", trigger: "blur"}
          ],
          ruleVersionCode: [
            {required: true, message: "引擎编码不能为空", trigger: "blur"}
          ],
        },
        //版本信息
        ruleVersion:{},
        // 规则版本详情抽屉
        drawer: false,
        code: "",
        cmOptions:{
          mode: "text/x-java",  //Java语言
          theme: "darcula", // 默认主题
          autofocus: true,
          lineNumbers: true,   //显示行号
          smartIndent: true, // 自动缩进
          autoCloseBrackets: true// 自动补全括号
        },
        versionDrawer:'60%',
        addCode:false,
        testRuleVersion:"",
        //选择数据框
        selectDataFrame:false,
        //数据库
        database:[],
        //表数据
        tableData:{
          //数据库名称
          databaseName:"",
        },
      };
    },
    //计算属性 类似于data概念",
    computed: {},
    //监控data中的数据变化",
    watch: {},
    //方法集合",
    methods: {
      //回显规则信息
      getRuleMsg(ruleId){
        console.log(ruleId)
        findByRuleId(ruleId).then(response => {
          this.ruleMsg = response.data
        })
      },
      //规则激活状态
      startActivate(){
        start(this.ruleMsg.ruleId).then(response => {
          this.$modal.msgSuccess("激活成功");
          this.getRuleMsg(this.ruleMsg.ruleId)
        })
      },
      //规则激活状态
      unstartActivate(){
        unstart(this.ruleMsg.ruleId).then(response => {
          this.$modal.msgSuccess("关闭成功");
          this.getRuleMsg(this.ruleMsg.ruleId)
        })
      },
      start(){
        start(this.ruleMsg.ruleId).then(res => {
          this.ruleMsg.ruleId = res.data
        })
      },
      unstartVersion(){
        unstart(this.ruleMsg.ruleId).then(res => {
          this.ruleMsg.ruleId = res.data
        })
      },
      //版本信息
      showList(ruleId){
        console.log(ruleId)
        getList(ruleId).then(response => {
          this.versionList = response.data
        })
      },
      // 表单重置
      reset() {
        this.resetForm("form");
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "基本信息";
      },
      // 封装字段检查逻辑
      areFieldsValid() {
        // 使用逻辑与操作符确保两个字段都不为空
        return this.form.ruleVersionName && this.form.ruleVersionCode;
      },
      // 生成代码的方法
      executionGeneration() {
        // 首先检查字段是否有效
        if (!this.areFieldsValid()) {
          if (!this.form.ruleVersionName) {
            this.$message("规则名称不能为空");
          }
          if (!this.form.ruleVersionCode) {
            this.$message("引擎编码不能为空");
          }
          return;
        }
        this.form.ruleId = this.ruleMsg.ruleId;
        generatedCode(this.form).then(response => {
          // 处理生成的代码
          console.log('代码生成成功', response);
          this.addCode = true;
          this.form.ruleVersionType = response.data.ruleVersionType
          this.form.ruleVersionText = response.data.ruleVersionText
        }).catch(error => {
          console.error('代码生成失败', error);
          this.$message("代码生成失败");
        });
      },
        /** 提交按钮 */
      submitForm: function () {
        console.log(this.form)
        this.$refs["form"].validate(valid => {
          if (valid) {
            save(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.addCode = false;
              this.showList(this.ruleMsg.ruleId);
            });
          }
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      //版本激活状态
      startVersionActivate(ruleVersionId){
        startVersion(ruleVersionId).then(response => {
          this.$modal.msgSuccess("激活成功");
          this.showList(this.ruleMsg.ruleId)
        })
      },
      unstartVersionActivate(ruleVersionId){
        unstartVersion(ruleVersionId).then(response => {
          this.$modal.msgSuccess("关闭成功");
          this.showList(this.ruleMsg.ruleId)
        })
      },
      //版本回显
      selectByVersionId(ruleVersionId){
        console.log(ruleVersionId)
        findByRuleVersionId(ruleVersionId).then(response => {
          this.drawer = true
          this.ruleVersion = response.data
        })
      },
      //改变样式
      changeClassName(className) {
        var reg = new RegExp(/public class .*? extends ActionParamBuilder/);
        this.code = this.code.replace(reg,
          "public class " + className + " extends ActionParamBuilder"
        );
      },
      testRule(ruleVersionId){
        console.log(ruleVersionId)
        findByRuleVersionId(ruleVersionId).then(response => {
          this.testRuleVersion = response.data
          this.openTest = true
        })
      },
      //测试
      testData(testRuleVersion){
        console.log(testRuleVersion)
        console.log(this.ruleMsg.ruleRegion)
        if (this.ruleMsg.ruleRegion==='F'){
          compileLoad(testRuleVersion).then(response => {
            this.$modal.msgSuccess(response.msg);
          })
        }
        if (this.ruleMsg.ruleRegion==='R'){
          row(testRuleVersion).then(response => {
            this.$modal.msgSuccess(response.msg);
          })
        }
        if (this.ruleMsg.ruleRegion==='C'){

        }
      },
      //保存代码
      saveVersionCode(ruleVersion){
        console.log(ruleVersion)
        saveCode(ruleVersion).then(response => {
          this.$modal.msgSuccess(response.msg);
        })
      },
      //打开选择框 加载数据库
      selectData(){
        this.selectDataFrame = true
        extractDataName().then(response => {
          this.database = response.data;
          console.log(response)
        })
      },
      //获取库中数据表
      selectTable(dataTableName){
        console.log(dataTableName)
        findSelectDataShow(dataTableName).then(response => {
          this.tableData = response.data
          console.log(this.tableData)
        })
      }
    },
    //生命周期 - 创建完成（可以访问当前this实例）",
    created() {
      const ruleId = this.$route.params && this.$route.params.ruleId;
      this.getRuleMsg(ruleId)
      this.showList(ruleId)
    },
    //生命周期 - 挂载完成（可以访问DOM元素）",
    mounted() {
    },
    beforeCreate() {
    }, //生命周期 - 创建之前",
    beforeMount() {
    }, //生命周期 - 挂载之前",
    beforeUpdate() {
    }, //生命周期 - 更新之前",
    updated() {
    }, //生命周期 - 更新之后",
    beforeDestroy() {
    }, //生命周期 - 销毁之前",
    destroyed() {
    }, //生命周期 - 销毁完成",
    activated() {
    } //如果页面有keep-alive缓存功能，这个函数会触发",
  };
</script>
<style scoped>
  .el-dropdown {
    vertical-align: top;
  }
  .el-dropdown + .el-dropdown {
    margin-left: 15px;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .big-card {
    margin-top: 30px;
  }
  .box-card {
    width: 480px;
  }
  .remark{
    margin-top: 10px;
  }
  .versionType{
    background-color: #5a5e66;
  }
</style>
