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

<script setup lang="ts">
import { onMounted, ref, nextTick } from "vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import { searchMaterialsPage,addMaterials,updateMaterials,deleteMaterials,deleteBatchMaterials} from "@/api/business/database/material";
import Page from '@/components/Pagination/page.vue'
import { getToken } from '@/utils/auth'
const url = import.meta.env.VITE_APP_BASE_API;
// 搜索框
const queryParams = ref({
  current: 1,
  size: 10,
  querystr: ''
});
//分页 总条数
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,
    pageNum: queryParams.value.current,
    pageSize: queryParams.value.size,
  };
  loading.value = true;
  searchMaterialsPage(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;
}

// 处理数字输入的过滤
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('');
  }
}


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



const infoForm = ref();
//搜索内容及点击搜索按钮
const input = ref("");
//新建物料数据
const title = ref("");
const info: any = ref({
  name: "",
  description: "",
  uConcentration: "",
  uo2Density: "",
  uEnrichment: "",
  puConcentration: "",
  puo2Density: "",
  puIsotope: "",
  hno3Acidity: "",
  h2c2o4Concentration: "",
  organicRatio: "",
  moistureContent: "",
});

const dialogVisible = ref(false);
function addClick() {
  title.value = "新增物料数据";
  info.value = {
    name: "",
    description: "",
    uConcentration: "",
    uo2Density: "",
    uEnrichment: "",
    puConcentration: "",
    puo2Density: "",
    puIsotope: "",
    hno3Acidity: "",
    h2c2o4Concentration: "",
    organicRatio: "",
    moistureContent: "",
  };
  customAttrsData.value = []
  dialogVisible.value = true;
}
//新建物料数据-确认按钮/修改按钮
function confirmClick(formEl: any) {
  formEl.validate((valid: any) => {
    if (valid) {

      if (!info.value.materialId) {

        const params = {
          projectId: -1,
          ...info.value,
          customAttrs: JSON.stringify( customAttrsData.value)
        }
        addMaterials(params).then((res) => {
          gettableData();
          dialogVisible.value = false;
        });
      } else if (info.value.materialId) {
        const params = {
            projectId: -1,
            ...info.value,
            customAttrs: JSON.stringify( customAttrsData.value)
          }
        updateMaterials(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" }],
  uConcentration: [
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字或小数", trigger: "blur" }
  ],
  uo2Density: [
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字或小数", trigger: "blur" }
  ],
  uEnrichment: [
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字或小数", trigger: "blur" }
  ],
  puConcentration: [
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字或小数", trigger: "blur" }
  ],
  puo2Density: [
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字或小数", trigger: "blur" }
  ],
  puIsotope: [
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字或小数", trigger: "blur" }
  ],
  hno3Acidity: [
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字或小数", trigger: "blur" }
  ],
  h2c2o4Concentration: [
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字或小数", trigger: "blur" }
  ],
  organicRatio: [
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字或小数", trigger: "blur" }
  ],
  moistureContent: [
    { pattern: /^\d+(\.\d+)?$/, message: "请输入有效的数字或小数", trigger: "blur" }
  ],
});
//修改物料数据
function editClick(row: any) {
  title.value = "修改物料数据";
  info.value = JSON.parse(JSON.stringify(row));

  if(row.customAttrs != null && row.customAttrs != ""){
    customAttrsData.value = JSON.parse(row.customAttrs);
  }else{
    customAttrsData.value = []
  }
  dialogVisible.value = true;
}

//删除物料数据
function delAloneClick(row: any) {
  ElMessageBox.confirm("确定删除此物料数据吗？", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let params = {
        id: row.materialId,
      };
      deleteMaterials(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.materialId)
    })
    let params = {
      ids: id,
    };
    deleteBatchMaterials(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 removeAttr(index:any){
  customAttrsData.value.splice(index, 1);
}
function addAttr(){
  customAttrsData.value.push({
    name: null,
    value: null,
    unit: null,
  });
}
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()
}
onMounted(() => {
  gettableData();
});
</script>

<template>
  <div class="Materials-box">
    <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 + '/materials/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="name" label="物料名称" min-width="180"></el-table-column>
        <!-- <el-table-column prop="description" label="物料数据描述" min-width="100"></el-table-column> -->
        <el-table-column prop="modifier" label="创建人" width="120"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="200">
          <template #default="scope">
            {{ dateFormat(scope.row.createdAt) }}
          </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/table/edit.png" alt="" title="修改"
                @click="editClick(scope.row)" style="cursor: pointer; ">
                 <img  src="@/assets/table/del.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="1000px" height="600px">
      
      <el-form ref="infoForm" :model="info" :rules="rules" label-width="220px" 
      style="height: calc(100vh - 200px) ; overflow: auto;">
        <el-form-item label="物料名称" prop="name" style="width: 100%;" label-width="80px">
          <el-input v-model="info.name" style="width: 100%" placeholder="输入物料名称"></el-input>
        </el-form-item>
        <!-- <el-form-item label="物料描述" style="width: 100%;" label-width="80px">
          <el-input type="textarea" v-model="info.description"  :rows="2" style="width: 100%" placeholder="请输入物料描述"></el-input>
        </el-form-item> -->
        <div class="Materials_dialog_display">
          <el-form-item label="铀浓度（g/L）" prop="uConcentration">
            <el-input v-model="info.uConcentration" style="width: 100%" placeholder="" @input="handleNumberInput('uConcentration')"></el-input>
          </el-form-item>
          <el-form-item label="氧化铀密度（g/cm3）" prop="uo2Density">
            <el-input v-model="info.uo2Density" style="width: 100%" placeholder="" @input="handleNumberInput('uo2Density')"></el-input>
          </el-form-item>
        </div>
        <div class="Materials_dialog_display">
          <el-form-item label="铀富集度（%）" prop="uEnrichment">
            <el-input v-model="info.uEnrichment" style="width: 100%" placeholder="" @input="handleNumberInput('uEnrichment')"></el-input>
          </el-form-item>
          <el-form-item label="钚浓度（g/L）" prop="puConcentration">
            <el-input v-model="info.puConcentration" style="width: 100%" placeholder="" @input="handleNumberInput('puConcentration')"></el-input>
          </el-form-item>
        </div>
        <div class="Materials_dialog_display">
          <el-form-item label="氧化钚密度（g/cm3）" prop="puo2Density">
            <el-input v-model="info.puo2Density" style="width: 100%" placeholder="" @input="handleNumberInput('puo2Density')"></el-input>
          </el-form-item>
          <el-form-item label="钚同位素比例（PU-240占比）%" prop="puIsotope">
            <el-input v-model="info.puIsotope" style="width: 100%" placeholder="" @input="handleNumberInput('puIsotope')"></el-input>
          </el-form-item>
        </div>
        <div class="Materials_dialog_display">
          <el-form-item label="硝酸酸度（mol/L）" prop="hno3Acidity">
            <el-input v-model="info.hno3Acidity" style="width: 100%" placeholder="" @input="handleNumberInput('hno3Acidity')"></el-input>
          </el-form-item>
          <el-form-item label="草酸浓度（mol/L）" prop="h2c2o4Concentration">
            <el-input v-model="info.h2c2o4Concentration" style="width: 100%" placeholder="" @input="handleNumberInput('h2c2o4Concentration')"></el-input>
          </el-form-item>
        </div>
        <div class="Materials_dialog_display">
          <el-form-item label="有机相比例%" prop="organicRatio">
            <el-input v-model="info.organicRatio" style="width: 100%" placeholder="" @input="handleNumberInput('organicRatio')"></el-input>
          </el-form-item>
          <el-form-item label="含水率%" prop="moistureContent">
            <el-input v-model="info.moistureContent" style="width: 100%" placeholder="" @input="handleNumberInput('moistureContent')"></el-input>
          </el-form-item>
        </div>
        <div class="Materials_dialog_titledisplay">
          <div class="Materials_dialog_titleline"></div>
          <div>物料成分</div>
        </div>
        <div class="custom_attrs_box">
          <div class="custom_attrs_header">
            <div class="custom_attrs_header1">成分名称</div>
            <div class="custom_attrs_header2">成分参数</div>
            <!-- <div class="custom_attrs_header3">单位</div> -->
            <div class="custom_attrs_header4">操作</div>
          </div>

          <div class="custom_attrs_header" v-for="(item, index) in customAttrsData" :key="index">
            <div class="custom_attrs_content1">
              <el-input v-model="item.key" style="width: 100%" placeholder=""></el-input>
            </div>
           <div class="custom_attrs_content2">
              <el-input v-model="item.value" style="width: 100%" placeholder="" 
                @input="tableNumberInput(index,'value')"></el-input>
            </div>
            <!-- <div class="custom_attrs_content3">
              <el-input v-model="item.unit" style="width: 100%" placeholder=""></el-input>
            </div> -->

            <div class="custom_attrs_content4" @click="removeAttr(index)">
              删除
            </div>
          </div>

        </div>
        <div class="addAttrBox" @click="addAttr">
          <svg t="1766543724217" style="margin-right: 5px;" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6518" width="16" height="16"><path d="M105 480a8 8 0 0 1 8-8h799a8 8 0 0 1 8 8v64a8 8 0 0 1-8 8H113a8 8 0 0 1-8-8v-64z" fill="#266FFF" p-id="6519"></path><path d="M480 920a8 8 0 0 1-8-8V112a8 8 0 0 1 8-8h64a8 8 0 0 1 8 8v800a8 8 0 0 1-8 8h-64z" fill="#266FFF" p-id="6520"></path></svg>
          添加一行
        </div>
        <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>
.Materials-box {
  padding-right: 10px;
}

:deep(.el-tree-node__content) {
  font-size: 15px;
  font-weight: 500;
  width: 100%;
  height: 40px;
}

.dialog-footer {
  display: block;
  margin-top: 20px;
}

.conductproject-bg-box {
  padding: 20px;
  width: 100%;
  height: calc(100vh - 130px);
  overflow: auto;
  background-color: rgba(255, 255, 255, 1);
  border: none;
  border-radius: 3px;
  box-sizing: border-box;
}

.line {
  height: 1px;
  background: rgba(240, 241, 242, 1);
  margin-top: 12px;
}

.menuspan {
  display: inline-block;
  width: 120px;
  font-size: 14px;
  font-family: "微软雅黑";
  font-weight: 400;
  font-style: normal;
  color: #787878;
}
</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
}
.Materials-box .el-button{
  height: 36px;
}
.el-dialog .el-button{
  height: 40px;
}
.Materials_dialog_display{
  display: flex;
  justify-content: space-between;
}
.Materials_dialog_display .el-form-item--default{
  width: 48%;
}
.Materials_dialog_titledisplay{
  display: flex;
  align-items: center;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial', sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 14px;
  color: #282828;
  margin-bottom: 10px;
}
.Materials_dialog_titleline{
  width: 4px;
  height: 12px;
  background: inherit;
  background-color: rgba(38, 111, 255, 1);
  border-radius: 0px;
  filter: drop-shadow(none);
  transition: none;
  color: #266FFF;
  margin-right: 8px;
}

.custom_attrs_box{
  width: 100%;
  border: 1px solid #f0f1f2;
  border-bottom: 0px solid #f0f1f2;
  overflow: auto;
}
.custom_attrs_header{
  display: flex;
}
.custom_attrs_header1{
  width: 45%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial', sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 14px;
  color: #282828;
  background-color: #fafafa;
  border-right: 1px solid #f0f1f2;
  border-bottom: 1px solid #f0f1f2;
}
.custom_attrs_header2{
  width: 45%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial', sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 14px;
  color: #282828;
  background-color: #fafafa;
  border-right: 1px solid #f0f1f2;
  border-bottom: 1px solid #f0f1f2;
}
.custom_attrs_header3{
  width: 20%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial', sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 14px;
  color: #282828;
  background-color: #fafafa;
  border-right: 1px solid #f0f1f2;
  border-bottom: 1px solid #f0f1f2;
}
.custom_attrs_header4{
  width: 10%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial', sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 14px;
  color: #282828;
  background-color: #fafafa;
  border-bottom: 1px solid #f0f1f2;
}

.custom_attrs_content1{
  width: 45%;
  height: 42px;
  line-height: 40px;
  text-align: center;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial', sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 14px;
  color: #282828;
  border-right: 1px solid #f0f1f2;
  border-bottom: 1px solid #f0f1f2;
}
.custom_attrs_content2{
  width: 45%;
  height: 42px;
  line-height: 40px;
  text-align: center;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial', sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 14px;
  color: #282828;
  border-right: 1px solid #f0f1f2;
  border-bottom: 1px solid #f0f1f2;
}
.custom_attrs_content3{
  width: 20%;
  height: 42px;
  line-height: 40px;
  text-align: center;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial', sans-serif;
  font-weight: 700;
  font-style: normal;
  font-size: 14px;
  color: #282828;
  border-right: 1px solid #f0f1f2;
  border-bottom: 1px solid #f0f1f2;
}
.custom_attrs_content4{
  width: 10%;
  height: 42px;
  line-height: 40px;
  text-align: center;
  font-family: '微软雅黑', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 14px;
  color: #266FFF;
  border-bottom: 1px solid #f0f1f2;
}
.custom_attrs_content1 .el-input__wrapper{
  box-shadow: 0 0 0 transparent;
}
.custom_attrs_content1 .el-input__wrapper.is-focus{
  box-shadow:inset 0 0 0 1px #266FFF !important;
}
.custom_attrs_content2 .el-input__wrapper{
  box-shadow: 0 0 0 transparent;
}
.custom_attrs_content2 .el-input__wrapper.is-focus{
  box-shadow:inset 0 0 0 1px #266FFF !important;
}
.custom_attrs_content3 .el-input__wrapper{
  box-shadow: 0 0 0 transparent;
}
.custom_attrs_content3 .el-input__wrapper.is-focus{
  box-shadow:inset 0 0 0 1px #266FFF !important;
}

.addAttrBox{
  width: 100%;
  height: 38px;
  background-color: #f5f8ff;
  line-height: 38px;
  text-align: center;
  font-family: '微软雅黑', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 14px;
  color: #266FFF;
  border: 1px dashed #266FFF;
  margin-top: 10px;
  cursor: pointer;
}


</style>