<template>

    <div style="height: 100%;padding: 10px;">
      
      <a-row :gutter="[16, 24]">
        <a-col class="gutter-row" :span="24">
          <vxe-grid v-bind="gridOptions" ref="tableRef">
            <template #toolbarButtons>
              <div style="margin:10px">
                <a-tag color="red">请点击权重列，设置权重</a-tag>
              </div>
            </template>
          </vxe-grid>
        </a-col>
        <a-col class="gutter-row" :span="24">
          <vxe-form
            vertical
            ref="formRef"
            :data="formData"
            :rules="formRules"
            :loading="loading"
            @submit="submitEvent"
            @reset="resetEvent">
            <!-- <vxe-form-item title="指标编号" field="mtrcNo" span="24">
              <template #default="params">
                <vxe-input v-model="params.data.mtrcNo" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
              </template>
            </vxe-form-item> -->
            <vxe-form-item title="指标名称" field="mtrcName" span="24">
              <template #default="params">
                <vxe-input v-model="params.data.mtrcName" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
              </template>
            </vxe-form-item>
            <vxe-form-item title="指标公式" field="formulaName" span="24" :item-render="{}" title-overflow>
              <template #default="params">
                <vxe-textarea v-model="params.data.formulaName" placeholder="请输入" :autosize="{minRows: 6, maxRows: 10}" clearable readonly></vxe-textarea>
              </template>
            </vxe-form-item>
          </vxe-form>
        </a-col>
      </a-row>
    </div>

</template>

<script lang="ts" setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { VXETable, VxeGridProps, VxeGridInstance } from 'vxe-table'
import {saveOrUpdate} from '../MetricMonitorSetHight.api';

const emit = defineEmits(['callback','success']);

const loading = ref(false);
const tableRef = ref<VxeGridInstance>();


const gridOptions = reactive<VxeGridProps<any>>({
    border: true,
    maxHeight: 400,
    columnConfig: {
      resizable: true
    },
    columns: [
      { type: 'seq', width: "5%" },
      { field: 'mtrcName', title: '指标名称'},
      { field: 'mtrcNo', title: '指标编码', width: "30%" },
      { 
        field: 'Weight', 
        title: '权重', 
        width: "30%",
        editRender: { name: 'VxeInput' },
        cellRender: {
          name: 'VxeInput'
        }
      },
    ],
    editConfig: {
      trigger: 'click',
      mode: 'row',
      afterEdit: ({ row, column }) => {
        if (column.field === 'Weight') {
          updateformulaFromTable();
        }
      }
    },
    toolbarConfig: {
      zoom: true,
      slots: {
        buttons: 'toolbarButtons',
        tools: "toolsButtons"
      },
    },
    data: [],
    dataChange: (data) => {
      updateformulaFromTable();
    }
})


watch(() => gridOptions.data, (newData) => {
  updateformulaFromTable();
}, { deep: true })


const iniData = (datas) => {
  gridOptions.data = datas ? [...datas] : []
  nextTick(() => {
    updateformulaFromTable();
  })
}

const updateformulaFromTable = async() => {
  if (gridOptions.data && gridOptions.data.length > 0) {
    await createformula(gridOptions.data);
    //formData.value.formulaName = newFormula;
    if (gridOptions.data[0]?.mtrcName && !formData.value.mtrcName) {
      formData.value.mtrcName = gridOptions.data[0].mtrcName + '_综合指标';
    }
  } else {
    formData.value.formula = '';
  }
}

const formRef = ref()
const formData = ref({
  id:'',
  mtrcName: '',
  formula: '',
  mtrcNo:'',
  params:'',
  formulaName:'',
})
const formRules = ref({
  mtrcNo: [
    { required: true, message: '请输入编号' },
    { min: 5, max: 5, message: '长度在5个数字' }
  ],
  mtrcName: [
    { required: true, message: '请输入名称' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符' }
  ],
  formula: [
    { required: true, message: '请输入公式' }
  ]
})

const createformula = async (datas, options = {}) => {
  // 参数验证
  if (!Array.isArray(datas)) {
    console.warn('createformula: datas 参数必须是数组');
    return { nameFormula: '', codeFormula: '' };
  }

  // 默认配置
  const config = {
    operator: '+',
    weightKey: 'Weight',
    nameKey: 'mtrcName',
    codeKey: 'mtrcNo', // 新增代码字段的key
    defaultWeight: 1,
    validateWeights: true,
    ...options
  };

  try {
    const validItems = datas.filter(item => {
      if (!item || typeof item !== 'object') {
        console.warn('createformula: 跳过无效数据项', item);
        return false;
      }
      
      const name = item[config.nameKey];
      const code = item[config.codeKey];
      
      // 名称和代码都需要存在
      if ((name === undefined || name === null || name === '') || 
          (code === undefined || code === null || code === '')) {
        return false;
      }
      return true;
    });

    const nameFormulaItems = [];
    const codeFormulaItems = [];
    const codes = [];

    validItems.forEach(item => {
      const name = item[config.nameKey];
      const code = item[config.codeKey];
      let weight = item[config.weightKey];
      
      // 处理权重值
      if (weight === undefined || weight === null || weight === '') {
        weight = config.defaultWeight;
      }
      
      if (config.validateWeights) {
        const numWeight = Number(weight);
        if (isNaN(numWeight)) {
          weight = config.defaultWeight;
        } else {
          weight = numWeight;
        }
      }
      
      // 构建名称公式项
      if (weight === 1) {
        nameFormulaItems.push(name);
      } else {
        nameFormulaItems.push(`${name}*${weight}`);
      }
      
      // 构建代码公式项
      if (weight === 1) {
        codeFormulaItems.push(code);
      } else {
        codeFormulaItems.push(`${code}*${weight}`);
      }
      codes.push(code)
    });

    const result = {
      nameFormula: nameFormulaItems.length > 0 ? nameFormulaItems.join(` ${config.operator} `) : '',
      codeFormula: codeFormulaItems.length > 0 ? codeFormulaItems.join(` ${config.operator} `) : '',
      codes: codes.length > 0 ? codes.join(",") : ''
    };

    // 如果需要，仍然可以设置到formData中
    formData.value.formulaName = result.nameFormula;
    formData.value.formula = result.codeFormula;
    formData.value.params = result.codes;

    //return result;

  } catch (error) {
    console.error('createformula: 生成公式时发生错误', error);
    return { nameFormula: '', codeFormula: '' };
  }
};

const updateWeight = (index, newWeight) => {
  if (gridOptions.data && gridOptions.data[index]) {
    gridOptions.data[index].Weight = newWeight;
    updateformulaFromTable();
  }
}

const changeEvent = (params) => {
  const $form = formRef.value
  if ($form) {
    $form.updateStatus(params)
  }
}

const submitEvent = async  (isUpdate) => {
  loading.value = true
  await saveOrUpdate(formData.value,isUpdate)
  loading.value = false
  emit("success")
}

const resetEvent = () => {
  updateformulaFromTable();
  VXETable.modal.message({ content: '已重置公式', status: 'info' })
}

const iniEditData = (oldData) => {
  Object.assign(formData.value,oldData);
  nextTick(() => {
    updateformulaFromTable();
  })
}



defineExpose({
  iniData,
  submitEvent,
  iniEditData,
});

</script>