<template>
    <BasicModal v-bind="$attrs" @register="registerModal"  :centered="true" destroyOnClose :title="title" :width="900" @ok="handleSubmit">
        <BasicForm @register="registerForm"/>
    </BasicModal>
  </template>
  
  <script lang="ts" setup>
      import {ref, computed, unref} from 'vue';
      import {BasicModal, useModalInner} from '/@/components/Modal';
      import {BasicForm, useForm,FormSchema} from '/@/components/Form/index';
      import {saveOrUpdate} from '../MetricMonitorSet.api';
     
      const parameters = ref();
      const activeKey = ref();

      const extractParameters = (formula) => {
            const regex = /[a-zA-Z]+/g;
            parameters.value = formula.match(regex);
            return parameters.value;
      };

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

      const metricId = ref();
      const oldFileds = ref([]);
      
      const onChange= (e) => {
        const formula = e.target.value;
        setParams(formula)
      }
            
     function setParams(formula) {
        const parameters = extractParameters(formula);
        parameters.forEach((parameter) => {
            if(oldFileds.value.indexOf(parameter)<0){
                oldFileds.value.push(parameter)
                appendSchemaByField({
                    component: 'JSelectMetric',
                    label: '参数'+parameter,
                    field: parameter,
                    componentProps: {
                        rowKey: 'mtrcNo',
                        labelKey: 'mtrcName',
                    },
                },undefined) 
           }
       
        });

        let i=0;
        oldFileds.value.forEach((filed) => {
            if(!parameters.includes(filed)){
                removeSchemaByFiled(filed);
                oldFileds.value.splice(i,1)
            }
            i++
        });
     }

      const formSchemaFomulas: FormSchema[] = [
        {
            label: '',
            field: 'id',
            component: 'Input',
            show: false
        },{
            label: '指标公式',
            field: 'formula',
            component: 'Input',
            componentProps: {
                rows: 1,
                placeholder: '参数最好都用大写字母',
                //onBlur: onChange,
                onChange:onChange
            },
        }
    ]

    const [registerForm, {setProps,resetFields, getFieldsValue,setFieldsValue,appendSchemaByField,removeSchemaByFiled}] = useForm({
        //labelWidth: 150,
        schemas: formSchemaFomulas,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });

      //表单赋值
      const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
          //重置表单
            metricId.value = data.record.id
            setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
            let tmpFormulas = data.record.formulas;
            
            await deleteField()

            if(tmpFormulas!="") { 
               let jsonObj = JSON.parse(tmpFormulas)
                await setParams(jsonObj['formula'])
                await setFieldsValue({
                    ...jsonObj
                });
            }
            setProps({ disabled: !data?.showFooter })
      });
      const title = "公式"

      async function handleSubmit(v) {
          try {          
              let values = JSON.stringify(getFieldsValue())
              let retjson = {
                  id:metricId.value,
                  formulas:values.toString()
              }
              //setModalProps({confirmLoading: true});
              await saveOrUpdate(retjson);
              await resetFields();
              deleteField();
              closeModal();
              emit('success');
          } finally {
              setModalProps({confirmLoading: false});
          }
      }

    async function deleteField() {
        if(oldFileds.value){
            while(oldFileds.value.length>0) {
                let first = oldFileds.value[0]
                await removeSchemaByFiled(first);
                oldFileds.value.splice(0,1)
            }
            oldFileds.value = []
        }
    }



  </script>
  
  <style lang="less" scoped>
      /** 时间和数字输入框样式 */
    :deep(.ant-input-number){
          width: 100%
      }
  
      :deep(.ant-calendar-picker){
          width: 100%
      }
  </style>