<template>
  <div class="app-container">
    <el-row class="m-t-0">
      <el-col :span="24">
        <el-container>
          <el-header height="42px" class="l-h-42 p-l-10 p-r-10 border border-b-n">
            <div class="l">
              <i :class="pageState === 'add' ? 'el-icon-plus f-s-20' : 'el-icon-edit f-s-20'"></i>
              <font class="m-l-10 f-s-18 fb">{{ $route.meta.title }}</font>
            </div>
          </el-header>
          <el-main class="border p-20 m-b-20">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px"
              :label-position="$store.state.app.isWideScreen ? 'top' : 'right'" class="w-80">

              <!-- 基本信息 -->
              <div class="p-b-5">
                <el-divider content-position="left">
                  <font class="fb f-s-18 normalFontColor">基本信息</font>
                </el-divider>
              </div>
              <el-form-item label="样式名称" prop="name">
                <el-input v-model="form.name" placeholder="例如：谷歌卫星" />
              </el-form-item>
              <el-form-item label="是否启用" prop="is_active">
                <el-switch v-model="form.is_active" :active-value="1" :inactive-value="0" />
              </el-form-item>
              <el-form-item label="排序" prop="sort_order">
                <el-input-number v-model="form.sort_order" :min="0" :max="9999" :step="1" />
              </el-form-item>

              <!-- 资源信息 -->
              <div class="p-t-10 p-b-5">
                <el-divider content-position="left">
                  <font class="fb f-s-18 normalFontColor">资源与源配置（84坐标系）</font>
                </el-divider>
              </div>
              <el-form-item label="sprite 路径" prop="sprite">
                <el-input v-model="form.sprite"
                  :placeholder="form.sprite && form.sprite.includes('/Public/map/sprite') ? '使用默认路径 /Public/map/sprite' : '可选：sprite 路径（留空则使用默认路径）'" />
              </el-form-item>
              <el-form-item label="glyphs 路径" prop="glyphs">
                <el-input v-model="form.glyphs" placeholder="可选：glyphs 路径（如有）" />
              </el-form-item>
              <!-- 固定使用默认值，不显示 -->
              <el-form-item label="瓦片URL" prop="url"
                :rules="[{ required: true, message: '请输入瓦片URL', trigger: 'blur' }]">
                <el-input v-model="form.url"
                  placeholder="请输入瓦片URL，例如：http://gac-geo.googlecnapps.cn/maps/vt?lyrs=m&x={x}&y={y}&z={z}" />
              </el-form-item>
              <!-- 固定使用默认值，不显示 -->

              <!-- 提交按钮 -->
              <el-form-item>
                <el-button type="primary" :icon="pageState === 'add' ? 'el-icon-plus' : 'el-icon-edit'"
                  @click="pageState === 'add' ? addMapStyle() : saveMapStyle()">
                  {{ pageState === 'add' ? '创建' : '更新' }}
                </el-button>
                <el-button v-if="pageState === 'add'" class="iconfont icon-qingchu" @click="resetForm">
                  <font class="m-l-5">重填</font>
                </el-button>
              </el-form-item>

            </el-form>
          </el-main>
        </el-container>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'MapStyleAdd',
  data () {
    return {
      form: {
        id: null,
        name: '',
        sprite: '',
        glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
        url: '', // 瓦片URL
        is_active: 1,
        sort_order: 0
      },
      pageState: 'add',
      mapStyleId: this.$route.params.id,
      rules: {
        name: [{ required: true, message: '请输入样式名称', trigger: 'blur' }],
        url: [{ required: true, message: '请输入瓦片URL', trigger: 'blur' }]
      }
    }
  },
  async created () {
    // 初始化页面状态与预填充
    if (this.mapStyleId != null) {
      this.pageState = 'edit'
      this.form.id = this.mapStyleId
      let item = (this.$store.state.mapStyleList || []).find(i => String(i.id) === String(this.mapStyleId))
      if (!item) {
        // 尝试拉取一次列表后再匹配（兼容刷新后store丢失）
        try {
          await this.$store.dispatch('fetchMapStyleList', this.$store.state.settings.host)
          item = (this.$store.state.mapStyleList || []).find(i => String(i.id) === String(this.mapStyleId))
        } catch (e) { }
      }
      if (item) {
        this.fillFormFromItem(item)
      } else {
        this.$message.warning('未在列表中找到该样式，表单为空')
      }
    }
  },
  methods: {
    // 校验 tiles 输入（行或JSON数组）
    parseTilesInput (val) {
      const text = (val || '').trim()
      if (!text) return []
      try {
        const asJson = JSON.parse(text)
        if (Array.isArray(asJson)) return asJson
      } catch (e) {
        // 不是JSON，按行解析
      }
      return text.split(/\r?\n/).map(s => s.trim()).filter(Boolean)
    },
    fillFormFromItem (item) {
      this.form = {
        id: item.id,
        name: item.name,
        sprite: item.sprite || '',
        glyphs: item.glyphs || 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
        url: item.url || (item.sources && item.sources.default && item.sources.default.tiles &&
          item.sources.default.tiles.length > 0 ? item.sources.default.tiles[0] : ''),
        is_active: item.is_active,
        sort_order: item.sort_order
      }

      // 处理从 _original 中恢复数据
      if (item._original) {
        this.form.url = item._original.url || ''
        this.form.sprite = item._original.sprite || ''
        this.form.glyphs = item._original.glyphs || 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf'
      }
    },
    resetForm () {
      this.$refs.formRef.resetFields()
      this.form = {
        id: null,
        name: '',
        sprite: '',
        glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
        url: '',
        is_active: 1,
        sort_order: 0
      }
    },
    /**
     * @description: 创建地图样式
     */
    async addMapStyle () {
      const res = await this.$store.dispatch('addMapStyle', this.form)
      if (res.data.status === 1) {
        this.$router.push('/mapstyle/index')
      }
    },
    /**
     * @description: 更新地图样式
     */
    async saveMapStyle () {
      this.form.id = this.mapStyleId
      const res = await this.$store.dispatch('saveMapStyle', this.form)
      if (res.data.status === 1) {
        this.$router.push('/mapstyle/index')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/theme.scss";

.w-80 {
  max-width: 880px;
}
</style>
