<script lang="ts">
export default {
  name: "criticalData",
};
</script>

<script setup lang="ts">
import { onMounted, ref, nextTick } from "vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import { searchCriticalDataPage,addCriticalData,updateCriticalData,deleteCriticalData,deleteBatchCriticalData} from "@/api/business/database/criticalData";
import { getDictItemById } from '@/api/dict';
import Page from '@/components/Pagination/page.vue'
import { getToken } from '@/utils/auth'
const url = import.meta.env.VITE_APP_BASE_API;
// 搜索框
const queryParams:any = ref({
  current: 1,
  size: 10,
  deviceType: ''
});
//分页 总条数
const total = ref()
//定义表格数据

const customAttrsData:any = ref([])

const tableData: any = ref([]);
const multipleSelection = ref([]);
// 表格加载
const loading = ref(false)
function gettableData() {
  let params = {
    name: input.value,
    deviceType: queryParams.value.type,
    pageNum: queryParams.value.current,
    pageSize: queryParams.value.size,
  };
  loading.value = true;
  searchCriticalDataPage(params).then((result:any) => {
    tableData.value = result.records;
    total.value = result.total;
    loading.value = false;
  }).catch((err) => {
    loading.value = false;
  });
}
//表格多选事件
function handleSelectionChange(val: any) {
  multipleSelection.value = val;
}





const menuData:any = ref([])

// 查询字典项
function menuInit() {
  let params = {
    dictId: 'fe2c3418b8998f4e64d56ab46bfe0fed',
    size:99,
    current:1
  }
  getDictItemById(params).then((result: any) => {
    menuData.value = result.data.records;
    queryParams.value.type = menuData.value[0].itemCode
    gettableData();
  }).catch((err: any) => {
  });
}

function handleMenu(row:any) {
   queryParams.value.type = row.itemCode
   gettableData()
}

const infoForm = ref();
//搜索内容及点击搜索按钮
const input = ref("");
//新建设备
const title = ref("");
const info: any = ref({

  deviceType: null,
  diameter: null,
  height: null,
  fissileConcentration: null,
  isotopicAbundance: null,
  extraFeatures: null,
  keffValue: null,
});

const dialogVisible = ref(false);
function addClick() {
  title.value = "新增设备";
  info.value = {
    deviceType: queryParams.value.type,
    diameter: null,
    height: null,
    fissileConcentration: null,
    isotopicAbundance: null,
    extraFeatures: null,
    keffValue: null,

  };
  customAttrsData.value = []
  dialogVisible.value = true;
}
//新建设备-确认按钮/修改按钮
function confirmClick(formEl: any) {
  formEl.validate((valid: any) => {
    if (valid) {

      if (!info.value.projectId) {

        const params = {
          projectId: -1,
          ...info.value,
          customAttrs: JSON.stringify( customAttrsData.value)
        }
        addCriticalData(params).then((res) => {
          gettableData();
          dialogVisible.value = false;
        });
      } else if (info.value.projectId) {
        const params = {
            projectId: -1,
            ...info.value,
            customAttrs: JSON.stringify( customAttrsData.value)
          }
        updateCriticalData(params).then((res) => {
          gettableData();
          dialogVisible.value = false;
        });
      } else {
        return false;
      }
    }
  });
}

//新建角色-取消按钮
function handleClose() {
  dialogVisible.value = false;
  if (infoForm.value != null) infoForm.value.resetFields();
}
//新建设备
const rules = ref({
  name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入设备编码", trigger: "blur" }],
});
//修改设备
function editClick(row: any) {
  title.value = "修改设备";
  info.value = JSON.parse(JSON.stringify(row));

  if(row.customAttrs != null){
    customAttrsData.value = JSON.parse(row.customAttrs);
  }
  dialogVisible.value = true;
}

//删除设备
function delAloneClick(row: any) {
  ElMessageBox.confirm("确定删除此设备吗？", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let params = {
        id: row.deviceId,
      };
      deleteCriticalData(params).then(() => {
        gettableData();
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      });
    })
}


// 多选删除？
function delClick() {
  ElMessageBox.confirm("确定删除已选择角色吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let id = [] as any[];
    multipleSelection.value.forEach((item: any) => {
      id.push(item.deviceId)
    })
    let params = {
      ids: id,
    };
    deleteBatchCriticalData(params.ids).then(() => {
      gettableData();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    });
  });
}
function dateFormat(row: any) {
  const daterc = row;
  if (daterc != null) {
    var date = new Date(daterc);
    var year = date.getFullYear();
    var month =
      date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    // 拼接
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  }
}


function handlePreview(){
  // loadingtext.value = "正在导入数据，请耐心等待！"
  loading.value = true
}
const upload:any = ref(null)
function handlesSuccess(file: any) {
   if(file !== false){
    ElMessage({
      message: "导入成功！",
      type: "success",
    });
   }else{
    ElMessage({
    message: "导入失败！",
    type: "error",
  });
   }
    
    gettableData()
  upload.value.clearFiles()
}
function handleError(file: any){
  loading.value = false
  ElMessage({
    message: "导入失败！",
    type: "error",
  });
  upload.value.clearFiles()
}

// 处理数字输入的过滤
function handleNumberInput(field: string) {
  // 过滤输入，只允许数字和小数点
  info.value[field] = info.value[field].replace(/[^\d.]/g, '');
  // 确保只有一个小数点
  const parts = info.value[field].split('.');
  if (parts.length > 2) {
    info.value[field] = parts[0] + '.' + parts.slice(1).join('');
  }
}


onMounted(() => {
  menuInit()
});
</script>

<template>
  <div class="criticalData-box">
    <div class="conductproject-bg-leftBox">
        <div v-for="(item,index) in menuData" 
          :key="index" :class="{'menu-list-active': item.itemCode == queryParams.type }" class="menu-list" 
        @click="handleMenu(item)">
            {{ item.dictName }}
        </div>
    </div>
    <div class="conductproject-bg-box">
      <div
        style="display: flex;display: -webkit-flex; justify-content: space-between; -webkit-justify-content: space-between;margin-bottom: 10px">
        <div style="display: flex;display: -webkit-flex;">
          <el-input v-model="input" placeholder="请输入设备名称" @keyup.enter="gettableData" style="width: 200px" clearable />
          <el-button type="primary" style="margin-left: 10px" @click="gettableData">搜索</el-button>
        </div>
        <div style="display: flex;display: -webkit-flex;">
          <el-button  type="primary" @click="addClick">
            新增</el-button>
              <el-upload
              ref="upload"
              accept=".xlsx,.xls"
              class="upload-demo"
              :action=" url + '/critical-data/import' "
              :headers="{ token: getToken() }" 
              :show-file-list="false"
              :before-upload="handlePreview"
              :on-success="handlesSuccess"
              :on-error="handleError">
              <el-button type="primary" style="margin: 0 10px;">导入</el-button>
            </el-upload>
          <el-button  :type="multipleSelection.length > 0 ? 'primary' : ''"
            :disabled="multipleSelection.length <= 0" @click="delClick">删除</el-button>
        </div>
      </div>
      <el-table v-loading="loading" :data="tableData" style="width: 100%; height: calc(100vh - 260px);margin-bottom: 10px;" border
        @selection-change="handleSelectionChange"
        :header-cell-style="{ background: 'rgb(250 250 250)', color: '#383838', height: '50px' }">
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
        <el-table-column prop="diameter" label="等效直径" min-width="100"></el-table-column>
        <el-table-column prop="height" label="等效高度" min-width="100"></el-table-column>
        <el-table-column prop="fissileConcentration" label="核材料浓度" min-width="100"></el-table-column>
        <el-table-column prop="isotopicAbundance" label="同位素丰度" min-width="100"></el-table-column>
        <el-table-column prop="keffValue" label="对应 k_eff 值" min-width="100"></el-table-column>
        <el-table-column prop="modifier" label="创建人" width="120"></el-table-column>
        <el-table-column prop="updatedAt" label="创建时间" width="200">
          <template #default="scope">
            {{ dateFormat(scope.row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <span
              style="display: flex;display: -webkit-flex; justify-content: space-around;-webkit-justify-content: space-around; ">
              <img  src="@/assets/MenuIcon/lbcz_xg.png" alt="" title="修改"
                @click="editClick(scope.row)" style="cursor: pointer; ">
                 <img  src="@/assets/MenuIcon/lbcz_sc.png" alt="" title="删除"
                @click="delAloneClick(scope.row)" style="cursor: pointer; "> 
            </span>
          </template>
        </el-table-column>
      </el-table>
      <Page :total="total" v-model:size="queryParams.size" v-model:current="queryParams.current" @pagination="gettableData()" ></Page>

    </div>

    <el-dialog v-model="dialogVisible" :close-on-click-modal="false"
    :modal="false" draggable :before-close="handleClose" :title="title"
      append-to-body width="677px" height="530px">
      
      <el-form ref="infoForm" :model="info" :rules="rules" label-width="100px" >
        <el-form-item label="等效直径" style="width: 100%;">
          <el-input v-model="info.diameter" style="width: 100%" placeholder="请输入等效直径" 
          @input="handleNumberInput('diameter')"></el-input>
        </el-form-item>
        <el-form-item label="等效高度"  style="width: 100%;">
          <el-input v-model="info.height" style="width: 100%" placeholder="请输入等效高度"
          @input="handleNumberInput('height')"></el-input>
        </el-form-item>
        <el-form-item label="核材料浓度" style="width: 100%;">
          <el-input v-model="info.fissileConcentration" style="width: 100%" placeholder="请输入核材料浓度"
          @input="handleNumberInput('fissileConcentration')">
             <!-- <template #append>m</template> -->
          </el-input>
        </el-form-item>
        <el-form-item label="同位素丰度" style="width: 100%;">
          <el-input v-model="info.isotopicAbundance" style="width: 100%" placeholder="请输入同位素丰度"
          @input="handleNumberInput('isotopicAbundance')">
             <!-- <template #append>m</template> -->
          </el-input>
        </el-form-item>
        <el-form-item label="对应k_eff值"  style="width: 100%;">
          <el-input v-model="info.keffValue" style="width: 100%" placeholder="请输入对应k_eff值"
          @input="handleNumberInput('keffValue')">
             <!-- <template #append>m³/s</template> -->
          </el-input>
        </el-form-item>
        <span class="dialog-footer"
          style="display: flex;display: -webkit-flex; justify-content: flex-end;-webkit-justify-content: flex-end;">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="confirmClick(infoForm)">确 定</el-button>
        </span>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped>
.criticalData-box {
  padding-right: 10px;
  display: flex;
  justify-content: space-between;
}


.dialog-footer {
  display: block;
  margin-top: 20px;
}
.conductproject-bg-leftBox{
  width: 240px;
  height: calc(100vh - 130px);
  overflow: auto;
  padding: 20px 0px;
  background-color: rgba(255, 255, 255, 1);
  border: none;
  border-radius: 3px;
  box-sizing: border-box;
}
.menu-list{
  width: 220px;
  height: 40px;
  line-height: 40px;
  box-sizing: border-box;
  padding-left: 30px;
  font-family: 'Arial Normal', 'Arial', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 14px;
  letter-spacing: normal;
  color: #333333;
  margin-left: 10px;
  cursor: pointer;
}
.menu-list:hover{
  background-color: #f9f9f9;
}
.menu-list-active{
  background-color: #eaf1ff !important;
  color: rgb(38, 111, 255) ;
}
.conductproject-bg-box {
  padding: 20px;
  width:  calc(100% - 255px);
  height: calc(100vh - 130px);
  overflow: auto;
  background-color: rgba(255, 255, 255, 1);
  border: none;
  border-radius: 3px;
  box-sizing: border-box;
}

.menu-title{
  width: 100%;
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid rgba(242, 242, 242, 1);
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial', sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 15px;
  color: #363636;
  padding-left: 20px;
}

</style>
<style>
.el-dialog {
  padding: 0 !important;
  border-radius: 10px !important;
  border: 1px solid #363636 !important;
}
.el-dialog  .el-dialog__header{
  display: flex;
  display: -webkit-flex;
  justify-content: flex-start;-webkit-justify-content: flex-start;
  align-items: center;-webkit-align-items: center;
  padding: 10px 20px;
  background-color: #f1f3f8 !important;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial', sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 16px;
  color: #1B1B1B;
  text-align: left;
  border-radius: 10px 10px 0 0;
  height: 50px;
}
.el-dialog .el-dialog__close{
   font-size: 22px;
   color: rgb(80, 80, 80);
}
.el-dialog .el-dialog__headerbtn{
  display: flex;
  align-items: center;
}
.el-dialog .el-dialog__body{
  padding: 20px 40px !important;
}
.el-dialog .el-input{
 --el-input-inner-height: 38px
}
.el-dialog .el-button{
  height: 40px;
}
.el-input-group__append {
  background-color: transparent !important;
  border: none !important;
}
</style>