<template>
  <div class="app-container">
    <el-form inline :model="queryParams">
      <el-form-item label="批量对象表名:">
        <el-input v-model="queryParams.bathObjTabName"></el-input>
      </el-form-item>
      <el-form-item label="批里对象字段名:">
        <el-input v-model="queryParams.bathObjFldName"></el-input>
      </el-form-item>
      <el-form-item label="词性名称:">
        <el-input v-model="queryParams.posName"></el-input>
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="queryParams.status" style="width: 200px" clearable>
          <el-option label="正常" key="tsmcb-query-status-1" value="1"></el-option>
          <el-option label="弃用" key="tsmcb-query-status-1" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Minus"
            @click="multDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出</el-button>
      </el-col>
    </el-row>
    <el-table :data="dataList" @selection-change="handleSelection">
      <el-table-column type="selection" width="50" align="center" />
<!--      <el-table-column label="序号" align="center" prop="onum"></el-table-column>-->
      <el-table-column label="批量对象表名" align="center" prop="bathObjTabName"></el-table-column>
      <el-table-column label="批里对象字段名" align="center" prop="bathObjFldName"></el-table-column>
      <el-table-column label="频次" align="center" prop="freq"></el-table-column>
      <el-table-column label="词性" align="center" prop="pos"></el-table-column>
      <el-table-column label="词性名称" align="center" prop="posName"></el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status"
                     active-value="1"
                     inactive-value="0" @change="changeStatus(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="负责人员" align="center" prop="updateBy"></el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime">
        <template #default="scope">
          <span>{{scope.row.updateTime.replace("T"," ")}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" prop="operation">
        <template #default="scope">
          <el-link type="primary" @click="handleEdit(scope.row)" :underline="false">修改</el-link>
          <el-link type="danger"  style="margin-left: 10px" @click="handleDelete([scope.row.onum])" :underline="false">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <el-dialog
        v-model="showDialog"
        :title="currentForm.operate === 'ADD'?'新增词典配置表':'编辑词典配置表'"
        width="500"
    >
      <el-form v-if="showDialog"
               :model="currentForm"
               ref="formRef"
               :rules="rules"
               label-width="125px">
        <el-form-item label="批量对象表名:" prop="bathObjTabName">
          <el-input
              v-model="currentForm.bathObjTabName" clearable
          />
        </el-form-item>
        <el-form-item label="批量对象字段名:" prop="bathObjFldName">
          <el-input
              v-model="currentForm.bathObjFldName" clearable
          />
        </el-form-item>
        <el-form-item label="频次:" prop="freq">
          <el-input
              v-model="currentForm.freq" clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="词性:" prop="pos">
          <el-input
              v-model="currentForm.pos" clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="词性名称:" prop="posName">
          <el-input
              v-model="currentForm.posName" clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="状态:">
          <el-radio-group v-model="currentForm.status">
            <el-radio value="1" size="large">正常</el-radio>
            <el-radio value="0" size="large">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSave">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?overWrite=' + upload.overWrite"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <!--      <el-form>-->
      <!--        <el-form-item>-->
      <!--          <template #label>-->
      <!--            开启覆盖-->
      <!--            <el-tooltip-->
      <!--                class="box-item"-->
      <!--                effect="dark"-->
      <!--                placement="right"-->
      <!--            >-->
      <!--              <template #content>-->
      <!--                <div>打开“开启覆盖”则原补录信息会被模板中未填信息覆盖为空值。<br>-->
      <!--                  关闭“开启覆盖”则模板中留空数据不会影响原补录信息-->
      <!--                </div>-->
      <!--              </template>-->
      <!--              <el-link :underline="false" type="primary"><i class="ri-question-line"></i></el-link>-->
      <!--            </el-tooltip>-->
      <!--          </template>-->
      <!--          <el-switch v-model="upload.overWrite"></el-switch>-->
      <!--        </el-form-item>-->
      <!--      </el-form>-->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="upload.isUploading" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="导入结果" v-model="upload.showResult" width="1000px" append-to-body>
      <template v-if="upload.showResult">
        <el-tabs type="border-card" v-if=" (upload.resultMsg.table && upload.resultMsg.table.length>0) || (upload.resultMsg.column && upload.resultMsg.column.length>0)">
          <el-tab-pane label="表级问题" v-if="upload.resultMsg.table && upload.resultMsg.table.length>0">
            <el-table :data="upload.resultMsg.table" stripe style="width: 100%">
              <el-table-column prop="row" label="行"  />
              <el-table-column prop="ssysCd" label="系统"  />
              <el-table-column prop="mdlName" label="模式" />
              <el-table-column prop="tabEngName" label="表名称" />
              <el-table-column prop="errorInfo" label="问题" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="字段级问题" v-if="upload.resultMsg.column && upload.resultMsg.column.length>0">
            <el-table :data="upload.resultMsg.column" stripe style="width: 100%">
              <el-table-column prop="row" label="行"  />
              <el-table-column prop="ssysCd" label="系统"  />
              <el-table-column prop="mdlName" label="模式" />
              <el-table-column prop="tabEngName" label="表名称" />
              <el-table-column prop="fldEngName" label="字段名称" />
              <el-table-column prop="errorInfo" label="问题" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <span v-if="  (upload.resultMsg.table && upload.resultMsg.table.length===0) &&  (upload.resultMsg.column && upload.resultMsg.column.length===0) && upload.resultMsg.successCount === 0">
          上传的文档内容为空，请进行有效上传
        </span>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="upload.showResult = false">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, nextTick, computed, watch, reactive, onMounted } from 'vue'
import { getCdplbList, saveCdplb, deleteCdplb } from "@/api/dataint/cdplb"
import {getToken} from "@/utils/auth.js";
import * as XLSX from "xlsx";
const { proxy } = getCurrentInstance();

const queryParams = ref({
  bathObjTabName:'',
  bathObjFldName:'',
  posName:'',
  status:'',
  pageNum:1,
  pageSize:10
})
const showDialog = ref(false)
const rules = ref({
  bathObjTabName: [{required: true, message: '批量对象表名不能为空！', trigger: 'change',},],
  bathObjFldName: [{required: true, message: '批里对象字段名不能为空！！', trigger: 'change',},],
  pos: [{required: true, message: '词性不能为空！', trigger: 'change',},],
  posName: [{required: true, message: '词性名称不能为空！', trigger: 'change',},],
  freq: [{required: true, message: '频次不能为空！', trigger: 'change',},],
})
const currentForm = ref({
  operate: 'ADD',
  bathObjTabName:'',
  bathObjFldName:'',
  pos:'',
  posName:'',
  freq:'',
  status:'1'
})
const multSelection = ref([])
const dataList = ref([])
const total = ref(0)
/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  overWrite: false,
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/dataint/cdplb/upload",
  showResult: false,
  resultMsg: {}
});
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download("/dataint/cdplb/importTemplate", {
  }, `meta_template_${new Date().getTime()}.xlsx`);
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  let resData = response.data
  if (resData.successCount > 0 && resData.rows.length === 0){
    proxy.$modal.msgSuccess("导入成功")
  }else {
    upload.resultMsg = resData
    upload.showResult = true
  }
  getList();
}
function handleQuery(){
  queryParams.value.pageNum = 1;
  getList()
}
function getList(){
  getCdplbList(queryParams.value).then(res=>{
    dataList.value = res.data.rows
    total.value = res.data.total
  })
}
function resetQuery(){
  queryParams.value = {
    pos:'',
    type:'',
    stdRplStr:'',
    status:'',
    pageNum:1,
    pageSize:10
  }
  handleQuery()
}
function handleAdd(){
  showDialog.value = true
  currentForm.value ={
    operate: 'ADD',
    bathObjTabName:'',
    bathObjFldName:'',
    pos:'',
    posName:'',
    freq:'',
    status:'1'
  }
}
function handleSave(){
  proxy.$refs.formRef.validate(valid => {
    if (valid) {
      saveCdplb(currentForm.value).then(res=>{
        proxy.$modal.msgSuccess("操作成功");
        showDialog.value = false
        getList()
      })
    }
  });
}
function handleEdit(row){
  currentForm.value = JSON.parse(JSON.stringify(row))
  currentForm.value.operate = 'UPDATE'
  showDialog.value = true
}
function changeStatus(row){
  let param = {
    onum: row.onum,
    status: row.status
  }
  saveCdplb(param).then(res=>{
    proxy.$modal.msgSuccess("操作成功");
    getList()
  })
}
function multDelete(){
  let array = []
  if (multSelection.value.length>0){
    for (let i = 0; i < multSelection.value.length; i++) {
      array.push(multSelection.value[i].onum)
    }
    handleDelete(array)
  }else{
    proxy.$modal.msgWarning("请至少选择一条数据")
  }

}
function handleDelete(array){
  deleteCdplb(array).then(res=>{
    proxy.$modal.msgSuccess("操作成功");
    getList()
  })
}
function handleImport(){
  upload.title = "数据导入";
  upload.open = true;
}
function handleExport(){
  let data = [];
  if (dataList.value.length > 0){
    for (let i = 0; i < dataList.value.length; i++) {
      data.push({
        "批量对象表名":dataList.value[i].bathObjTabName,
        "批里对象字段名":dataList.value[i].bathObjFldName,
        "频次":dataList.value[i].freq,
        "词性":dataList.value[i].pos,
        "词性名称":dataList.value[i].posName,
        "状态":dataList.value[i].status === '1'?"正常":"停用"
      })
    }
  }
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(data);
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
  XLSX.writeFile(workbook, "数据导出.xlsx");
}
function handleSelection(val){
  multSelection.value= val
}
onMounted(() => {
  handleQuery()
})
</script>
<style scoped lang="scss">

</style>