<template>
  <div class="XFpdding" style="height: 350px;">
    <ul>
      <li
        class="item"
        v-for="(tab, index) in tabslist1"
        :key="index"
        :class="{ active: currentTab1 === index }"
        @click="selectTab1(index)"
      >
        <img :src="tab.imgSrc" style="width: 22px;"/>
        {{ tab.name }}
      </li>
    </ul>
    <div v-show="currentTab1 == '0'" class="eldesign classtable" style="margin-top: 10px">
      <el-table :data="inParams" border style="width: 100%; " :header-cell-class-name="headerCellClassName">
          <el-table-column type="index" width="70" label="编号"/>
          <el-table-column prop="code" label="编码">
            <!-- <template #default="{ row }">
              <el-input v-model="row.code" />
            </template> -->
          </el-table-column>
          <el-table-column prop="name" label="参数名称">
            <template #default="{ row }">
              <el-input v-model="row.name" />
            </template>
          </el-table-column>
          <el-table-column prop="value" label="参数值">
            <template #default="{ row }">
              <el-input v-model="row.value" type="number" />
            </template>
          </el-table-column>
          <el-table-column prop="flag" label="启用" width="100">
            <template v-slot="scope">
              <el-checkbox
                :false-label="0"
                :true-label="1"
                
                v-model="scope.row.flag"
              />
            </template>
          </el-table-column>
        </el-table>
    </div>

    <div v-if="currentTab1 == '1'" style="margin-top: 10px;height: 280px">
        <PythonEdit  v-model:value="equation" language="python" />
    </div> 

    <div v-show="currentTab1 == '2'" class="eldesign classtable" style="margin-top: 10px">
        <el-table :data="outParams" border style="width: 100%; height: 280px" :header-cell-class-name="headerCellClassName">
          <el-table-column type="index" width="70" label="编号" />
          <el-table-column prop="name" label="参数名称">
            <template #default="{ row }">
              <el-input v-model="row.name" @change="handleEdit(row)" />
            </template>
          </el-table-column>
          <el-table-column prop="value" label="参数值">
            <template #default="{ row }">
              <el-input v-model="row.value" type="number" />
            </template>
          </el-table-column>
          <el-table-column prop="flag" label="启用" width="100">
            <template v-slot="scope">
              <el-checkbox
                :false-label="0"
                :true-label="1"
                v-model="scope.row.flag"
              />
            </template>
          </el-table-column>
        </el-table>
    </div>

    <el-dialog v-model="xinjiandialog" align-center :modal="false" :close-on-click-modal="false"
      :append-to-body="true" draggable :fullscreen="false" :modal-append-to-body="false" modal-class="summary-dlg"
       width="400" class="dialog_class bgcolor colortext tianjia sel">
      <template #header="{ titleId, titleClass }">
        <div class="my-header ">
          <!-- <el-image :src="getImgPath('xuek0.png')" fit="contain"></el-image> -->
          <h4 :id="titleId" :class="titleClass">新建</h4>
        </div>
      </template>
      <div style="margin-top: 20px;padding: 20px;">
        <el-form>
          <el-form-item label="code:" :label-width="formLabelWidth1">
            <el-input v-model="code" maxlength="100"/>
          </el-form-item>
          <el-form-item label="参数名称:" :label-width="formLabelWidth1">
            <el-input v-model="name" maxlength="100"/>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="xinjiandialog = false">取消</el-button>
          <el-button type="primary" @click="xinjiantablecolumn();xinjiandialog = false">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script  setup>
import { ref, onMounted, reactive, provide, nextTick } from "vue"
import { ElMessage, ElButton, ElDialog, ElSelect } from "element-plus"
import { request, uploadFile } from "@/utils/request"
import emitter from "@/utils/emitter"

import PythonEdit from '@/components/PythonEditor/index.vue'; 
import configParams from "@/assets/img/configParams.png";
import MathFuncX from "@/assets/img/mathfuncX.png";
import MathFuncFx from "@/assets/img/mathfuncFx.png";
import MathFuncY from "@/assets/img/mathfuncY.png";

let currentTab1 = ref(0)

let pid = ref();
let wid = ref();
let mfcid = ref();

let tabslist1 = ref([
  { id: "0", name: "自变量x", imgSrc: MathFuncX },
  { id: "1", name: "表达式y=F(x)", imgSrc: MathFuncFx },
  { id: "2", name: "因变量y", imgSrc: MathFuncY },
])

let inParams = ref([
  // { code:'', name: "00", value: 0, flag: 1 },
  // { code:'', name: "00", value: 0, flag: 1 },
  // { code:'', name: "00", value: 0, flag: 1 },
])

let equation = ref(`import os
import numpy as np
from surromdao.solver import BaseSolver

class Branin(BaseSolver):
    def __init__(self, filename=os.path):
        super().__init__(filename)

    def compute(self, xdict):
        x = np.zeros(2)
        # x[1] = x[2]`);

let outParams = ref([
  // { code:'', name: "00", value: 0, flag: 1 },
  // { code:'', name: "00", value: 0, flag: 1 },
  // { code:'', name: "00", value: 0, flag: 1 },
  // { code:'', name: "00", value: 0, flag: 1 },
  // { code:'', name: "00", value: 0, flag: 1 },
  // { code:'', name: "00", value: 0, flag: 1 },
])

let xinjiandialog = ref(false)

let formLabelWidth1 = ref(100)
let code = ref('')
let name = ref('')

// 监听 outParams 的变化
watch(
  outParams,
  (newParams) => {
    // 生成新的 equation 内容
    let newEquation = ``;

    // 遍历 outParams，添加 name = {name} 到 equation
    newParams.forEach(param => {
      newEquation += `${param.name} = \n`;
    });

    // 更新 equation 的值
    equation.value = newEquation;
  },
  { deep: true }  // 深度监听，确保数组内部变化也能触发
);

const mathfuncnew = () => {
  // console.log('新建')
  xinjiandialog.value = true;
}

let xinjiantablecolumn = () => {
  // console.log('xinjiantablecolumn')
  if(code.value && name.value){
    if(currentTab1.value === 0){
      inParams.value.push({ code: code.value, name: name.value, value: 0, flag: 1 });
    }else if(currentTab1.value === 2){
      outParams.value.push({ code: code.value, name: name.value, value: 0, flag: 1 });
    }else {
      return;
    }
    code.value = '';
    name.value = '';
  }else{
    ElMessage.error('请输入code和参数名称')
  }
}

let emit = defineEmits(['selectTab']);
const selectTab1 = (index) => {
  // console.log('dayin',index);
  currentTab1.value = index;
  // console.log('currentTab1',currentTab1.value);
  emit('selectTab', index);
}

const headerCellClassName = ({ column }) => {
  // console.log('列：',column.property)
  if (column.property === 'name') {
    console.log('yanse',column.property)
    return 'header-blue';
  } else if (column.property === 'value') {
    return 'header-green';
  } else if (column.property === 'flag') {
    return 'header-yellow';
  }
  return '';
};

const convertToStringArray = (result, Data) => {
  console.log('Data:', Data);

  // 安全检查 Data，确保它是一个数组
  if (!Array.isArray(Data)) {
    console.error('Data should be an array');
    return result; // 返回原 result 或者根据需要返回其他默认值
  }

  result = Data.map(row => {
    // 获取每一行的 `code`, `name`, `value` 和 `flag`
    const code = row.code || ' ';
    const name = row.name || ' ';
    const value = (row.value === null || row.value === undefined || row.value === '') ? ' ' : row.value;
    const flag = (row.flag === null || row.flag === undefined || row.flag === '') ? ' ' : row.flag;

    // 将字段连接为一个以逗号分隔的字符串
    return `${code},${name},${value},${flag}`;
  }).join(';');  // 每行之间用分号分隔

  return result;
}

const convertToStringArray1 = (result, Data) => {
  console.log('Data:', Data);

  // 安全检查 Data，确保它是一个数组
  if (!Array.isArray(Data)) {
    console.error('Data should be an array');
    return result; // 返回原 result 或者根据需要返回其他默认值
  }

  result = Data.map(row => {
    // 获取每一行的 `code`, `name`, `value` 和 `flag`
    const paramid = row.paramid || ' ';
    const code = row.code || ' ';
    const name = row.name || ' ';
    const value = (row.value === null || row.value === undefined || row.value === '') ? ' ' : row.value;
    const flag = (row.flag === null || row.flag === undefined || row.flag === '') ? ' ' : row.flag;

    // 将字段连接为一个以逗号分隔的字符串
    return `${paramid},${code},${name},${value},${flag}`;
  }).join(';');  // 每行之间用分号分隔

  return result;
}

const getmathfunc = (id,nowid) => {
  pid.value = id;
  if(nowid){
    wid.value = nowid;
  }
  // console.log('pid-1:',pid.value)
  const params = {
    transCode: "MDO0063",
    pid: pid.value,
    wid: wid.value
  };
  request(params).then((res) => {
    if(res == null){
      ElMessage.error('MathFunc初始化失败')
      return
    }
    if (res.hasOwnProperty("mfcid")) {
      getmathfuncAssign(res);
      emitter.emit("mfcidFromMathFunc", mfcid);
    }
  })
  .catch((err) => {
      console.log('MathFunc初始化失败err:', err)
      ElMessage.error('MathFunc初始化失败')
    })
}

const getmathfuncAssign = (data) => {
  // console.log('getxfoilAssign-data:', data);
  pid.value = data.pid;
  mfcid.value = data.mfcid;
  equation.value = data.equation;
  inParams.value = data.inParams;
  outParams.value = data.outParams;
}

const getmathfuncsave = (id,nowid) => {
  if(nowid){
    wid.value = nowid
  }
  pid.value = id;
  // console.log("pid:",pid.value);
  const params = {
    transCode: "MDO0064",
    pid: pid.value,
    wid: wid.value,
    equation: equation.value,
    inParams: convertToStringArray1([],inParams.value),
    outParams: convertToStringArray([],outParams.value)
  };
  request(params).then((res) => {
    ElMessage({
        message: '保存成功',
        type: 'success',
      })
  })
  .catch((err) => {
      ElMessage.error('保存失败')
    })
}

defineExpose({ getmathfunc, getmathfuncAssign, getmathfuncsave ,mathfuncnew})

</script>