<template>
  <div v-if="value" class="platform-edit-dialog">
    <div class="dialog-overlay" @click="closeDialog"></div>
    <div class="dialog-content">
      <div class="dialog-header">
        <h3>平台配置编辑</h3>
        <div class="close-btn" @click="closeDialog">×</div>
      </div>

      <div class="dialog-body">
        <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px" size="small">
          <el-form-item label="平台图标">
            <el-upload
              class="avatar-uploader"
              :action="uploadImgUrl"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              name="file"
            >
              <div class="upload-preview-box">
                <img v-if="formData.imageUrl" :src="formatImg(formData.imageUrl)" class="avatar-img" />
                <i v-else class="el-icon-plus avatar-icon"></i>
                <div class="upload-text">更换图标</div>
              </div>
            </el-upload>
          </el-form-item>

          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入平台名称"></el-input>
          </el-form-item>

          <el-form-item label="类型">
            <el-select v-model="formData.type" placeholder="选择类型" style="width: 100%;">
              <el-option label="空中" value="Air"></el-option>
              <el-option label="海上" value="Sea"></el-option>
              <el-option label="地面" value="Ground"></el-option>
            </el-select>
          </el-form-item>

          <p class="group-title-new">性能规格</p>
          <div class="specs-container">
            <el-form-item label="巡航速度">
              <div class="input-with-del">
                <el-input v-model="specs.speed" placeholder="km/h"></el-input>
                <el-button type="text" icon="el-icon-close" class="del-icon" @click="specs.speed = ''"></el-button>
              </div>
            </el-form-item>

            <el-form-item label="单位油耗">
              <div class="input-with-del">
                <el-input-number v-model="specs.fuelConsumption" :precision="2" style="width: 100%"></el-input-number>
                <el-button type="text" icon="el-icon-close" class="del-icon" @click="specs.fuelConsumption = 0"></el-button>
              </div>
            </el-form-item>

            <el-form-item label="高度限制">
              <div class="input-with-del">
                <div class="range-row">
                  <el-input-number v-model="specs.minAlt" placeholder="最低" controls-position="right"></el-input-number>
                  <span>~</span>
                  <el-input-number v-model="specs.maxAlt" placeholder="最高" controls-position="right"></el-input-number>
                  <span class="unit-text">m</span>
                </div>
                <el-button type="text" icon="el-icon-close" class="del-icon" @click="resetAlt"></el-button>
              </div>
            </el-form-item>

            <el-form-item label="威力扇区">
              <div class="input-with-del">
                <div class="range-row">
                  <el-input-number v-model="specs.radius" placeholder="半径" controls-position="right"></el-input-number>
                  <span class="unit-text">km /</span>
                  <el-input-number v-model="specs.angle" :max="360" placeholder="角度" controls-position="right"></el-input-number>
                  <span class="unit-text">°</span>
                </div>
                <el-button type="text" icon="el-icon-close" class="del-icon" @click="resetSector"></el-button>
              </div>
            </el-form-item>
          </div>

          <div style="display: flex; justify-content: space-between; align-items: center; margin: 25px 0 10px;">
            <p class="group-title-new" style="margin: 0;">扩展参数</p>
            <div class="add-prop-container">
              <el-button
                type="primary"
                plain
                size="mini"
                icon="el-icon-plus"
                @click="addProp"
              >添加扩展参数</el-button>
            </div>
          </div>

          <div v-for="(item, index) in customProps" :key="index" class="custom-prop-row">
            <el-input v-model="item.key" placeholder="属性名" style="width: 35%"></el-input>
            <el-input v-model="item.value" placeholder="属性值" style="width: 50%"></el-input>
            <i class="el-icon-delete delete-prop-icon" @click="removeProp(index)"></i>
          </div>
        </el-form>
      </div>

      <div class="dialog-footer-new" style="display: flex; justify-content: center; gap: 40px; padding-top: 10px; padding-bottom: 20px;">
        <el-button size="medium" @click="closeDialog" style="width: 120px; border-radius: 20px;">取 消</el-button>
        <el-button size="medium" type="primary" @click="savePlatform" style="width: 120px; border-radius: 20px;">保 存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { updateLib } from "@/api/system/lib";

export default {
  name: 'PlatformEditDialog',
  props: {
    value: { type: Boolean, default: false },
    platform: { type: Object, default: () => ({}) }
  },
  data() {
    return {
      // 上传相关配置
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      headers: { Authorization: "Bearer " + getToken() },
      // 基础一级字段
      formData: {
        name: '',
        type: '',
        imageUrl: ''
      },
      //固定的性能参数
      specs: {
        speed: '',
        fuelConsumption: 0,
        minAlt: 0,
        maxAlt: 0,
        radius: 0,
        angle: 0
      },
      //动态自定义属性数组
      customProps: [],
      rules: {
        name: [{ required: true, message: '请输入平台名称', trigger: 'blur' }]
      }
    };
  },
  watch: {
    value(newVal) {
      if (newVal) {
        console.log("子组件接收到的原始数据:", this.platform);
        this.$nextTick(() => {
          this.initFormData();
        });
      }
    }
  },
  methods: {
    // 初始化数据，拆解 JSON
    initFormData() {
      // 基础字段回显
      this.formData = {
        name: this.platform.name || '',
        type: this.platform.type || '',
        imageUrl: this.platform.imageUrl || ''
      };
      let rawSpecs = {};
      try {
        // 解析 JSON 字符串
        rawSpecs = this.platform.specsJson ? JSON.parse(this.platform.specsJson) : {};
      } catch (e) {
        console.error("JSON解析失败", e);
        rawSpecs = {};
      }
      // 填充固定参数：使用 ?? (空值合并) 确保 0 也能被正确回显
      this.specs = {
        speed: rawSpecs.speed ?? '',
        fuelConsumption: rawSpecs.fuelConsumption ?? 0,
        minAlt: rawSpecs.minAlt ?? 0,
        maxAlt: rawSpecs.maxAlt ??  0,
        radius: rawSpecs.radius ??  0,
        angle: rawSpecs.angle ?? 0
      };

      // 提取自定义参数：排除掉固定键名以及系统生成的冗余键名
      const fixedKeys = [
        'speed', 'fuelConsumption', 'minAlt', 'maxAlt', 'radius', 'angle',
        'minAltitude', 'maxAltitude', 'sectorRadius', 'sectorAngle',
        'origin', 'createTime'
      ];
      this.customProps = Object.keys(rawSpecs)
        .filter(key => !fixedKeys.includes(key))
        .map(key => ({
          key: key,
          value: rawSpecs[key]
        }));
    },

    // 上传成功回调
    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.formData.imageUrl = res.fileName; // 拿到相对路径
        this.$message.success("图标上传成功");
      }
    },

    savePlatform() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 封装 specs_json 逻辑
          const finalSpecs = {};
          // 过滤掉空值，只保留有用的参数
          Object.keys(this.specs).forEach(key => {
            const val = this.specs[key];
            if (val !== '' && val !== null && val !== undefined) {
              finalSpecs[key] = val;
            }
          });
          // 加上自定义参数
          this.customProps.forEach(item => {
            if (item.key && item.value) finalSpecs[item.key] = item.value;
          });
          // 组装发往后端的完整数据包
          const postData = {
            id: this.platform.id,
            name: this.formData.name,
            type: this.formData.type,
            iconUrl: this.formData.imageUrl,
            specsJson: JSON.stringify(finalSpecs)
          };
          updateLib(postData).then(response => {
            // 若依自带的消息通知
            this.$modal.msgSuccess("修改成功");
            // 通知父组件
            this.$emit('save');
            this.closeDialog();
          }).catch(err => {
            console.error("更新失败：", err);
          });
        }
      });
    },

    addProp() { this.customProps.push({ key: '', value: '' }); },
    removeProp(index) { this.customProps.splice(index, 1); },
    closeDialog() { this.$emit('input', false); },

    // 图片显示逻辑
    formatImg(url) {
      if (!url) return '';
      const backendUrl = process.env.VUE_APP_BACKEND_URL;
      return backendUrl + url.replace(/\/+/g, '/').replace('/dev-api', '');
    },

    resetAlt() {
      this.specs.minAlt = 0;
      this.specs.maxAlt = 0;
    },
    resetSector() {
      this.specs.radius = 0;
      this.specs.angle = 0;
    }
  }
};
</script>

<style scoped>
/* 1. 弹窗核心容器：增加圆角，优化阴影 */
.platform-edit-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(4px);
}

.dialog-content {
  position: relative;
  background: white;
  border-radius: 16px;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
  width: 550px;
  max-height: 85vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  animation: dialog-fade-in 0.3s ease;
}

@keyframes dialog-fade-in {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}

/*  页眉页脚：彻底删掉分割线 */
.dialog-header {
  padding: 20px 25px 5px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f2f2f2;
}

.dialog-header h3 {
  font-weight: bold;
  color: #333;
}

.dialog-footer-new {
  display: flex;
  justify-content: center;
  gap: 30px;
  padding: 15px 0 30px; /* 增加底部留白，更自然 */
}

/* 3. 主体内容与滚动条 */
.dialog-body {
  padding: 10px 25px;
  overflow-y: auto;
  flex: 1;
}

.dialog-body::-webkit-scrollbar {
  width: 6px;
}
.dialog-body::-webkit-scrollbar-thumb {
  background: #e0e0e0;
  border-radius: 10px;
}

/*  分组标题 */
.group-title-new {
  font-size: 13px;
  font-weight: bold;
  color: #333;
  padding: 4px 12px;
  border-radius: 4px;
  display: inline-block;
  margin: 15px 0 10px;
  border-left: 3px solid #1890ff;
}

/* 5. 图标预览：强制左对齐 */
.avatar-uploader {
  line-height: 0;
}

.upload-preview-box {
  width: 64px;
  height: 64px;
  border: 2px dashed #e0e0e0;
  border-radius: 8px;
  margin: 0; /* 关键：确保与下方输入框对齐 */
  cursor: pointer;
  position: relative;
  transition: 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-preview-box:hover {
  border-color: #409EFF;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.avatar-icon {
  font-size: 20px;
  color: #999;
}

.upload-text {
  position: absolute;
  bottom: 0;
  width: 100%;
  background: rgba(0,0,0,0.5);
  color: #fff;
  font-size: 10px;
  text-align: center;
  opacity: 0;
  transition: 0.3s;
}

.upload-preview-box:hover .upload-text {
  opacity: 1;
}

.input-with-del {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.unit-text {
  color: #999;
  font-size: 12px;
  white-space: nowrap;
}

.custom-prop-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  padding-left: 100px;
}

.delete-prop-icon {
  color: #F56C6C;
  cursor: pointer;
  font-size: 18px;
  transition: 0.2s;
}

.delete-prop-icon:hover {
  transform: scale(1.2);
}

.close-btn {
  font-size: 22px;
  color: #999;
  cursor: pointer;
}

.add-prop-container {
  padding-left: 100px;
  margin-bottom: 15px;
}

.dialog-footer-new {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 10px 0 25px;
  border-top: none;
}
</style>
