<template>
  <div class="cqcy-content" style="margin: 0;height: calc(100% - 70px);">
    <breadcrumb-view :breadcrumbList="breadcrumbList" :show-index="false"></breadcrumb-view>
    <el-button type="primary" class="cy-nav-btn" icon="el-icon-circle-plus-outline" size="mini" @click="handleAdd">新增</el-button>
    <el-divider></el-divider>
    <div class="cy-main">
      <el-table
          :data="tableData" border :stripe="true"
          :header-cell-style="{background: '#E8E8E8'}"
          style="width: 100%;">
        <el-table-column align="center"
            label="四则运算表达式"
            prop="operationRule"
            width="300">
        </el-table-column>
        <el-table-column align="center"
            label="数据值"
            prop="mathParameter"
            width="120">
        </el-table-column>
        <el-table-column align="center"
            label="备注"
            prop="remark"
            width="180">
        </el-table-column>
        <el-table-column align="center"
            label="创建时间"
            prop="createTime"
            width="160">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="primary"
                @click="handleTest(scope.$index, scope.row)">测试</el-button>
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="margin-top: 20px;"
          background
          layout="sizes, prev, pager, next, total"
          :current-page="tablePage"
          @size-change="sizeChangeEvent"
          @current-change="currentChangeEvent"
          :total="tableTotal">
      </el-pagination>
    </div>

    <!-- 新增数据模型 -->
    <el-dialog
        :title="dialogDataModelTitle"
        width="80%"
        top="10vh"
        center
        :before-close="dialogClose"
        :visible.sync="dialogDataModelVisible"
        :close-on-click-modal="false"
        :append-to-body="true">
      <el-form ref="dataModelForm" :model="dataModelForm" :rules="dataModelRules" label-width="110px" label-position="top">
        <el-form-item label="四则运算表达式" prop="operationRule">
          <el-input v-model="dataModelForm.operationRule" placeholder="请输入四则运算表达式"></el-input>
          <span style="font-size: 12px;">
            提示：四则运算支持的英文符号&nbsp;【<b>+</b>】、【<b>-</b>】、【<b>*</b>】、【<b>/</b>】、【<b>()</b>】，真实数据值使用固定字符串&nbsp;【<b>calcVal</b>】
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="dataModelForm.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="saveDataModelEvent">确定</el-button>
          <el-button @click="dialogClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import BreadcrumbView from '@/components/BreadcrumbView'
import { showLoading } from '@/utils/cqcy'
import {
  addDataModel,
  delDataModelById,
  getAllDataModel,
  testDataModelById,
  updateDataModel,
  updateItemDescribe
} from "@/api/datasource";

export default {
  name: "index",
  components: {
    BreadcrumbView
  },
  data() {
    /** 四则运算表达式验证 */
    let validateCalc = (rule, value, callback) => {
      try {
        value = value.replace(/ /g, '')
        value = value.replace(/calcVal/g, '99999')
        if (/^[\d|\-|\+|\*|\/|\.|\(|\)]+$/.test(value)) {
          // 排除连续的运算符
          if (/[\-|\+|\*|\/]{2,}/.test(value)) {
            callback(new Error('表达式验证失败，请修改后再试'))
            return
          }
          // 解决 0.5 简写成 .5
          if (/\D\./.test(value)) {
            callback(new Error('表达式验证失败，请修改后再试'))
            return
          }
          let val = eval(value)
          if (typeof val == 'number' && val != Infinity) {
            callback()
            return
          }
        }
        callback(new Error('表达式验证失败，请修改后再试'))
      } catch (e) {
        callback(new Error('表达式验证失败，请修改后再试'))
      }
    }
    return {
      breadcrumbList: ['数据模型'],
      dialogDataModelVisible: false,
      dialogDataModelTitle: '新增数据模型',
      tablePage: 1,
      tableLimit: 10,
      tableTotal: 0,
      tableData: [],
      dataModelForm: {
        id: '',
        mathParameter: 'calcVal',
        operationRule: '',
        remark: ''
      },
      dataModelRules: {
        operationRule: [
          { validator: validateCalc, trigger: 'blur' }
        ],
      }
    }
  },
  watch: {
  },
  beforeDestroy() {
  },
  created() {
    this.getAllDataModel()
  },
  methods: {
    /** 新增数据模型 */
    handleAdd() {
      this.dialogDataModelTitle = '新增数据模型'
      this.dialogDataModelVisible = true
    },
    /** 编辑数据模型 */
    handleEdit(index, row) {
      this.dialogDataModelTitle = '编辑数据模型'
      this.dataModelForm = row
      this.dialogDataModelVisible = true
    },
    /** 测试数据模型值 */
    handleTest(index, row) {
      this.$prompt('请输入数值', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'close_confirm',
        closeOnClickModal: false,
        inputValidator: (val) => {
          if (!/^[0-9]+(.[0-9]{1,2})?$/.test(val)) {
            return '请输入正确的数字'
          }
          if (val.length > 6) {
            return '请输入小于6位的数字'
          }
        }
      }).then(({ value }) => {
        const loading = showLoading(this, '计算中，请稍候···')
        let params = {
          'id': row.id,
          'dataValue': value
        }
        testDataModelById(params).then(res => {
          loading.close()
          let bds = row.operationRule
          bds = bds.replaceAll(/calcVal/g, value)
          bds += '='
          bds += res.data
          this.$alert(bds, '计算结果', {
            confirmButtonText: '确定',
            callback: action => {
            }
          })
        }).catch((e) => {
          loading.close()
          this.$message({
            message: '计算失败！',
            type: 'warning'
          })
        })
      }).catch(() => {
      })
    },
    /** 删除数据模型 */
    handleDelete(index, row) {
      this.$confirm('您确定要删除该表达式吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'close_confirm',
        closeOnClickModal: false
      }).then(() => {
        const loading = showLoading(this, '删除中，请稍候···')
        delDataModelById(row.id).then(res => {
          loading.close()
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
          this.getAllDataModel()
        }).catch((e) => {
          loading.close()
          this.$message({
            message: '删除失败！',
            type: 'warning'
          })
        })
      }).catch(() => {
      })
    },
    /** 保存数据模型 */
    saveDataModelEvent() {
      this.$refs['dataModelForm'].validate((valid) => {
        if (valid) {
          const loading = showLoading(this, '保存中，请稍候···')
          if (this.dataModelForm.id) {
            updateDataModel(this.dataModelForm).then(res => {
              loading.close()
              this.$message({
                message: '修改成功！',
                type: 'success'
              })
              this.dialogDataModelVisible = false
              this.dataModelForm.id = ''
              this.$refs['dataModelForm'].resetFields()
              this.getAllDataModel()
            }).catch((e) => {
              loading.close()
              this.$message({
                message: '修改失败！',
                type: 'warning'
              })
            })
           return
          }
          addDataModel(this.dataModelForm).then(res => {
            loading.close()
            this.$message({
              message: '保存成功！',
              type: 'success'
            })
            this.dialogDataModelVisible = false
            this.$refs['dataModelForm'].resetFields()
            this.getAllDataModel()
          }).catch((e) => {
            loading.close()
            this.$message({
              message: '保存失败！',
              type: 'warning'
            })
          })
        }
      })
    },
    /** 数据条数改变 */
    sizeChangeEvent(val) {
      this.tablePage = 1
      this.tableLimit = val
      this.getAllDataModel()
    },
    /** 页码改变 */
    currentChangeEvent(val) {
      this.tablePage = val
      this.getAllDataModel()
    },
    /** 查询所有模型数据 */
    getAllDataModel() {
      const loading = showLoading(this, '请稍候···')
      let params = {
        'page': this.tablePage,
        'limit': this.tableLimit
      }
      getAllDataModel(params).then(res => {
        loading.close()
        if (!res.data) {
          this.$message({
            message: '数据查询失败！',
            type: 'warning'
          })
          return
        }
        this.tableTotal = res.data.count
        this.tableData = res.data.dataModelList
      }).catch((e) => {
        loading.close()
        this.$message({
          message: '数据查询失败！',
          type: 'warning'
        })
      })
    },
    /** 弹出层关闭事件 */
    dialogClose(done) {
      if (typeof(done) === 'function') {
        done()
      } else {
        this.dialogDataModelVisible = false
        this.$refs['dataModelForm'].resetFields()
        this.getAllDataModel()
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.breadcrumb-content {
  padding-bottom: 0;
}

.cy-main {
  margin: 10px 20px;
  width: calc(100% - 40px);
  height: calc(100% - 100px);
}

.cy-nav-btn {
  float: right!important;
  margin-right: 20px!important;
  margin-top: -20px!important;
}
</style>