<template>
	<div class="system-edit-dic-container">
		<el-dialog :title="(ruleForm.id ? '修改' : '新增') + '计算指标模型'" v-model="isShowDialog" width="700px">
			<el-form :model="ruleForm" ref="formRef" :rules="rules" label-width="110px">
				<el-form-item label="指标标识" prop="key">
          <el-input @input="validateKeyInput" style="width: 520px;"  v-model="ruleForm.key" placeholder="请输入指标标识" />
				</el-form-item>

        <el-form-item label="指标名称" prop="name">
					<el-input style="width: 520px;"  v-model="ruleForm.name" placeholder="请输入指标名称" />
				</el-form-item>

        <el-form-item label="指标说明" prop="description">
					<el-input style="width: 520px;"  v-model="ruleForm.description" type="textarea" placeholder="请输入内容"></el-input>
				</el-form-item>

        <el-form-item label="计算公式" prop="formula">
          <el-row class="flex" style="width: 100%;">
            <el-input style="width: 430px;" disabled v-model="ruleForm.formula" placeholder="请输入计算公式"></el-input>
            <el-button @click="showformulaFormDialog" type="primary" class="ml10">
              <el-icon>
                <ele-Edit />
              </el-icon>
              编辑
            </el-button>
          </el-row>

				</el-form-item>

				<el-form-item label="数据类型" prop="types">
					<el-select style="width: 520px;" v-model="ruleForm.types" filterable placeholder="请选择数据类型">
						<el-option v-for="item in tabData" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>

        <el-form-item label="精度" prop="accuracy" v-if="ruleForm.types == 'float' || ruleForm.types == 'double'">
          <el-input style="width: 520px;" v-model="ruleForm.accuracy" placeholder="请输入精度" />
        </el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">取 消</el-button>
					<el-button type="primary" @click="onSubmit">{{ ruleForm.id  ? '修 改' : '添 加' }}</el-button>
				</span>
			</template>
		</el-dialog>

    <el-dialog title="编辑计算公式" v-model="isShowFormulaDialog" width="600px">
			<el-form :model="formulaForm" ref="formulaFormRef" :rules="formulaFormRules" label-width="110px">
        <el-form-item label="运算符号">
          <div class="symbol-list-wrap">
            <div @click="assembleItem(item)" class="symbol-item-wrap" v-for="(item, index) in symbolList" :key="index">{{ item }}</div>
          </div>
				</el-form-item>

        <el-form-item label="设备属性" prop="key">
					<el-select @change="handleSelect" style="width: 520px;" v-model="formulaForm.key" filterable placeholder="请选择数据类型">
						<el-option v-for="item in nodeData" :key="item.key" :label="item.name" :value="item.key" />
					</el-select>
				</el-form-item>

        <el-form-item label="当前公式" prop="formula">
          <el-input ref="formulaRef" @blur="handleBlur" style="width: 520px;" v-model="formulaForm.formula" placeholder="请输入公式" />
        </el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button type="primary" @click="onSubmitFormulaForm">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
wa1
<script lang="ts" setup>
import { ref, unref } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import api from '/@/api/datahub';

const emit = defineEmits(['typeList']);

const validateAccuracy = (rule: any, value: any, callback: any) => {
  if (['float', 'double'].indexOf(ruleForm.value.types) > -1  && !value) {
    callback(new Error('请输入精度'))
  } else {
    callback()
  }
}

const route = useRoute();
const symbolList = ref([
  '+', '-', '*', '/', '(', ')', '&', '^', '|', '~', '<<', '>>'
])


const cursorIndex = ref(0);
const formulaRef = ref(null);
const formRef = ref<HTMLElement | null>(null);
const formulaFormRef = ref<HTMLElement | null>(null);
const isShowDialog = ref(false);
const isShowFormulaDialog = ref(false);
const tabData = ref([
  {
    label: 'int(整数型)',
    value: 'int',
  },
  {
    label: 'long(长整数型)',
    value: 'long',
  },
  {
    label: 'float(单精度浮点型)',
    value: 'float',
  },
  {
    label: 'double(双精度浮点型)',
    value: 'double',
  }
])

const nodeData = ref([]);
const formulaForm = ref({
  key: '',
  formula: '',
  })

const ruleForm = ref({
  id: 0,
  key: '',
  name: '',
  description: '',
  formula: '',
  types: '',
  accuracy: null,
  dataTemplateKey: ''
})
const rules = ref({
  key: [
    { required: true, message: '指标标识不能为空', trigger: 'blur' },
    { pattern: /^[a-zA-Z]+$/, message: '指标标识只能输入英文字母', trigger: 'blur' }
  ],
  name: [{ required: true, message: '指标名称不能为空', trigger: 'blur' }],
  description: [{ required: true, message: '指标说明不能为空', trigger: 'blur' }],
  formula: [{ required: true, message: '计算公式不能为空', trigger: 'blur' }],
  types: [{ required: true, message: '数据类型不能为空', trigger: 'blur' }],
  accuracy: [{ required: true, validator: validateAccuracy, trigger: 'change' }],
});

const formulaFormRules = ref({
  key: [{ required: true, message: '设备属性不能为空', trigger: 'blur' }],
  formula: [{ required: true, message: '计算公式不能为空', trigger: 'blur' }],
});

// 验证指标标识输入，只允许输入英文字母
const validateKeyInput = (val: string) => {
  ruleForm.value.key = val.replace(/[^a-zA-Z]/g, '');
};

const handleBlur = () => {
  if (!formulaRef.value) return;
  cursorIndex.value = formulaRef.value.$el.querySelector('input').selectionStart;
}

const assembleItem = (item: any) => {
  if (cursorIndex.value === 0 && !formulaForm.value.formula) {
    formulaForm.value.formula += item;
  } else {
    formulaForm.value.formula = formulaForm.value.formula.substring(0, cursorIndex.value) + item + formulaForm.value.formula.substring(cursorIndex.value);
  }
}

const handleSelect = (value: any) => {
  formulaForm.value.formula += `(${value})`;
}

const showformulaFormDialog = () => {
  if(ruleForm.value.formula) {
    formulaForm.value.formula = ruleForm.value.formula;
  }
  isShowFormulaDialog.value = true;
}

// 打开弹窗
const openDialog = (row: any, dataTemplateKey:string) => {
  resetForm();
  if (row && row.id) {
    ruleForm.value = row;
  }
  if (dataTemplateKey) {
    ruleForm.value.dataTemplateKey = dataTemplateKey;
  }
  getNodeList();
  isShowDialog.value = true;
};


// 获取数据模型节点列表
const getNodeList = () => {
  api.tnode.getList({
    tid: route.params.modelId
  }).then((res: any) => {
    nodeData.value = res.list;
  });
};
const resetForm = () => {
  ruleForm.value = {
    id: 0,
    key: '',
    name: '',
    description: '',
    formula: '',
    types: '',
    accuracy: null,
    dataTemplateKey: ''
  };
};
// 关闭弹窗
const closeDialog = () => {
  isShowDialog.value = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};

// 计算公式编辑弹窗
const onSubmitFormulaForm = () => {
  const formWrap = unref(formulaFormRef) as any;
  if (!formWrap) return;
  formWrap.validate((valid: boolean) => {
    if (valid) {
      ruleForm.value.formula = formulaForm.value.formula;
      isShowFormulaDialog.value = false;
    }
  });
};
const onSubmit = () => {
  const formWrap = unref(formRef) as any;
  if (!formWrap) return;
  formWrap.validate((valid: boolean) => {
    if (valid) {
      if (ruleForm.value.id !== 0) {
        //修改
        api.calculationIndicator.edit(ruleForm.value).then(() => {
          ElMessage.success('计算指标模型修改成功');
          closeDialog(); // 关闭弹窗
          emit('typeList');
        });
      } else {
        //添加
        api.calculationIndicator.add(ruleForm.value).then(() => {
          ElMessage.success('计算指标模型添加成功');
          closeDialog(); // 关闭弹窗
          emit('typeList');
        });
      }
    }
  });
};

defineExpose({ openDialog })
</script>

<style lang="scss" scoped>
.symbol-list-wrap {
  display: flex;
  flex-wrap: wrap;
  .symbol-item-wrap {
    width: 100px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 16px;
    
    border: 1px solid #f1f1f1;
    margin-bottom: 12px;
    margin-right: 12px;
  }
}
</style>

