<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规则名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入规则名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否激活" prop="isActivate">
        <el-input
          v-model="queryParams.isActivate"
          placeholder="请输入是否激活"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规则代码" prop="ruleCode">
        <el-input
          v-model="queryParams.ruleCode"
          placeholder="请输入规则代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    {{ rule.name }}
    <el-descriptions class="margin-top" :column="3" border>
      <template slot="extra">
        <el-dropdown split-button type="primary">
          更多操作
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <el-button
                type="text"
                @click="handleAdd"
              >新增
              </el-button>
            </el-dropdown-item>
            <el-dropdown-item>开启引擎
              <el-dropdown-item>
                <el-switch
                  style="float: right; margin: 4px 5px 0;"
                  v-model="rule.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-value="Y"
                  inactive-value="N"
                  @change="handleStatus(rule)">
                </el-switch>
              </el-dropdown-item>
            </el-dropdown-item>
            <el-dropdown-item>关闭引擎

            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user"></i>
          主键
        </template>
        {{ rule.id }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user"></i>
          规则名称
        </template>
        {{ rule.name }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user"></i>
          规则类型
        </template>
        {{ rule.ruleType }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user"></i>
          是否激活
        </template>
        <el-tag> {{ rule.isActivate }}</el-tag>


      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user"></i>
          规则描述
        </template>
        {{ rule.ruleDesc }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label">
          <i class="el-icon-user"></i>
          规则代码
        </template>
        {{ rule.ruleCode }}
      </el-descriptions-item>
    </el-descriptions>

    <!--    <pagination-->
    <!--        v-show="total>0"-->
    <!--        :total="total"-->
    <!--        :page.sync="queryParams.pageNum"-->
    <!--        :limit.sync="queryParams.pageSize"-->
    <!--        @pagination="getList"-->
    <!--    />-->


    <br><br>
    <el-row :gutter="10">
      <!--            <el-empty description="暂无支付客户" v-if="customerList.length === 0"></el-empty>-->
      <el-col :span="12" v-for="customer in ruleAndEditionList">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <div>
              <el-descriptions class="margin-top" title="规则引擎版本" :column="3" border>
                <template slot="extra">

                  <el-dropdown>
                <span class="el-dropdown-link">
                    下拉菜单<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item>
                        <el-button
                          size="mini"
                          type="text"
                          icon="el-icon-edit"
                          @click="findByIdVersion(customer.id)"
                          v-hasPermi="['rule:rule:edit']"
                        >规格详情
                        </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button @click="drawers(customer.id)" type="text" style="margin-left: 16px;">
                          规则测试
                        </el-button>
                      </el-dropdown-item>

                      <el-dropdown-item>
                        <el-switch
                          style="float: right; margin: 4px 5px 0;"
                          v-model="customer.status"
                          active-color="#13ce66"
                          inactive-color="#ff4949"
                          active-value="Y"
                          inactive-value="N"
                          @change="handleStatusChange(customer)"
                        >
                        </el-switch>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <!--                  </el-button>-->
                </template>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-user"></i>
                    版本主键
                  </template>
                  {{ customer.id }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-user"></i>
                    版本类
                  </template>
                  {{ customer.ruleKind }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-user"></i>
                    版本名称
                  </template>
                  {{ customer.name }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-user"></i>
                    编码
                  </template>
                  {{ customer.ruleCoding }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-user"></i>
                    是否激活
                  </template>

                  <el-tag>{{ customer.ruleActivate }}</el-tag>

                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    <i class="el-icon-user"></i>
                    状态
                  </template>

                  <el-tag> {{ customer.status }}</el-tag>

                </el-descriptions-item>

                <el-descriptions-item>
                  <div>
                    <editor v-model="customer.ruleContent" :min-height="192"/>
                  </div>
                </el-descriptions-item>


              </el-descriptions>
            </div>

          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改规则版本对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-button type="primary" @click="generate" style="margin-bottom:20px;">生成版本类</el-button>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="版本类" prop="ruleKind">
          <el-input v-model="form.ruleKind" disabled/>
        </el-form-item>
        <el-form-item label="版本名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入版本名称"/>
        </el-form-item>
        <el-form-item label="编码" prop="ruleCoding">
          <el-input v-model="form.ruleCoding" type="textarea" placeholder="请输入编码"/>
        </el-form-item>
        <el-form-item label="是否激活" prop="ruleActivate">
          <el-radio-group v-model="form.ruleActivate" placeholder="请输入是否激活">
            <el-radio label="Y"></el-radio>
            <el-radio label="N"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="ruleActivate">
          <el-radio-group v-model="form.status" placeholder="请输入状态">
            <el-radio label="初始化"></el-radio>
            <el-radio label="正常"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内容" prop="ruleContent">
          <el-input v-model="form.ruleContent" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="版本" prop="ruleId">
          <el-input v-model="form.ruleId" disabled placeholder="请输入版本"/>
        </el-form-item>

        <!--        前台web编写代码-->
        <el-form-item label="引擎编码" prop="ruleEngine">
          <codemirror ref="ruleEngine" :value="form.ruleEngine" :options="cmOptions" class="code">
          </codemirror>
        </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>


    <!--规则测试-->
    <el-drawer
      title="我是标题"
      :visible.sync="drawer"
      :with-header="false" size="70%">
      <span>
<!--      <el-button type="primary" @click="generate" style="margin-bottom:70px;">生成版本类</el-button>-->
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="版本类" prop="ruleKind">
          <el-input v-model="form.ruleKind" disabled/>
        </el-form-item>
        <el-form-item label="版本名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入版本名称"/>
        </el-form-item>
        <el-form-item label="编码" prop="ruleCoding">
          <el-input v-model="form.ruleCoding" type="textarea" placeholder="请输入编码"/>
        </el-form-item>
        <el-form-item label="是否激活" prop="ruleActivate">
          <el-radio-group v-model="form.ruleActivate" placeholder="请输入是否激活">
            <el-radio label="Y"></el-radio>
            <el-radio label="N"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="ruleActivate">
          <el-radio-group v-model="form.status" placeholder="请输入状态">
            <el-radio label="初始化"></el-radio>
            <el-radio label="正常"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内容" prop="ruleContent">
          <el-input v-model="form.ruleContent" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="版本" prop="ruleId">
          <el-input v-model="form.ruleId" disabled placeholder="请输入版本"/>
        </el-form-item>
        <!--        前台web编写代码-->
        <el-form-item label="引擎编码" prop="ruleEngine">
          <codemirror ref="ruleEngine" :value="form.ruleEngine" v-model="form.ruleEngine" :options="cmOptions"
                      class="code">
          </codemirror>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="preserve()">保存代码</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      </span>
      <br>
      <span>
        <el-row>
          <el-col :span="12">
            <el-card class="box-card">
          <div slot="header" class="clearfix">
              <span>选择数据接入</span>
          </div>
        <el-select v-model="dataOrigin.sourceId" placeholder="请选择数据接入" @change="chan()">
          <el-option v-for="i in origins" :label="i.tableName" :value="i.id" :key="i.id"></el-option>
        </el-select>
            </el-card>
          </el-col>
              <el-col :span="12" v-show="selects">
                <el-card class="box-card">
          <div slot="header" class="clearfix">
        <span>选择资产结构</span>
          </div>
      <span>
          <el-select v-model="dataOrigin.tableId" placeholder="请选择数据结构" @change="ch()">
              <el-option v-for="i in tableOrigin" :label="i.tableName" :value="i.id" :key="i.id"></el-option>
          </el-select>
      </span>
                </el-card>
              </el-col>
            </el-row>
                      <el-col v-show="selectss">
                <el-card class="box-card">
          <div slot="header" class="clearfix">
        <span>选择资产集</span>
            <template>
              {{tableDatas}}
              <el-table>
                 <el-table-column
                   v-for="tableData in tableDatas"
                   :label="tableData.label"
                   width="180">
                   {{tableData.value}}
    </el-table-column>
                <el-table-column label="操作">

      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEditSelect(scope.row)">选择
        </el-button>
      </template>
    </el-table-column>
              </el-table>
</template>
          </div>
        <span>
          <template slot-scope="scope">
        <el-button
          type="primary"
          @click="measurements(scope.row)">测试
        </el-button>
      </template>
        </span>
                </el-card>
              </el-col>
      </span>

    </el-drawer>

  </div>
</template>

<script>
import {delRule, getRule} from "/src/api/rule/rule";
import {
  addGenerate,
  addRule,
  disable,
  enable, findTableIdByParentId,
  getEditionList,
  getFindByEditionId, selectById, measurement,
  updateRule, updateRuleEngine, findTableValueByTableName
} from "@/api/rule/ruleEdition";


import {codemirror} from 'vue-codemirror'
import "codemirror/theme/ambiance.css";
import select from "view-design/src/components/select"; // 这里引入的是主题样式，根据设置的theme的主题引入，一定要引入！！
require("codemirror/mode/javascript/javascript"); // 这里引入的模式的js，根据设置的mode引入，一定要引入！

export default {
  name: "Rule",
  computed: {
    select() {
      return select
    }
  },
  data() {
    return {
      selects: false,
      selectss: false,
      drawer: false,
      cmOptions: {
        lineNumbers: true, // 显示行号
        mode: 'text/x-yaml', // 语法model
        gutters: ['CodeMirror-lint-markers'], // 语法检查器
        theme: "ambiance",
        lint: true, // 开启语法检查
      },
      tableData: [],
      tableDatas: [],
      ruleAndEditionList: [],
      //版本
      ruleAndEdition: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      childId: {},
      // 规则表格数据
      ruleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // opens: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        ruleType: null,
        isActivate: null,
        ruleDesc: null,
        ruleCode: null,
      },
      ruleAndVersion: {
        id: "",
        name: "",
        ruleType: "",
        isActivate: "",
        ruleDesc: "",
        ruleCode: ""
      },
      rule: {},
      // 表单参数
      form: {
        id: '',
        ruleKind: 'null',
        name: '',
        ruleCoding: '',
        ruleActivate: '',
        status: '',
        ruleContent: '',
        ruleId: '',
        ruleEngine: '',
      },
      //数据源
      dataOrigin: {},
      origins: [],

      tableOrigin: [],
      showCode: false,
      // 表单校验
      rules: {
        isActivate: [
          {required: true, message: "是否激活;是否激活不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.ruleAndVersion.id = this.$route.query.id
    this.findById();
    this.findList()
    this.getDataOrigin()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）",
  mounted() {
    this.findById();
  },
  methods: {
    //表数据
    handleEditSelect(data) {
      console.log(data.basicId);
      console.log(data.tableName);
      findTableValueByTableName(data.basicId, data.tableName).then(res => {
        console.log(res.data)
        this.tableDatas = res.data
        alert(res.data)
      })
    },
    //规则测试
    measurements(data) {
      this.tableDatas=data
      measurement(data).then(res => {
        this.$modal.msgSuccess("操作成功");
      })
    },
    //保存代码
    preserve() {
      this.$refs["form"].validate(valid => {
        updateRuleEngine(this.form).then(response => {
          alert(this.form.ruleEngine)
          // console.log(this.form)
          this.$modal.msgSuccess("修改成功");
        });
      });
    },


    //数据接入源
    getDataOrigin() {
      selectById(this.dataOrigin).then(res => {
        this.origins = res.data
        // console.log("origins", this.origins)
      })
    },

    chanChild() {
      findTableIdByParentId(this.dataOrigin.sourceId).then(res => {
        this.tableOrigin = res.data
        // console.log(this.tableOrigin)
      })
    },
    //禁用
    handleStatus() {
      if (row.status === "Y") {
        enable(row.id).then((res) => {
          this.$modal.msgSuccess("启用成功")
          this.findList()
        })
      } else {
        disable(row.id).then((res) => {
          this.$modal.msgSuccess("禁用成功")
          this.findList()
        })
      }
    },
    //数据源
    chan() {
      this.selects = true
      this.chanChild()
    },
    ch() {
      this.selectss = true
    },
    //测试规则
    drawers(id) {
      getFindByEditionId(id).then(res => {
        this.form = res.data[0]
        this.drawer = true
        console.log(this.form)
      })
    },
    //生成版本类
    generate() {
      addGenerate(this.form).then(res => {
        this.form.ruleKind = res.data.ruleKind
        this.form.ruleEngine = res.data.ruleEngine
        alert(this.form.ruleEngine)
        this.showCode = true
        this.findList()
        debugger
      })
    },
    //版本card
    findList() {
      getEditionList(this.ruleAndVersion.id).then(res => {
        this.ruleAndEditionList = res.data
      })
    },
    //根据ID回显
    findById() {
      getRule(this.ruleAndVersion.id).then(res => {
        this.rule = res.data[0]
      })
    },
    //根据ID回显版本
    findByIdVersion(id) {
      getFindByEditionId(id).then(res => {
        this.form = res.data[0]
        this.open = true;
      })
    },


    /** 客户状态更改触发 */
    handleStatusChange(row) {
      if (row.ruleActivate === "Y") {
        enable(row.id).then((res) => {
          this.$modal.msgSuccess("启用成功")
          this.findList()
        })
      } else {
        disable(row.id).then((res) => {
          this.$modal.msgSuccess("禁用成功")
          this.findList()
        })
      }
    },
    // /** 查询规则列表 */
    // getList() {
    //   this.loading = true;
    //   listRule(this.queryParams).then(response => {
    //     this.ruleList = response.data;
    //     this.total = response.data;
    //     this.loading = false;
    //   });
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        ruleType: null,
        isActivate: null,
        ruleDesc: null,
        ruleCode: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // this.getList();
    },
    /** 重置按钮操作 */
    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;
      2
      this.form.ruleId = this.ruleAndVersion.id
      this.title = "添加规则";
    },
    // /** 规则维护按钮操作 */
    // handleMaintain(row) {
    //   this.$router.push({
    //     path: 'version',
    //     query: {id: row.id}
    //   })
    // },
    /** 修改按钮操作 */
    handleUpdate(id) {
      this.reset();
      // const id = row.id || this.ids
      updateRule(id).then(response => {
        this.form = response.data[0];
        this.open = true;
        this.title = "修改规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              // this.getList();
            });
          } else {
            addRule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.form.ruleId = this.rule.id
              console.log(this.form.ruleId)
              this.open = false;
              // this.getList();
              this.findList()
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除规则编号为"' + ids + '"的数据项？').then(function () {
        return delRule(ids);
      }).then(() => {
        // this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rule/rule/export', {
        ...this.queryParams
      }, `rule_${new Date().getTime()}.xlsx`)
    }
  },
  components: {
    codemirror
  },

};
</script>
<style scoped>
.information-box >>> .CodeMirror {
  font-family: monospace;
  height: 71vh;
  direction: ltr;
}
</style>
