<template>
  <div style="width: 100%;height: 100%;">
    <div class="content">
      <el-container style="height: 100%;">
        <el-aside class="leftaside">
          <div class="left-1">
            <ex-design ref="exRef" :type="type" :exDatajson="oneData"/>
          </div>
          <div class="left-2">
            <agent-model ref="amRef" :type="type" :amDatajson="twoData" :isfileup="isButtonEnabled"/>
          </div>
          <div class="left-3">
            <op-algorithm ref="oaRef" :type="type" :oaDatajson="thirdData"/>
          </div>
          <div class="left-4">
            <op-run :type="type" @saveAllData="projectinfochange"/>
          </div>
        </el-aside>
        <el-main></el-main>
        <el-aside class="rightaside">
          <div class="right-1">
            <op-problem ref="opRef" :type="type" :opDatajson="fourData" :runtype="type"/>
          </div>
          <div class="right-2">
            <analyze-work @changetype="handleTypeChange"/>
          </div>
        </el-aside>
      </el-container>
    </div>
    <div class="footer">
      <info-log />
    </div>
  </div>
</template>

<script setup>
import { request, enPassword } from "@/utils/request";

import { ElMessage, ElMessageBox } from 'element-plus'

import infoLog from './footer/infoLog.vue';
import exDesign from './leftaside/exDesign.vue';
import agentModel from './leftaside/agentModel.vue';
import opAlgorithm from './leftaside/opAlgorithm.vue';
import opRun from './leftaside/opRun.vue';
import analyzeWork from './rightaside/analyzeWork.vue';
import opProblem from './rightaside/opProblem.vue';

import { useProjectStore } from '@/store/project'
import { useValOptionsStore } from '@/store/valoptions'

const projectStore = useProjectStore()
const valOptionsStore = useValOptionsStore()

const pid = computed(() => projectStore.pid)
const type = ref(0)

const projectInitJson = ref()

const oneData = ref()
const twoData = ref()
const thirdData = ref()
const fourData = ref()
const exRef = ref()
const amRef = ref()
const oaRef = ref()
const opRef = ref()

const valType1Items = ref()


const getProjectInit = () => {
  const params = {
    transCode: 'AC00009',
    pid: pid.value,
    type: type.value,
  };
  request(params)
    .then((res) => {
      projectInitJson.value = JSON.parse(res.pattJson); // 转换为 JSON 对象
      console.log(projectInitJson.value); // 输出解析后的对象

      oneData.value = projectInitJson.value[0];
      twoData.value = projectInitJson.value[1];
      thirdData.value = projectInitJson.value[2];
      fourData.value = projectInitJson.value[3];

      // 初始化选项
      valType1Items.value = findValType1Items(projectInitJson.value);
      // 去重
      const valCodeTypes = [
        ...new Set(
          valType1Items.value
            .filter(item => item?.valCodeType)
            .map(item => item.valCodeType)
        )
      ];
      console.log('valCodeTypes:', valCodeTypes);
      Promise.all(
        valCodeTypes.map(async (valCodeType) => {
          const rows = await getValTypeOptions(valCodeType);
          return { valCodeType, rows };
        })
      )
      .then(results => {
        const dataMap = Object.fromEntries(results.map(item => [item.valCodeType, item.rows]));
        console.log("映射结果 dataMap:", dataMap);
        valOptionsStore.setValOptionsMap(dataMap);
      })
      .catch(err => {
        ElMessage.error(err.returnMsg || "选项初始化失败");
        console.log(err);
      });

      console.log('选项',valType1Items);

      // console.log(oneData.value);
    })
    .catch((err) => {
      ElMessage.error(err.returnMsg || "初始化失败");
      console.error(err);
    });
}

const getValTypeOptions = async (valCodeType) => {
  const params = {
    transCode: 'BES001',
    type: valCodeType,
  };
  const res = await request(params);
  return res.rows;
};

function findValType1Items(nodes) {
  let result = [];

  function traverse(nodeList) {
    nodeList.forEach(node => {
      // 判断当前节点
      if (node.vo?.valType === 1 && node.vo?.valCodeType !== "swithType") {
        result.push(node.vo);
      }
      // 递归遍历子节点
      if (Array.isArray(node.svo) && node.svo.length > 0) {
        traverse(node.svo);
      }
    });
  }

  traverse(nodes);
  return result;
}


// 项目属性添加修改
const projectinfochange = async () => {
  try {
    const exdata = exRef.value.saveData();
    const amdata = amRef.value.saveData();
    const oadata = oaRef.value.saveData();
    const opdata = opRef.value.gatherData();

    // 合并数据
    const allData = [...exdata, ...amdata, ...oadata, ...opdata];
    console.log('alldata', allData);

    // 格式化 rows
    const rows = allData.map(item => ({
      pid: pid.value,
      attId: item.attId,
      pattId: item.pattId,
      val: item.val
    }));

    // 发请求
    const params = {
      transCode: 'AC00005',
      rows
    };

    const res = await request(params);
    // ElMessage.success('保存成功');
  } catch (err) {
    console.error(err);
    ElMessage.error(err.returnMsg || '保存失败');
  }
};

// 分析工况类型切换
const handleTypeChange = async (val) => {
  console.log('type', val);
  await projectinfochange();
  type.value = val;
};


// 代理模型文件上传是否可用
const isButtonEnabled = computed(() => {
  const DOE = exRef.value?.exDataObj?.switch?.val;
  const SMT = amRef.value?.amDataObj?.switch?.val;
  const OPT = oaRef.value?.oaDataObj?.switch?.val;
  // console.log('[调试] DOE:', DOE, 'SMT:', SMT, 'OPT:', OPT );

  // 情况 3: DOE关, SMT开, OPT关
  const case3 = DOE === '0' && SMT === '1' && OPT === '0';

  // 情况 6: DOE关, SMT开, OPT开
  const case6 = DOE === '0' && SMT === '1' && OPT === '1';

  // console.log('[调试] case3:', case3, 'case6:', case6, '最终可用:', case3 || case6);

  return case3 || case6;
});


// 监听 type 的变化
watch(
  () => type.value,
  (newVal) => {
    getProjectInit();
  }
)

onMounted(() => {
  getProjectInit();
});


</script>

<style scoped>
.content {
  width: 100%;
  height: 80%;

  .leftaside {
    width: 25%;
    height: 100%;
    padding-left: 10px;

    display: flex;
    flex-direction: column;
    gap: 5px;
    overflow: auto;
  }

  .rightaside {
    width: 25%;
    height: 100%;
    padding-right: 10px;

    display: flex;
    flex-direction: column;
    gap: 5px;
    overflow: auto;
  }
}

.leftaside {
  .left-1 {
    width: 100%;
    height: 23%;
  }

  .left-2 {
    width: 100%;
    height: 23%;
  }

  .left-3 {
    width: 100%;
    height: 29%;
  }

  .left-4 {
    width: 100%;
    height: 22%;
  }
}

.rightaside {
  .right-1 {
    width: 100%;
    height: 67%;
  }

  .right-2 {
    width: 100%;
    height: 30%;
  }
}

.footer {
  width: 100%;
  height: 20%;

  padding: 20px 10px;

  font-size: 12px;
}

</style>