<template>
  <div>
    <Title>
      <template v-slot:titleName>业务参数列表</template>
      <template v-slot:titleContent></template>
      <template v-slot:titleOperate>
      </template>
    </Title>

    <!--搜索条件-->
    <div class="form-container ab-p-l-20" >
        <el-radio-group style="padding-bottom: 25px;" v-model="radioModel" v-for="subsystem in subsystems" :key="subsystem">
            <el-radio-button :label="subsystem" @change="useTableQueryReload(tableRef)" />
        </el-radio-group>
    </div>
    <!--表列表-->
    <div class="table-container">
      <vxe-grid ref="tableRef" v-bind="tableOptions">
        <template #buttons_toolbar>
          <el-space wrap>
          </el-space>
        </template>
        <template #tools_toolbar>
          <el-input style="margin-right: 15px; " v-model="filterName" type="search" placeholder="表内搜索" @keyup="useInVxeGridSearch(tableRef)"></el-input>
        </template>
        <template #valueType="{row}">
            <el-text>
              <template v-if="'set'===row.valueType">多值</template>
              <template v-else>值</template>
            </el-text>
        </template>
        <template #valuees="{ row }" style="cursor: pointer">
          <el-text type="primary" @click="dialogFormShow(row)" style="cursor: pointer">
            <template v-if="'set'===row.valueType"><el-icon size="20"><Document /></el-icon></template>
            <template v-else-if="null===row.valuees||''==row.valuees.trim()"><el-icon size="20"><Edit /></el-icon></template>
            <template v-else>{{row.valuees}}</template>
          </el-text>
        </template>
      </vxe-grid>
    </div>
  </div>
  
  <!--表详情-->
  <el-dialog v-model="dialogFormVisible" :width="dialogFormWidth"  >
    <template #header>
      <div class="my-header">
        <el-row>
          <el-col :span="24">参数：{{ currentTableRow.key}}</el-col>
          <el-col :span="24">说明：{{ currentTableRow.describe}}</el-col>
          <el-col :span="24">备注：{{ currentTableRow.procedures}}</el-col>
        </el-row>
      </div>
    </template>
    
    <template v-if="'set'===currentTableRow.valueType">
      <vxe-grid vxe-grid ref="detailtableRef" v-bind="detailTableOptions" @edit-closed="execSaveAbacusConfigItem" >
        <template #buttons_toolbar>
          <el-space wrap>
            <el-button @click="detailTableDataAddEvent" ><el-icon size="18"><Plus /></el-icon>新增参数</el-button>
          </el-space>
        </template>
        <template #tools_toolbar>
        </template>
        <template #operate="{ row }">
          <el-link v-show="row.id.length>0" type="primary"  :underline="false" title="删除" @click="execDeleteAbacusConfigItem(row)"><el-icon size="20"><Delete /></el-icon></el-link>
        </template>
      </vxe-grid>
    </template>
    <template v-else-if="'boolean'===currentTableRow.valueType">
      <el-row :gutter="20" v-loading="dialogFormLoading">
        <el-col :span="20">
          <el-select v-model="currentTableRow.valuees" placeholder="请选择值" >
            <el-option label="true" value="true" />
            <el-option label="false" value="false" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="execSaveAbacusConfig">保存</el-button>
        </el-col>
      </el-row>
    </template>
    <template v-else>
      <el-row :gutter="20" v-loading="dialogFormLoading">
        <el-col :span="20">
          <el-input v-model="currentTableRow.valuees" placeholder="请输入值" />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="execSaveAbacusConfig">保存</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog> 

</template>
  

<script lang="ts">
export default { name: "documentDataDictionary" }
</script>
<script setup lang="ts">
import Title from "@/framework/components/Title/index.vue";
import { keygroupList,abacusConfigList,saveAbacusConfig,abacusConfigItemList,deleteAbacusConfigItem,saveAbacusConfigItem } from '@/subsystem/api/sms/config'
import { useQueryParamsHandle,useInVxeGridSearch,useQueryAndClientPaging,useTableQueryReload } from '@/framework/hooks/useVxeTableHandle'
import { gridDefaultProps } from '@/framework/utils/standard/vxe.ts'
import { Base64 } from 'js-base64';

const subsystems = ref([])
const radioModel=ref('');


/**表格初始化 */
const filterName = ref('')
const tableData = ref([])
const tableRef = ref<VxeGridInstance>()//表格对象
const tableOptions = reactive<VxeGridProps>(gridDefaultProps({
  params: reactive<VxeTableParam>({
    clientPage: true, //是否客户端分页
    tableDataCache: tableData, //表格数据缓存
    filterNameRef: filterName, //表内搜索引用
    // searchProps: [],//需要检索列的key
    children: false,//树形表格场景，表内搜索筛选后的数据，是否作为子节点展示，默认否
    allTreeExpand:false,//树形表格场景，表内搜索筛选后的数据，是否自动展开子节点，默认否
  }),
  rowConfig: {keyField: 'id'},//自定义行数据唯一主键的字段名
  sortConfig: { trigger: 'cell', remote: true, }, //排序配置
  pagerConfig: { enabled: true, pageSize: 100, pageSizes: [100] },//分页配置
  toolbarConfig: { custom: true, export:false,slots: { buttons: 'buttons_toolbar', tools: 'tools_toolbar' }, },//工具栏配置
  columns: [
    { type: 'seq', title: '序号', width:'50px' },
    { field: 'valueType', title: '类型', width:'100px', slots: {default: 'valueType'} },
    { field: 'key', title: '参数'},
    { field: 'valuees', title: '值' , slots: {default: 'valuees'} },
    { field: 'describe', title: '说明'},
    { field: 'procedures', title: '备注'},
  ]
}))

/**值相关 */
const dialogFormVisible=ref(false)
const dialogFormWidth=ref(800)
const currentTableRow=ref({})

/**值表格相关 */
const detailtableRef = ref<VxeGridInstance>()//表详情表格对象
const detailTableOptions = reactive<VxeGridProps<RowVO> & { data: RowVO[] }>(gridDefaultProps({
  params: reactive<VxeTableParam>({
    clientPage: true, //是否客户端分页
  }),
  editConfig: {
    trigger: 'dblclick',
    mode: 'row'
  },
  data:[],
  toolbarConfig: { custom: true, slots: { buttons: 'buttons_toolbar', tools: 'tools_toolbar' }, },//工具栏配置
  columns: [
    { type: 'seq', title: '序号', width:'50px', },
    { field: 'code', title: '参数', editRender: { name: 'input' },   },
    { field: 'name', title: '值', editRender: { name: 'input'}, },
    { field: 'describe', title: '说明', editRender: { name: 'input' }, },
    { field: '', title: '操作',slots: {default: 'operate'},align:'center',minWidth:'5%'},//操作类居中显示 
  ]
}))

const execDeleteAbacusConfigItem = async(row) => {
  await ElMessageBox.confirm('确认该参数？','警告',{confirmButtonText: '确认',cancelButtonText: '取消',type: 'warning',}
    ).then(() => {
      console.log(row.id!=="");
      if(row.id!==""){
         deleteAbacusConfigItem({id:row.id}).then((data: any) => {
          ElMessage({message: '操作成功',type: 'success',})
            queryAbacusConfigItemList(row.keyGroup,row.key)
         })
      }
      // detailTableOptions.data=detailTableOptions.data.filter(o => o._X_ROW_KEY !== o._X_ROW_KEY);
  }).catch(() => {
  })
}

//可选参数：row, rowIndex, $rowIndex, column, columnIndex, $columnIndex
const execSaveAbacusConfigItem = (row) => {
  let param=JSON.parse(JSON.stringify(row.row));
  if(!param.code&&!param.name&&!param.describe){
    detailtableRef.value.setEditRow(row.row)
    return false;
  }
  param.name=Base64.encode(param.name)
  param.keyGroup=currentTableRow.value.keyGroup
  param.key=currentTableRow.value.key
  param.insulate=currentTableRow.value.insulate
  saveAbacusConfigItem(param).then((data: any) => {
    ElMessage({message: '操作成功',type: 'success',})
    queryAbacusConfigItemList(data.keyGroup,data.key)
  }).catch((e)=>{
    detailtableRef.value.setEditRow(row.row)
  })
}

const detailTableDataAddEvent = () => {
  let addRow=detailTableOptions.data.find((o: any) => o.id === "")
  if(addRow){
    detailtableRef.value.setEditRow(addRow)
  }else{
    const newRow: RowVO = {
      id: "",
      keyGroup: currentTableRow.value.keyGroup,
      key: currentTableRow.value.key,
      code: "",
      name: "",
      insulate: null,
      describe: ""
    }
    detailTableOptions.data.push(newRow)
    detailtableRef.value.setEditRow(newRow)
  }
}


const queryAbacusConfigItemList = async(keyGroup,key) => {
  await abacusConfigItemList({keyGroup:keyGroup,key:key}).then((data: any) => {
    detailTableOptions.data=data
  })
}

const dialogFormShow = (row) => {
  currentTableRow.value=JSON.parse(JSON.stringify(row))//对象复制，防止列表数据跟随修改文本框调整
  if('set'===row.valueType){
    dialogFormWidth.value=800
    queryAbacusConfigItemList(currentTableRow.value.keyGroup,currentTableRow.value.key)
  }else{
    dialogFormWidth.value=500
  }
  dialogFormVisible.value=true
}

const dialogFormLoading=ref(false)
const execSaveAbacusConfig = () => {
  dialogFormLoading.value=true
  saveAbacusConfig({id:currentTableRow.value.id,value:Base64.encode(currentTableRow.value.valuees)}).then((data: any) => {
    ElMessage({message: '操作成功',type: 'success',})
    useTableQueryReload(tableRef.value)
  }).finally(() => {
    dialogFormVisible.value=false
    dialogFormLoading.value=false
  })
}



onMounted(() => {
  keygroupList().then((data: any) => {
        subsystems.value=data
        radioModel.value=data[0]
        tableOptions.proxyConfig= {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          props: { result: 'data', total: 'total' },// 对应响应结果，按照后台服务PageResult对象配置
          ajax: {
            // 接收 Promise 对象
            query: ({ page, sorts, filters }) => {
              const queryParams = useQueryParamsHandle({'keyGroup':radioModel.value}, page, sorts, filters)//请求参数处理
              return useQueryAndClientPaging(tableRef,page, sorts,function(){ return abacusConfigList(queryParams)  }) //客户端分页
            },
          }
        }
    }).finally(() => {
    })
});

</script>

<style lang="scss" scoped>
</style>
