<template>
  <el-dialog
    :model-value="visible"
    :title="title"
    @close="handleClose"
    :close-on-click-modal="false"
    width="600px"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      @submit.prevent
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>

      <el-form-item label="制造商" prop="manufacturer">
        <el-input v-model="formData.manufacturer" />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" type="textarea" />
      </el-form-item>

      <el-form-item label="类别" prop="category">
        <el-select v-model="formData.category" placeholder="请选择类别" @change="handleCategoryChange">
          <el-option label="执行器" value="actuator" />
          <el-option label="传感器" value="sensor" />
        </el-select>
      </el-form-item>

      <el-form-item label="指令 (JSON)" prop="commands">
        <el-input
          v-model="formData.commands"
          type="textarea"
          :rows="5"
          placeholder="请输入JSON格式的指令参数"
        />
      </el-form-item>

      <el-form-item
        v-if="formData.category === 'sensor'"
        label="值描述 (JSON)"
        prop="values"
      >
        <el-input
          v-model="formData.values"
          type="textarea"
          :rows="5"
          placeholder="请输入JSON格式的值描述数组"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import deviceTemplateService from '../services/deviceTemplateService.js';

// 默认的JSON模板
const DEFAULT_ACTUATOR_COMMANDS = JSON.stringify({
  modbus_start_address: 0,
  modbus_quantity: 1
}, null, 2);

const DEFAULT_SENSOR_COMMANDS = JSON.stringify({
  modbus_function_code: 3,
  modbus_start_address: 0,
  modbus_quantity: 1
}, null, 2);

const DEFAULT_SENSOR_VALUES = JSON.stringify([
  {
    type: "temperature",
    multiplier: 0.1,
    offset: 0
  }
], null, 2);

export default {
  name: 'DeviceTemplateForm',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    templateData: {
      type: Object,
      default: () => ({}),
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['update:visible', 'success', 'cancel'],
  setup(props, { emit }) {
    const formRef = ref(null);
    const loading = ref(false);

    const initialFormData = () => ({
      id: '',
      name: '',
      manufacturer: '',
      description: '',
      category: 'actuator', // 默认执行器
      commands: DEFAULT_ACTUATOR_COMMANDS, // 预填充执行器指令
      values: '',
    });

    const formData = reactive(initialFormData());

    // JSON 验证器
    const validateJson = (rule, value, callback) => {
      if (!value) {
        return callback(new Error(rule.message));
      }
      try {
        JSON.parse(value);
        callback();
      } catch (e) {
        callback(new Error('请输入有效的 JSON 格式'));
      }
    };

    const rules = computed(() => ({
      name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
      category: [{ required: true, message: '请选择模板类别', trigger: 'change' }],
      commands: [
        { required: true, message: '请输入指令参数', trigger: 'blur' },
        { validator: validateJson, message: '指令参数必须是有效的 JSON 格式', trigger: 'blur' },
      ],
      values: [
        { required: formData.category === 'sensor', message: '请输入值描述', trigger: 'blur' },
        { validator: validateJson, message: '值描述必须是有效的 JSON 格式', trigger: 'blur' },
      ],
    }));

    const title = computed(() => {
      return props.isEdit ? '编辑设备模板' : '新增设备模板';
    });

    const handleCategoryChange = (newCategory) => {
      if (newCategory === 'actuator') {
        formData.commands = DEFAULT_ACTUATOR_COMMANDS;
        formData.values = ''; // 执行器没有values
      } else if (newCategory === 'sensor') {
        formData.commands = DEFAULT_SENSOR_COMMANDS;
        formData.values = DEFAULT_SENSOR_VALUES; // 传感器预填充values
      }
      nextTick(() => {
        if (formRef.value) {
          formRef.value.clearValidate();
        }
      });
    };

    const handleClose = () => {
      emit('update:visible', false);
      emit('cancel');
      // 重置表单
      Object.assign(formData, initialFormData());
      nextTick(() => {
        if (formRef.value) {
          formRef.value.resetFields();
        }
      });
    };

    const handleSubmit = async () => {
      if (!formRef.value) return;
      await formRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true;
          try {
            const submitData = {
              name: formData.name,
              manufacturer: formData.manufacturer,
              description: formData.description,
              category: formData.category,
              commands: JSON.parse(formData.commands),
            };

            if (formData.category === 'sensor' && formData.values) {
              submitData.values = JSON.parse(formData.values);
            }

            if (props.isEdit) {
              await deviceTemplateService.updateDeviceTemplate(formData.id, submitData);
            } else {
              await deviceTemplateService.createDeviceTemplate(submitData);
            }

            emit('success');
            handleClose();
          } catch (error) {
            console.error('保存设备模板失败:', error);
            ElMessage.error(
              props.isEdit ? '编辑设备模板失败: ' + (error.message || '未知错误') : '创建设备模板失败: ' + (error.message || '未知错误')
            );
          } finally {
            loading.value = false;
          }
        }
      });
    };

    watch(
      () => props.templateData,
      (newVal) => {
        if (newVal && Object.keys(newVal).length > 0) {
          // 填充表单数据
          formData.id = newVal.id;
          formData.name = newVal.name;
          formData.manufacturer = newVal.manufacturer;
          formData.description = newVal.description;
          formData.category = newVal.category;
          // 格式化JSON显示
          formData.commands = newVal.commands ? JSON.stringify(newVal.commands, null, 2) : '';
          formData.values = newVal.values ? JSON.stringify(newVal.values, null, 2) : '';
        } else {
          // 重置表单数据到初始状态 (新增模式)
          Object.assign(formData, initialFormData());
        }
        nextTick(() => {
          if (formRef.value) {
            formRef.value.clearValidate();
          }
        });
      },
      { immediate: true }
    );

    watch(
      () => props.visible,
      (newVal) => {
        if (newVal && !props.isEdit) {
          // 如果是新增模式且对话框打开，重置表单
          Object.assign(formData, initialFormData());
          nextTick(() => {
            if (formRef.value) {
              formRef.value.clearValidate();
            }
          });
        }
      },
      { immediate: true }
    );

    return {
      formRef,
      loading,
      formData,
      rules,
      title,
      handleCategoryChange,
      handleClose,
      handleSubmit,
    };
  },
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>