<template>
  <div style="padding: 30px" v-loading="loading">
    <el-descriptions class="margin-top" :title="`${ruleData.ruleCode}规则版本`" :column="3" border
                     style="font-size: 14px">
      <template slot="extra">
        <el-dropdown style="float:right;padding: 3px 0" v-hasPermi="['system:user:resetPwd', 'system:user:edit']"
                     @command="(command) => handleCommand(command, ruleData)">
          <el-button type="primary">更多操作 <i class="el-icon-caret-bottom"></i></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-hasPermi="['engine:ruleVersion:add']" command="handleAdd"
                              icon="el-icon-circle-plus">版本添加
            </el-dropdown-item>
            <el-dropdown-item v-hasPermi="['engine:ruleInfo:edit']" command="handleActivation"
                              icon="el-icon-circle-check" v-if="ruleData.isActivation === 'N'">激活引擎
            </el-dropdown-item>
            <el-dropdown-item v-hasPermi="['engine:ruleInfo:edit']" command="handleForbidden"
                              icon="el-icon-circle-close" v-if="ruleData.isActivation === 'Y'">禁用引擎
            </el-dropdown-item>
            <el-dropdown-item v-hasPermi="['engine:ruleInfo:edit']" command="handleRuleOpen"
                              icon="el-icon-switch-button" v-if="ruleData.status==='1'">开启引擎
            </el-dropdown-item>
            <el-dropdown-item v-hasPermi="['engine:ruleInfo:edit']" command="handleRuleClose"
                              icon="el-icon-circle-close" v-if="ruleData.status==='0'">关闭引擎
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
      <el-descriptions-item>
        <template slot="label">
          规则名称
        </template>
        {{ ruleData.ruleName }}
      </el-descriptions-item>
      <el-descriptions-item span="2">
        <template slot="label">
          <i class="el-icon-tickets"></i>
          引擎编码
        </template>
        {{ ruleData.ruleCode }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-mobile-phone"></i>
          规则类型
        </template>
        <dict-tag :options="dict.type.etl_rule_type" :value="ruleData.ruleTypeValue"/>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-office-building"></i>
          是否激活
        </template>
        <dict-tag :options="dict.type.etl_rule_status" :value="ruleData.isActivation"/>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-office-building"></i>
          规则状态
        </template>
        <dict-tag :options="dict.type.sys_normal_disable" :value="ruleData.status"/>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-office-building"></i>
          规则详情
        </template>
        <span v-html="ruleData.ruleExplain"/>
      </el-descriptions-item>
    </el-descriptions>

    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>规则引擎版本</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="12" v-for="ruleVersion in ruleData.ruleVersionList" style="margin-bottom: 20px;">
          <div class="grid-content bg-purple">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>{{ ruleVersion.ruleVersionName }}-{{ ruleVersion.ruleVersionCode }}</span>
                <el-dropdown style="float:right"
                             v-hasPermi="['system:user:resetPwd', 'system:user:edit']"
                             @command="(command) => handleRuleVersionCommand(command, ruleVersion)">
                  <el-button type="text">更多操作<i class="el-icon-arrow-down"></i></el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-hasPermi="['engine:ruleVersion:edit']" command="handleVersionDetails"
                                      icon="el-icon-s-unfold">规则详情
                    </el-dropdown-item>
                    <el-dropdown-item v-hasPermi="['engine:ruleVersion:edit']" command="handleOpenTest"
                                      icon="el-icon-position">测试规则
                    </el-dropdown-item>
                    <el-dropdown-item v-hasPermi="['engine:ruleVersion:edit']" command="handleVersionActivation"
                                      icon="el-icon-switch-button" v-if="ruleVersion.ruleVersionIsActivation==='N'">激活规则
                    </el-dropdown-item>
                    <el-dropdown-item v-hasPermi="['engine:ruleVersion:edit']" command="handleVersionDisable"
                                      icon="el-icon-switch-button" v-if="ruleVersion.ruleVersionIsActivation==='Y'">禁用规则
                    </el-dropdown-item>
                    <el-dropdown-item v-hasPermi="['engine:ruleVersion:edit']" command="handleVersionClass"
                                      icon="el-icon-edit">编写规则类
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>

              <el-descriptions class="margin-top" :column="2" border style="font-size: 14px">
                <el-descriptions-item span="2">
                  <template slot="label">
                    <i class="el-icon-user"></i>
                    版本类
                  </template>
                  {{ ruleVersion.ruleVersionClass }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-mobile-phone"></i>
                    版本名称
                  </template>
                  {{ ruleVersion.ruleVersionName }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-location-outline"></i>
                    版本CODE
                  </template>
                  {{ ruleVersion.ruleVersionCode }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-tickets"></i>
                    是否激活
                  </template>
                  <dict-tag :options="dict.type.etl_rule_status" :value="ruleVersion.ruleVersionIsActivation"/>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-office-building"></i>
                    版本状态
                  </template>
                  <dict-tag :options="dict.type.version_status" :value="ruleVersion.ruleVersionStatus"/>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-office-building"></i>
                    是否测试
                  </template>
                  <dict-tag :options="dict.type.version_test" :value="ruleVersion.ruleVersionIsTest"/>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-office-building"></i>
                    规则作用域
                  </template>
                  <dict-tag :options="dict.type.rule_version_scope" :value="ruleVersion.ruleVersionScope"/>
                </el-descriptions-item>
                <el-descriptions-item span="2">
                  <template slot="label">
                    <i class="el-icon-office-building"></i>
                    版本描述
                  </template>
                  <span v-html="ruleVersion.ruleVersionDescribed"></span>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 添加或修改规则版本对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="版本名称" prop=ruleVersionName>
                <el-input v-model="form.ruleVersionName" placeholder="请输入版本名称"/>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="版本CODE" prop="ruleVersionCode">
                <el-input v-model="form.ruleVersionCode" placeholder="请输入版本CODE"/>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="是否激活" prop="ruleVersionIsActivation">
                <dict-tag :options="dict.type.etl_rule_status" :value="form.ruleVersionIsActivation"/>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-form-item label="版本状态" prop="ruleVersionStatus">
                <dict-tag :options="dict.type.version_status" :value="form.ruleVersionStatus"/>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="grid-content bg-purple">
              <el-form-item label="版本作用域" prop="ruleVersionScope">
                <el-select v-model="form.ruleVersionScope" placeholder="请选择规则作用域" clearable>
                  <el-option
                    v-for="dict in dict.type.rule_version_scope"
                    :key="dict.value"
                    :label="`${dict.label} (${dict.raw.remark})`"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="grid-content bg-purple">
              <el-form-item label="版本描述" prop="ruleVersionDescribed">
                <editor v-model="form.ruleVersionDescribed" :min-height="192"/>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="grid-content bg-purple">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="this.form.addClass">
          <el-col :span="24">
            <div class="content">
              <div class="code-edit">
                <codemirror ref="codeMirror" v-model="form.classContent" :options="cmOptions"
                            style="height:100%;width:97%;margin: 20px" :disabled="!cmOptions.readOnly"/>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        <el-button type="primary" @click="generateVerSionClass('form')">生成引擎版本类</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer
      :title="drawer.title"
      :visible.sync="drawer.open"
      :direction="drawer.direction"
      :before-close="handleClose" size="80%">
      <div>
        <el-descriptions class="margin-top" :column="2" border style="font-size: 16px;margin: 20px">
          <el-descriptions-item span="2">
            <template slot="label">
              <i class="el-icon-user"></i>
              版本类
            </template>
            {{ drawer.data.ruleVersionClass }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-mobile-phone"></i>
              版本名称
            </template>
            {{ drawer.data.ruleVersionName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-location-outline"></i>
              版本CODE
            </template>
            {{ drawer.data.ruleVersionCode }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-tickets"></i>
              是否激活
            </template>
            <dict-tag :options="dict.type.etl_rule_status" :value="drawer.data.ruleVersionIsActivation"/>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              版本状态
            </template>
            <dict-tag :options="dict.type.version_status" :value="drawer.data.ruleVersionStatus"/>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              是否测试
            </template>
            <dict-tag :options="dict.type.version_test" :value="drawer.data.ruleVersionIsTest"/>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              规则作用域
            </template>
            <dict-tag :options="dict.type.rule_version_scope" :value="drawer.data.ruleVersionScope"/>
          </el-descriptions-item>
          <el-descriptions-item span="2">
            <template slot="label">
              <i class="el-icon-office-building"></i>
              版本描述
            </template>
            <span v-html="drawer.data.ruleVersionDescribed"></span>
          </el-descriptions-item>
        </el-descriptions>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>规则代码编辑</span>
            <el-dropdown style="float:right"
                         v-hasPermi="['system:user:resetPwd', 'system:user:edit']"
                         @command="(command) => handleRuleVersionClassCommand(command,drawer.data)">
              <el-button type="text">更多操作<i class="el-icon-arrow-down"></i></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-hasPermi="['engine:ruleVersion:edit']" command="handleConserve"
                                  icon="el-icon-s-claim">保存
                </el-dropdown-item>
                <el-dropdown-item v-hasPermi="['engine:ruleVersion:edit']" command="handleOpenTest"
                                  icon="el-icon-position">测试
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="content">
            <div class="code-edit">
              <codemirror ref="codeMirror" v-model="drawer.data.classContent" :options="cmOptions"
                          style="height:100%;width:97%;margin: 20px" :disabled="!cmOptions.readOnly"/>
            </div>
          </div>
        </el-card>
      </div>
    </el-drawer>

    <!-- 添加或修改规则版本对话框 -->
    <el-dialog :title="testData.title" :visible.sync="testData.open" width="80%" append-to-body v-loading="loading">
      <el-container style="height: 500px" v-if="active===0">
        <el-aside width="250px" title="数据库/表">
          <el-tree :data="tableInfoList" :props="{label:'tableName', children:'children'}">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span @click="getDataAnalysis(data)">{{ data.tableName }}</span>
            </span>
          </el-tree>
        </el-aside>
        <el-container>
          <el-main>
            <el-table
              :data="dataAnalysis"
              style="width: 100%"
              :key="new Date().getTime()"
              @selection-change="handleSelectionTestChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column label="名称" prop="columnName"></el-table-column>
              <el-table-column label="注释" prop="columnRemark"></el-table-column>
              <el-table-column label="是否主键" prop="isPrimary">
                <template slot-scope="scope">
                  <span v-if="scope.row.isPrimary==='Y'">
                    <el-tag type="success">{{ scope.row.isPrimary }}</el-tag>
                  </span>
                  <span v-if="scope.row.isPrimary==='N'">
                    <el-tag type="danger">{{ scope.row.isPrimary }}</el-tag>
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="类型" prop="columnType"></el-table-column>
              <el-table-column label="映射类型" prop="javaType"></el-table-column>
              <el-table-column label="长度" prop="columnLength"></el-table-column>
              <el-table-column label="小数位" prop="columnDecimals"></el-table-column>
              <el-table-column label="是否为空" prop="isNull">
                <template slot-scope="scope">
                  <span v-if="scope.row.isNull==='Y'">
                    <el-tag type="success">{{ scope.row.isNull }}</el-tag>
                  </span>
                  <span v-if="scope.row.isNull==='N'">
                    <el-tag type="danger">{{ scope.row.isNull }}</el-tag>
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="默认值" prop="defaultValue"></el-table-column>
              <el-table-column label="是否字典" prop="isDictionary"></el-table-column>
              <el-table-column label="映射字典" prop="dictionaryTable"></el-table-column>
            </el-table>
          </el-main>
        </el-container>
      </el-container>
      <div v-if="active===1" style="height: 500px">
        <el-card class="box-card"  >
          <div slot="header" class="clearfix">
            <span>测试数据</span>
            <el-button type="primary" style="float: right; padding: 3px 0" @click="testDemo()" v-if="active === 1">
              测试
            </el-button>
          </div>
          <el-table
            :data="dataStructureList"
            height="400"
            highlight-current-row
            @current-change="handleCurrentChange"
            ref="singleTable">
          <span v-for="data in dataLabel">
            <el-table-column
              :prop="data.key"
              :label="data.label"
            >
          </el-table-column>
          </span>
          </el-table>
        </el-card>
        <el-divider v-if="afterShow">转换后的数据</el-divider>
        <el-card class="box-card"  v-if="afterShow">
          <el-table
            :data="afterData"
            style="width: 100%"
            highlight-current-row
          >
          <span v-for="data in afterLabel">
            <el-table-column
              :prop="data.key"
              :label="data.label"
            >
          </el-table-column>
          </span>
          </el-table>
        </el-card>
      </div>


      <div slot="footer" class="dialog-footer">
        <el-button style="margin-top: 12px;" @click="nextDataTest" v-if="active === 0">下一步</el-button>
        <el-button style="margin-top: 12px;" @click="active--;testData.title = '测试页面'" v-if="active === 1">上一步
        </el-button>
        <el-button @click="cancelTestData">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）,
//例如：import 《组件名称》 from '《组件路径》,

import {getRuleInfo, updateRuleInfo} from "@/api/engine/ruleInfo";
import {
  listRuleVersion,
  getRuleVersion,
  delRuleVersion,
  addRuleVersion,
  updateRuleVersion, writeFile, readFile, getTableInfoList, getDataAnalysis, getEtlTableData, lineFile, isClassExist
} from "@/api/engine/ruleVersion";

// cm-setting.js
// 组件样式
import {codemirror} from 'vue-codemirror'
import 'codemirror/mode/clike/clike'
// cm-setting.js
// 组件样式
import 'codemirror/lib/codemirror.css'
// 主题
import 'codemirror/theme/eclipse.css'
import 'codemirror/theme/monokai.css'
import 'codemirror/theme/idea.css'

// html代码高亮
import 'codemirror/mode/htmlmixed/htmlmixed.js'

// 语言模式
import 'codemirror/mode/javascript/javascript.js'
import 'codemirror/mode/css/css.js'
import 'codemirror/mode/xml/xml.js'
// 代码展开折叠
import 'codemirror/addon/fold/foldcode.js'
import 'codemirror/addon/fold/foldgutter.js'
import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/addon/fold/brace-fold.js'
import {Base64} from "js-base64";


export default {
  name: "ruleVersion",
  dicts: ['etl_rule_type', 'etl_rule_status', 'version_status', 'sys_normal_disable', 'version_test', 'rule_version_scope'],
  //import引入的组件需要注入到对象中才能使用"
  // 注册使用
  components: {
    codemirror,
  },
  props: {},
  data() {
    //这里存放数据"
    return {
      testDataRow: [],
      testData: {
        open: false,
        loading: true,
        data: {
          rows: []
        }
      },
      //测试类数据
      testDataDemo: {
        data: []
      },
      //测试数据
      dataLabel: [],
      dataStructureList: [],
      active: 0,
      dataAnalysis: [],
      testIds: [],
      codemirror: null,
      code: '// Your Java code here',
      cmOptions: {
        autoRefresh: true, // 重点是这句，为true
        value: '', // 初始内容
        mode: 'text/x-java', //实现Java代码高亮
        tabSize: 4, // tab的空格宽度
        styleActiveLine: true, // 设置光标所在行高亮true/false
        lineNumbers: true, //显示行号
        theme: 'monokai', //设置主题cobalt/monokai
        // json: true,
        readOnly: false, // 设置为只读true/false;也可设置为"nocursor"失去焦点
        lineWrapping: false,
        foldGutter: true,
        extraKeys: {
          // 触发提示按键
          Ctrl: 'autocomplete',
        },
        hintOptions: {
          // 自定义提示选项
          completeSingle: false, // 当匹配只有一项的时候是否自动补全
          tables: {
            users: ['name', 'score', 'birthDate'],
            countries: ['name', 'population', 'size']
          }, // 代码提示
        },
        gutters: [
          'CodeMirror-lint-markers', //代码错误检测
          'CodeMirror-linenumbers',
          'CodeMirror-foldgutter', //展开折叠
        ],
      },
      //表二级联动
      tableInfoList: [],
      tableIds: [],
      ruleData: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 规则版本表格数据
      ruleVersionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleVersionName: null,
        ruleVersionCode: null,
        ruleVersionIsActivation: null,
        ruleVersionIsTest: null,
        ruleVersionStatus: null,
        ruleVersionScope: null
      },
      afterData:[],
      afterLabel:[],
      afterShow: false,
      //抽屉
      drawer: {
        open: false,
        direction: 'rtl',
        data: {},
        classContent: ''
      },
      tableTest: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ruleVersionName: [
          {required: true, message: '请输入版本名称', trigger: 'blur'},
        ],
        ruleVersionCode: [
          {required: true, message: '请输入版本CODE', trigger: 'blur'},
        ],
        ruleVersionScope: [
          {required: true, message: '请选择版本作用域', trigger: 'change'}
        ],
      },
    };
  },
  //计算属性 类似于data概念",
  computed: {},
  //监控data中的数据变化",
  watch: {},
  //方法集合",
  //生命周期 - 创建完成（可以访问当前this实例）",
  created() {
    this.getRuleData()
  },
  methods: {
    isClassExist(val){
      let flag = false
      isClassExist(val).then(
        res=>{
          if (res.data){
            this.$message.error("该类已存在，请更改版本CODE")
            flag = true
          }
        }
      )
      return flag
    },
    setCurrentRow(val) {
      this.$refs.singleTable.setCurrentRow(val);
    },
    handleCurrentChange(val) {
      console.log(val)
      this.setCurrentRow(val)
    },
    nextDataTest() {
      this.afterShow = false
      this.loading = true
      this.testData.data.rows = this.testIds

      console.log(this.tableData)
      this.testData.data['columnName'] = this.getDatabaseName(this.testData.data.basicId);
      console.log(this.testData.data)
      getEtlTableData(this.testData.data).then(
        res => {
          let dataList = res.data;
          let conListArr = this.conList(dataList);
          this.dataLabel = conListArr.dataLabel
          this.dataStructureList = conListArr.dataStructureList
          this.testDataDemo.data = dataList
          console.log(this.dataStructureList)
          this.loading = false
          this.active++;
          this.testData.title = '选择数据'
        }
      )
    },
    //转换后赋值
    conAfterDataMethod(dataList){
      let conListArr = this.conList(dataList);
      this.afterData = conListArr.dataStructureList
      this.dataLabel = conListArr.dataLabel
      console.log(conListArr)
      this.loading = false
    },
    conList(dataList) {
      let dataStructureList = []
      let dataLabel = []
      for (let dataI in dataList) {
        let dataSource = {}
        for (let i in dataList[dataI]) {
          if (dataI == 0) {
            dataLabel.push({label: dataList[dataI][i].label, key: dataList[dataI][i].key})
          }
          dataSource[dataList[dataI][i].key] = dataList[dataI][i].value
        }
        dataStructureList.push(dataSource)
      }
      return {dataLabel: dataLabel, dataStructureList: dataStructureList}
    },
    testDemo() {
      this.loading = true
      console.log(this.testDataDemo)
      console.log(this.testDataDemo.data)
      lineFile(this.testDataDemo).then(res => {
        console.log(res.data)
        this.afterShow = true
        this.conAfterDataMethod(res.data)
      })
    },
    handleSelectionTestChange(val) {
      if (val !== null && val.length !== 0) {
        this.testIds = val
        console.log(val)
      }
    },
    cancelTestData() {
      this.testData = {
        open: false,
        loading: true,
      }
      this.dataAnalysis = []
    },
    getDataAnalysis(row) {
      this.loading = true
      this.testData.data = row

      console.log(this.testData.data)
      getDataAnalysis(row.id).then(
        res => {
          this.dataAnalysis = res.data
          this.loading = false
        }
      )
    },
    getDatabaseName(id){
      let tableInfoList = this.tableInfoList;
      let databaseName = '';
      for (let i in tableInfoList) {
        if (tableInfoList[i].basicId == id){
          databaseName = tableInfoList[i].tableName
          break
        }
      }
      if (databaseName==''){
        this.$message.error("没有这个库")
      }
      return databaseName;
    },
    getTableInfoRespList() {
      getTableInfoList().then(res => {
        this.tableInfoList = res.data
        this.tableTest = true
        this.testData.loading = false
        this.loading = false
      })
    },
    generateVerSionClass() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.authClass()
        }
      })
    },
    authClass() {
      let extendsClass = '';
      switch (this.form.ruleVersionScope) {
        case '1':
          extendsClass = 'DataEngineValueActuator';
          break
        case '2':
          extendsClass = 'DataEngineRowActuator';
          break
        case '3':
          extendsClass = 'DataEngineRowsActuator';
          break
        default:
          this.$message.error("规则作用域类型错误---！！！")
          return
      }
      console.log(1)
      let ClassName = "ENGINE_" + this.ruleData.ruleCode + "_" + this.form.ruleVersionCode;
      let b = this.isClassExist(ClassName);
      if (b){
        return;
      }
      this.form.addClass = true;
      this.form['classContent'] = 'package com.muyu.etl.rule;\n' +
        '\n' +
        'import com.muyu.domain.DataStructure;\n' +
        'import com.muyu.etl.rule.basic.abstracts.' + extendsClass + ';\n' +
        '\n' +
        '/**\n' +
        ' * @Author WangXin\n' +
        ' * @Data ' + new Date() + '\n' +
        ' * @Description ' + this.form.ruleVersionDescribed + '\n' +
        ' * @Version 1.0.0\n' +
        ' */\n' +
        'public class ' + ClassName + ' extends ' + extendsClass + ' {\n' +
        '    \n' +
        '    \n' +
        '    @Override\n' +
        '    public void run() {\n' +
        '\n' +
        '    }\n' +
        '}'
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.loading = true
          done();
          this.tableTest = false
          this.loading = false
        })
        .catch(_ => {
        });
    },
    //规则激活
    handleActivation(id, isActivation) {
      updateRuleInfo({id, isActivation}).then(res => {
        if (res.code === 200) {
          this.$message.success('激活成功')
          this.resetQuery()
        }
      })
    },
    //规则禁用
    handleForbidden(id, isActivation) {
      this.$confirm('确认禁用？')
        .then(_ => {
          updateRuleInfo({id, isActivation}).then(res => {
            if (res.code === 200) {
              this.$message.success('禁用成功')
              this.resetQuery()
            }
          })
        })
        .catch(_ => {
        });
    },
    //规则开启
    handleRuleOpen(id, status) {
      updateRuleInfo({id, status}).then(res => {
        if (res.code === 200) {
          this.$message.success('规则开启')
          this.resetQuery()
        }
      })
    },
    //规则关闭
    handleRuleClose(id, status) {
      this.$confirm('确认关闭？')
        .then(_ => {
          updateRuleInfo({id, status}).then(res => {
            if (res.code === 200) {
              this.$message.success('规则关闭')
              this.resetQuery()
            }
          })
        })
        .catch(_ => {
        });
    },
    //规则操作
    handleCommand(command, row) {
      switch (command) {
        case 'handleAdd':
          this.handleAdd();
          break
        case 'handleActivation':
          this.handleActivation(row.id, 'Y');
          break
        case 'handleForbidden':
          this.handleForbidden(row.id, 'N');
          break
        case 'handleRuleOpen':
          this.handleRuleOpen(row.id, 0);
          break
        case 'handleRuleClose':
          this.handleRuleClose(row.id, 1);
          break
        default:
          break;
      }
    },
    //规则操作
    handleRuleVersionCommand(command, row) {
      switch (command) {
        case 'handleVersionDetails':
          this.handleVersionDetails(row.id);
          break
        case 'handleOpenTest':
          this.handleOpenTest(row);
          break
        case 'handleVersionActivation':
          this.handleVersionActivation(row.id, 'Y');
          break
        case 'handleVersionDisable':
          this.handleVersionDisable(row.id, 'N');
          break
        case 'handleVersionClass':
          this.handleVersionClass(row.id);
          break
        default:
          break;
      }
    },
    //规则操作
    handleRuleVersionClassCommand(command, row) {
      switch (command) {
        case 'handleOpenTest':
          this.handleOpenTest(row.id);
          break
        case 'handleConserve':
          this.handleConserve(row);
          break
        default:
          break;
      }
    },
    handleConserve(row) {
      writeFile({fileName: row.ruleVersionClass, content: Base64.encode(row.classContent)}).then(
        res => {
          if (res.code === 200) {
            this.$message.success("保存成功")
            this.closeRuleVersion();
          }
        }
      )
    },
    closeRuleVersion() {
      this.drawer = {
        open: false,
        direction: 'rtl',
        data: {},
        classContent: ''
      }
    },
    handleVersionDetails(id) {
      this.loading = true
      getRuleVersion(id).then(response => {
        readFile(response.data.ruleVersionClass).then(
          res => {
            this.drawer = {
              open: true,
              direction: 'rtl',
              data: response.data,
              title: '规则版本详情'
            }
            this.drawer.data.classContent = res.data
            this.cmOptions.readOnly = true
            this.loading = false
          }
        )
      })
    },
    handleOpenTest(row) {
      this.loading = true
      getRuleVersion(row.id).then(response => {
        readFile(response.data.ruleVersionClass).then(
          res => {
            this.testData = {
              open: true,
              data: response.data,
              title: '测试页面'
            }
            this.testDataDemo = row
            this.drawer.data.classContent = res.data
            this.cmOptions.readOnly = true
            this.getTableInfoRespList()
          }
        )
      })
    },
    handleVersionActivation(id, ruleVersionIsActivation) {
      this.loading = true
      updateRuleVersion({id, ruleVersionIsActivation}).then(response => {
        this.$modal.msgSuccess("激活成功");
        this.getRuleData();
      });
    },
    handleVersionDisable(id, ruleVersionIsActivation) {
      this.loading = true
      updateRuleVersion({id, ruleVersionIsActivation}).then(response => {
        this.$modal.msgSuccess("禁用成功");
        this.getRuleData();
      });
    },
    handleVersionClass(id) {
      this.loading = true
      getRuleVersion(id).then(response => {
        readFile(response.data.ruleVersionClass).then(
          res => {
            this.drawer = {
              open: true,
              direction: 'rtl',
              data: response.data,
              title: '规则版本编辑'
            }
            this.drawer.data.classContent = res.data
            this.cmOptions.readOnly = false
            this.loading = false
          }
        )
      })
    },
    getRuleData() {
      const ruleId = this.$route.params && this.$route.params.ruleId
      if (ruleId) {
        // 获取表详细信息
        getRuleInfo(ruleId).then(res => {
          this.ruleData = res.data
          this.loading = false
        })
      } else {
        this.$message.error("系统内部错误")
      }
    },
    /** 查询规则版本列表 */
    getList() {
      this.loading = true;
      listRuleVersion(this.queryParams).then(response => {
        this.ruleVersionList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ruleVersionClass: null,
        ruleVersionName: null,
        ruleVersionCode: null,
        ruleVersionIsActivation: 'N',
        ruleVersionIsTest: null,
        ruleVersionStatus: 0,
        ruleVersionDescribed: null,
        ruleId: this.$route.params && this.$route.params.ruleId,
        remark: null,
        classContent: '',
        addClass: false
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getRuleData();
    },
    /** 重置按钮操作 */
    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.title = "添加规则版本";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRuleVersion(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改规则版本";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          if (this.form.id != null) {
            updateRuleVersion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getRuleData();
            });
          } else {
            if (this.form.ruleVersionClass === undefined || this.form.ruleVersionClass === null || this.form.ruleVersionClass === '') {
              this.form.ruleVersionClass = "ENGINE_" + this.ruleData.ruleCode + "_" + this.form.ruleVersionCode;
            }
            if (this.isClassExist(this.form.ruleVersionClass)){
              return;
            }
            if (this.form.classContent === undefined || this.form.classContent === null || this.form.classContent === '') {
              this.$message.warning("请输入类的内容")
              return
            }
            this.form.classContent = Base64.encode(this.form.classContent)
            addRuleVersion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.getRuleData();
              this.open = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除规则版本编号为"' + ids + '"的数据项？').then(function () {
        return delRuleVersion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('engine/ruleVersion/export', {
        ...this.queryParams
      }, `ruleVersion_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

