<template>
  <el-card shadow="hover" v-if="coreCardPageVisible">

    <div class="launch-table-search">
      <el-row>
        <el-button @click="addModuleConfig">新增核心</el-button>
        <el-input
            style="width: 200px;margin-left: 10px"
            :suffix-icon="Search"
            v-model="search.inputSearch"
            placeholder="请输入配置类型"
            @change="searchQuery">
        </el-input>
        <el-button style="margin-left: 10px" @click="clearSerach">清空查询</el-button>
      </el-row>
    </div>

    <div>
      <vxe-table
          round
          border="inner"
          size="mini"
          :row-config="{isHover: true}"
          :column-config="{resizable: true}"
          :data="tableData">
        <vxe-column type="seq" width="60"></vxe-column>
        <vxe-column field="type" title="配置类型"></vxe-column>
        <vxe-column field="description" title="描述"></vxe-column>
        <vxe-column field="updateTime" title="更新时间"></vxe-column>
        <vxe-column title="操作" width="120">
          <template #default="{ row }">
            <el-button link type="primary" @click="showConfigInfo(row)">详情</el-button>
            <el-popconfirm title="确定要删除吗?" @confirm="delConfigInfo(row)">
              <template #reference>
                <el-button link type="primary">删除</el-button>
              </template>
            </el-popconfirm>

          </template>
        </vxe-column>
      </vxe-table>
    </div>

    <div class="launch-table-page">
      <el-pagination
          small
          :currentPage="page.current"
          :page-size="page.size"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

  </el-card>

  <el-card v-if="coreCardVisible" shadow="hover">
    <el-page-header :icon="ArrowLeft" @back="leftBack">
      <template #content>
        <span > {{ cardTitle }} </span>
      </template>
    </el-page-header>
    <el-form :model="coreConfigFrom" ref="configformRef" :rules="rules" class="launch-form">

      <el-form-item label="配置类型" :label-width="formLabelWidth" prop="type" :style="formInputWidth">
        <el-input v-model="coreConfigFrom.type" placeholder="请输入类型" />
      </el-form-item>

      <el-form-item label="描述" :label-width="formLabelWidth" prop="description" :style="formInputWidth">
        <el-input v-model="coreConfigFrom.description"/>
      </el-form-item>

      <el-form-item label="配置数据" :label-width="formLabelWidth" prop="configData" style="width: 70vw">
        <code-edit
            v-model="coreConfigFrom.configData"
            codeType="json"
            height="300px"
            @codeError="getCodeError"
        />
      </el-form-item>

      <el-form-item :label-width="formLabelWidth">
        <el-button type="primary" @click="onSubmit">
          保存
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>


</template>

<script setup>
import { reactive, ref, getCurrentInstance, onMounted } from 'vue'
import { Plus, ArrowLeft, Search } from '@element-plus/icons-vue'

const {proxy} = getCurrentInstance()
const coreConfigApi = proxy.$launchApi.coreConfigApi
const dictApi = proxy.$launchApi.dictApi
const dictFormat = proxy.$launchUtil.dictFormat
const ConditionEnum = proxy.$launchUtil.ConditionEnum
const {Page, Query, createSelectPage} = proxy.$launchUtil.selectPage


const configformRef = ref(null)
let cardTitle = ref("")

let coreCardVisible = ref(false)
let coreCardPageVisible = ref(true)

let codeError = ref(true)

let formLabelWidth = ref('20vw')
let formInputWidth = ref('width: 50vw')

//搜索
let search = ref({})

function searchQuery() {
  let queryArray = new Array()
  if(search.value.inputSearch && search.value.inputSearch.trim() !== ""){
    let query = new Query()
    query.setCondition(ConditionEnum.eq())
    query.setVal(search.value.inputSearch)
    query.setColumn("type")
    queryArray.push(query)
  }
  querys.value = queryArray
  selectPage()
}

function clearSerach() {
  search.value = {}
  querys.value = []
  selectPage()
}

// 查询表格数据
let newPage = new Page(10,1)
newPage.setOrders([
  {column:"update_time",asc:false}
])
let page = reactive(newPage)
let querys = ref([])
let tableData = ref([])

function selectPage(){
  coreConfigApi.selectPage(createSelectPage(page,querys.value)).then(data => {
    if(data != null){
      tableData.value = data.records
      page.total = data.total
      page.current = data.current
    }
  })
}

function handleSizeChange(val) {
  page.size = val
  selectPage()
}

function handleCurrentChange(val) {
  page.current = val
  selectPage()
}

// 详情
function showConfigInfo(val) {
  cardTitle.value = "配置详情"
  coreConfigFrom.value = val
  showCardVisible()
}

// 删除
function delConfigInfo(row){
  coreConfigApi.deleteById(row.id).then(result => {
    if(result === 1){
      proxy.$message.success("删除成功")
      selectPage()
    }
  })
}


// 表单校验规则
const rules = reactive({
  type:[
    { required: true, message: '该值不能为空',trigger: 'change'}
  ],
  description:[
    { required: true, message: '该值不能为空',trigger: 'change'}
  ],
  configData:[
    { required: true, message: '该值不能为空',trigger: 'change'}
  ]
})

// 表单对象
let coreConfigFrom = ref({})

function defModuleConfig() {
  return {
    type:'',
    description:'',
    configData:''
  }
}

function showCardVisible(){
  coreCardPageVisible.value = false
  coreCardVisible.value = true
}

function hideCardVisible(){
  coreCardPageVisible.value = true
  coreCardVisible.value = false
}

// 返回
function leftBack() {
  hideCardVisible()
  selectPage()
}

// 新建配置
function addModuleConfig() {
  cardTitle.value = "新建配置"
  coreConfigFrom.value = defModuleConfig()
  showCardVisible()
}

function getCodeError(value) {
  codeError.value = value === 0
}


function onSubmit(){

  let valid = configformRef.value.validate((valid, fields) => {
    // TODO 校验失败提示需要优化
    return valid
  })

  valid.then(val => {
    if(!val){
      proxy.$message.error("请输入所有必填项")
    }else if(!codeError.value){
      proxy.$message.error("代码语法错误")
    }

    if(val && codeError.value){
      coreConfigApi.insert(coreConfigFrom.value).then(result => {
        if(result === 1){
          proxy.$message.success("保存成功")
          coreConfigFrom.value = defModuleConfig()

          leftBack()
        }
      })
    }

  })


}

onMounted(() => {

  selectPage()
})


</script>

<style scoped>
.launch-table-search{
  min-height: 45px;
}
.launch-table-page{
  margin-top: 20px;
}
.launch-form{
  margin-top: 30px;
}
</style>