<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">
              <!-- 根据 pageState 显示图标 -->
              <i v-if="pageState === 'add'" class="el-icon-plus f-s-20"></i>
              <i v-else class="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="form" :model="form" label-width="120px"
              :label-position="$store.state.app.isWideScreen ? 'top' : 'right'">

              <!-- 只有添加模式下显示选择商铺组件 -->
              <el-form-item v-if="pageState === 'add'" label="所属商铺">
                <SelectionShopId v-model="form.shop_id" />
              </el-form-item>

              <!-- 飞机名称 -->
              <el-form-item label="飞机名称">
                <el-input v-model="form.name" placeholder="起名可以是中文" />
              </el-form-item>

              <!-- 购买日期，添加模式可选，编辑模式禁用 -->
              <el-form-item label="购买日期">
                <el-date-picker v-if="pageState === 'add'" v-model="form.date" type="date"
                  placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="timestamp" />
                <el-date-picker v-else v-model="form.date" type="date"
                  placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="timestamp" disabled />
              </el-form-item>

              <!-- 启用/停用开关 -->
              <el-form-item :label="form.onoff ? '启用' : '停用'">
                <el-switch v-model="form.onoff" />
              </el-form-item>

              <!-- 绑定机型下拉框 -->
              <el-form-item label="绑定机型">
                <el-select v-model="form.bind_class_id" placeholder="请选择机型">
                  <el-option
                    v-for="item in planeClassList"
                    :key="item.id"
                    :label="item.class_name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <!-- 选中机型后展示信息 -->
              <el-form-item label="">
                <el-descriptions v-if="selectedPlaneClass" title="机型信息" :column="3" border>
                  <el-descriptions-item label="最大载重">
                    {{ selectedPlaneClass.weight_max }} kg
                  </el-descriptions-item>
                  <el-descriptions-item label="轴距">
                    {{ selectedPlaneClass.wheelbase }} mm
                  </el-descriptions-item>
                  <el-descriptions-item label="类别">
                    {{ selectedPlaneClass.category }}
                  </el-descriptions-item>
                </el-descriptions>
              </el-form-item>

              <!-- 飞机描述 -->
              <el-form-item label="飞机描述">
                <el-input v-model="form.desc" type="textarea" placeholder="描述备注，非必填" />
              </el-form-item>

              <!-- 底部按钮，添加 / 编辑分别处理 -->
              <el-form-item v-if="pageState === 'add'">
                <el-button type="primary" icon="el-icon-plus" @click="addAir">创建</el-button>
                <el-button @click="setForm({ shop_id: form.shop_id })" class="iconfont icon-qingchu">
                  <font class="m-l-5">重填</font>
                </el-button>
              </el-form-item>

              <el-form-item v-else>
                <el-button type="primary" icon="el-icon-edit" @click="saveAir">更新</el-button>
              </el-form-item>
            </el-form>
          </el-main>
        </el-container>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import SelectionShopId from '@/components/SelectionShopId'

export default {
  name: 'RegisterAdd',
  components: { SelectionShopId },
  data () {
    return {
      // 表单模型
      form: {
        shop_id: '',
        name: '',
        date: '',
        onoff: true,
        bind_class_id: '',
        weight_max: '',
        desc: ''
      },
      // 当前飞机 ID（用于编辑模式）
      airId: this.$route.params.id,
      // 页面状态：add（添加）或 edit（编辑）
      pageState: 'add',
      // 当前选中的飞机对象
      plane: null
    }
  },
  computed: {
    // 所有飞机列表，从 Vuex 中获取
    airList () {
      return this.$store.state.airList || []
    },
    // 飞机机型列表，从 Vuex 中获取
    planeClassList () {
      return this.$store.state.planeClassList || []
    },
    // 当前选择的机型数据
    selectedPlaneClass () {
      return this.planeClassList.find(item => item.id === this.form.bind_class_id) || null
    }
  },
  methods: {
    // 初始化表单字段
    setForm (data) {
      this.form.shop_id = data.shop_id || ''
      this.form.name = data.name || ''
      this.form.date = data.date || ''
      this.form.onoff = data.onoff !== undefined ? data.onoff : true
      this.form.bind_class_id = data.bind_class_id || ''
      this.form.weight_max = data.weight_max || ''
      this.form.desc = data.desc || ''
      if (Object.keys(data).length === 0) {
        this.$message.warning('清空表单')
      }
    },
    // 初始化页面状态
    initPage () {
      // 如果没有 ID 则为添加
      if (!this.airId) {
        this.pageState = 'add'
      } else {
        this.pageState = 'edit'
        // 查找对应飞机数据，填入表单
        const targetPlane = this.airList.find((item) => item.id === this.airId)
        if (targetPlane) {
          this.plane = targetPlane
          this.setForm({
            shop_id: targetPlane.shop_id,
            name: targetPlane.name,
            date: parseInt(targetPlane.apply_time + '000'), // 转为时间戳
            onoff: targetPlane.onoff === '1',
            bind_class_id: targetPlane.bind_class_id,
            weight_max: targetPlane.weight_max,
            desc: targetPlane.describe
          })
        }
      }
    },
    // 提交添加请求
    async addAir () {
      const res = await this.$store.dispatch('fetchAddAir', this.form)
      if (res.data.status === 1) {
        this.$router.push('/register/index') // 成功后跳转
      }
    },
    // 提交编辑请求
    async saveAir () {
      this.form.id = this.airId
      const res = await this.$store.dispatch('fetchSaveAir', this.form)
      if (res.data.status === 1) {
        this.$router.push('/register/index')
      }
    }
  },
  async created () {
    // 页面加载时获取机型列表和飞机列表
    if (!this.planeClassList.length) {
      await this.$store.dispatch('fetchPlaneClassList')
    }
    if (!this.airList.length) {
      await this.$store.dispatch('fetchAirList') // 保证编辑页可正常读取
    }
    this.initPage()
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}
</style>
