<template>
  <div class="XFpdding" style="height: 463px;">
    <div>
      <el-form-item label="FFD包围盒：" :label-width="formLabelWidth1">
        <el-input
          v-model="ffdvalue.fname"
          :max="20"
          controls-position="right"
          @keydown.enter="keydownenter"
        >
        <template #append>
          <fileUploads
          :projectId="123" 
          solverType="exampleSolver" 
          accept=".xyz" 
          upId="uniqueId1" 
          name="点击选择文件"
          :imgSrc="imageSrc"
          @upload-success="handleFileUploadSuccess"
          />
        </template>
        </el-input>
      </el-form-item>
      <el-form-item label="参考坐标系：" :label-width="formLabelWidth1">
        <el-radio-group v-model="order">
          <el-radio :value="0" :label="0">x-y-z</el-radio>
          <el-radio :value="1" :label="1">x-z-y</el-radio>
          <el-radio :value="2" :label="2">y-x-z</el-radio>
          <el-radio :value="3" :label="3">y-z-x</el-radio>
          <el-radio :value="4" :label="4">z-x-y</el-radio>
          <el-radio :value="5" :label="5">z-y-x</el-radio>
        </el-radio-group>
      </el-form-item>
    </div>
    <el-form-item label="控制点数（X,Y,Z）：" :label-width="formLabelWidth1">
      <el-row style="width: 100%;" :gutter="5">
        <el-col :span="6">
          <el-input-number style="width: 120px;" v-model="ffdvalue.nx" controls-position="right" />
        </el-col>
        <el-col :span="6">
          <el-input-number style="width: 120px;" v-model="ffdvalue.ny" controls-position="right" />
        </el-col>
        <el-col :span="6">
          <el-input-number style="width: 120px;" v-model="ffdvalue.nz" controls-position="right" />
        </el-col>
        <el-col :span="6">
          <el-button @click="generateTable" style="width: 100%;">应用</el-button>
        </el-col>
      </el-row>
    </el-form-item>
    <div class="classtable">
      <el-table :data="tableDatacst1" style="width: 100%" border :header-cell-class-name="headerCellClassName">
        <el-table-column prop="axis" label="" width="60" />
        <el-table-column
          v-for="(item, index) in tablecstHeaders"
          :key="index"
          :prop="item.prop"
          :label="item.label"
        >
          <template #default="{ row }">
            <el-input v-model="row[item.prop]" />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script  setup>
import { ref, onMounted, reactive, provide, nextTick } from "vue"
import { RouterView, RouterLink, useRouter, useRoute } from "vue-router"
import myheader from "@/components/header.vue"
import fileUploads from '../components/fileuploads.vue'
import { request, uploadFile } from "@/utils/request"
import { ElMessage, ElButton, ElDialog, ElSelect } from "element-plus"
import { Edit, CaretBottom } from "@element-plus/icons-vue"
let formLabelWidth1 = ref('200')

let pid = ref()
let fid = ref()
let ffdid = ref()
let ffdvalue = ref({
  fname: "204",
  nx: 10,
  ny: 2,
  nz: 2
})
let order = ref(1)
let vars = ref()
let tableDatacst1 = ref([
{ axis: "Z1", X1: "1", X2: "2", X3: "3", X4: "4", X5: "5", X6: "6", X7: "7", X8: "8", X9: "9" },
{ axis: "Z2", X1: "1", X2: "2", X3: "3", X4: "4", X5: "5", X6: "6", X7: "7", X8: "8", X9: "9" }
])
let tablecstHeaders = ref([
  {prop:"X1",label:"X1"},
  {prop:"X2",label:"X2"},
  {prop:"X3",label:"X3"},
  {prop:"X4",label:"X4"},
  {prop:"X5",label:"X5"},
  {prop:"X6",label:"X6"},
  {prop:"X7",label:"X7"},
  {prop:"X8",label:"X8"},
  {prop:"X9",label:"X9"},
]) 
const imageSrc = new URL('@/assets/flowimg/ffdFileSave.png', import.meta.url).href;

const headerCellClassName = ({columnIndex}) => {
  if( columnIndex !== 0 ) {
    return 'header-blue';
  }

  return '';
}


const generateTable = () => {
  console.log("generateTable");

  // 获取X, Y, Z方向的数值
  const xCount = Number(ffdvalue.value.nx);
  const yCount = Number(ffdvalue.value.ny);
  const zCount = Number(ffdvalue.value.nz);

  // 根据选中的参考坐标系来确定列名和行名
  let columns = [];
  let rows = [];

  switch (order.value) {
    case 0: // x-y-z
      columns = Array.from({ length: xCount }, (_, i) => ({ label: `X${i + 1}`, prop: `X${i + 1}` }));
      rows = Array.from({ length: yCount }, (_, i) => ({ label: `Y${i + 1}`, prop: `Y${i + 1}` }));
      break;
    case 1: // x-z-y
      columns = Array.from({ length: xCount }, (_, i) => ({ label: `X${i + 1}`, prop: `X${i + 1}` }));
      rows = Array.from({ length: zCount }, (_, i) => ({ label: `Z${i + 1}`, prop: `Z${i + 1}` }));
      break;
    case 2: // y-x-z
      columns = Array.from({ length: yCount }, (_, i) => ({ label: `Y${i + 1}`, prop: `Y${i + 1}` }));
      rows = Array.from({ length: xCount }, (_, i) => ({ label: `X${i + 1}`, prop: `X${i + 1}` }));
      break;
    case 3: // y-z-x
      columns = Array.from({ length: yCount }, (_, i) => ({ label: `Y${i + 1}`, prop: `Y${i + 1}` }));
      rows = Array.from({ length: zCount }, (_, i) => ({ label: `Z${i + 1}`, prop: `Z${i + 1}` }));
      break;
    case 4: // z-x-y
      columns = Array.from({ length: zCount }, (_, i) => ({ label: `Z${i + 1}`, prop: `Z${i + 1}` }));
      rows = Array.from({ length: xCount }, (_, i) => ({ label: `X${i + 1}`, prop: `X${i + 1}` }));
      break;
    case 5: // z-y-x
      columns = Array.from({ length: zCount }, (_, i) => ({ label: `Z${i + 1}`, prop: `Z${i + 1}` }));
      rows = Array.from({ length: yCount }, (_, i) => ({ label: `Y${i + 1}`, prop: `Y${i + 1}` }));
      break;
    default:
      break;
  }

  // 更新表格列头
  tablecstHeaders.value = columns;

  // 生成表格的数据行
  tableDatacst1.value = [];
  for (let i = 1; i <= rows.length; i++) {
    let row = { axis: rows[i - 1].label };
    columns.forEach((column) => {
      row[column.prop] = null; // 每个单元格初始化为空
    });
    tableDatacst1.value.push(row);
  }
};


const handleFileUploadSuccess = (data) =>{
  ffdvalue.value.fname = data.fname;
  fid.value = data.bfid;
  console.log('文件上传成功，bfid:', data.bfid, 'fname:', data.fname);
}




// 用来生成 vars，存储表格中除了行名与列名的所有值
const generateVars = () => {
  let values = [];

  tableDatacst1.value.forEach(row => {
    tablecstHeaders.value.forEach(col => {
      let value = row[col.prop];
      if (value === null || value === undefined || value === '') {
        value = ' ';
      }
      values.push(value);
    });
  });

  // 将值拼接成用逗号分隔的字符串
  vars.value = values.join(',');
};

// 用来初始化表格，将 vars 中的值填充到表格中
const initializeTableFromVars = () => {
  if (!vars.value) return; 

  const values = vars.value.split(',');
  console.log('ffdchaxun',values); 

  let index = 0; 

  // 遍历 tableDatacst1 中的每一行
  tableDatacst1.value.forEach(row => {
    tablecstHeaders.value.forEach(col => {
      if (index < values.length) {
        // 将解析后的值赋给相应的单元格
        row[col.prop] = values[index] === ' ' ? '' : values[index]; // 空格用空字符串代替
        index++; 
      }
    });
  });
};


// ffd查询
const getffds = (id) => {
  pid.value = id;
  const params = {
    transCode: "MDO0043",
    pid: pid.value
  };
  request(params).then((res) => {
    if (res.hasOwnProperty("ffdid")) {
      // ffdid.value = res.ffdid;
      // ffdvalue.value.fname = res.fname;
      // ffdvalue.value.nx = res.nx;
      // ffdvalue.value.ny = res.ny;
      // ffdvalue.value.nz = res.nz;
      // order.value = Number(res.order);
      // vars.value = res.vars;
      // generateTable();
      // initializeTableFromVars();

      getffdsAssign(res);
    }
  })
  .catch((err) => {
      ElMessage.error(err.returnMsg)
    })
};

const getffdsAssign = (data) => {
  pid.value = data.pid
  ffdid.value = data.ffdid;
  ffdvalue.value.fname = data.fname;
  ffdvalue.value.nx = data.nx;
  ffdvalue.value.ny = data.ny;
  ffdvalue.value.nz = data.nz;
  order.value = Number(data.order);
  vars.value = data.vars;
  generateTable();
  initializeTableFromVars();
};

// ffd保存
const getffdsave = () => {
  generateVars();
  const params = {
    transCode: "MDO0044",
    pid: pid.value,
    fid: fid.value,
    fname: ffdvalue.value.fname,
    nx: ffdvalue.value.nx,
    ny: ffdvalue.value.ny,
    nz: ffdvalue.value.nz,
    order: order.value,
    vars: vars.value,
    checked:1
  };
  request(params)
    .then((res) => {
      ElMessage({
        message: res.returnMsg,
        type: 'success',
      })
    })
    .catch((err) => {
      ElMessage.error(err.returnMsg);
    });
};

defineExpose({ getffds,getffdsAssign, getffdsave });

</script>


