<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showSuccessToast, showFailToast, showConfirmDialog } from 'vant'
import Compressor from 'compressorjs'
import axios from "axios"
import { UploaderFileListItem } from 'vant'
import {
  addGoods,
  updateGoods,
  getGoodsInfo,
  type ShopGoodsDTO
} from '@/common/apis/manage/goods'
import { useWxStoreOutside } from '@/pinia/stores/wx'

const { VITE_APP_BASE_API } = import.meta.env

const route = useRoute()
const router = useRouter()
const wxStore = useWxStoreOutside()

// 判断是新增还是编辑模式
const isEditMode = ref(false)
const goodsId = ref<number | undefined>(undefined)

// 表单数据
const formData = reactive({
  goodsName: '',
  categoryId: undefined as number | undefined,
  externalGoodsId: undefined as number | undefined,
  corpid: wxStore.corpid || '',
  monthlyPurchaseLimit: undefined as number | undefined,
  price: undefined as number | undefined,
  stock: undefined as number | undefined,
  status: 1, // 默认上架
  autoApproval: 0, // 默认不免审批
  coverImg: '',
  goodsDetail: '',
  remark: '',
  usageInstruction: '',
  belongType: undefined as number | undefined
})

// 加载状态
const loading = ref(false)
const submitting = ref(false)

// 图片上传状态
const fileList = ref<UploaderFileListItem[]>([])
const uploading = ref(false)

// 监听文件列表变化，更新封面图URL
watch(fileList, (newList) => {
  if (newList.length === 0) {
    formData.coverImg = ''
  } else {
    // 如果列表中有图片且URL有效，更新封面图URL
    const item = newList[0]
    if (item.url) {
      formData.coverImg = item.url
    }
  }
}, { deep: true })

// 编辑模式下加载商品数据
const loadGoodsData = async (id: number) => {
  try {
    loading.value = true
    const res = await getGoodsInfo(id)
    const goods = res.data

    // 填充表单数据
    Object.assign(formData, {
      goodsName: goods.goodsName || '',
      categoryId: goods.categoryId,
      externalGoodsId: goods.externalGoodsId,
      corpid: goods.corpid || wxStore.corpid || '',
      monthlyPurchaseLimit: goods.monthlyPurchaseLimit,
      price: goods.price,
      stock: goods.stock,
      status: goods.status || 1,
      autoApproval: goods.autoApproval || 0,
      coverImg: goods.coverImg || '',
      goodsDetail: goods.goodsDetail || '',
      remark: goods.remark || '',
      usageInstruction: goods.usageInstruction || '',
      belongType: goods.belongType
    })

    // 如果有封面图URL，添加到文件列表
    if (goods.coverImg) {
      fileList.value = [{
        url: goods.coverImg,
        status: 'done',
        message: '已上传'
      }]
    }
  } catch (error) {
    console.error('加载商品数据失败:', error)
    showFailToast('加载商品数据失败')
    router.back()
  } finally {
    loading.value = false
  }
}

// 图片上传处理
const handleFileUpload = async (items: UploaderFileListItem | UploaderFileListItem[]) => {
  const files = Array.isArray(items) ? items : [items]
  uploading.value = true
  try {
    const uploadPromises = files.map(async (item) => {
      item.status = 'uploading'
      item.message = '上传中...'
      const file = item.file as File
      let compressedFile = file
      try {
        compressedFile = await new Promise<File>((resolve, reject) => {
          new Compressor(file, {
            quality: 0.8,
            maxWidth: 1280,
            maxHeight: 1280,
            success(result) {
              resolve(new File([result], file.name, {
                type: 'image/jpeg',
                lastModified: Date.now()
              }))
            },
            error(err) {
              reject(err)
            }
          })
        })
      } catch (error) {
        console.error('压缩失败:', error)
      }

      const uploadFormData = new FormData()
      uploadFormData.append('file', compressedFile)

      const { data } = await axios.post<{
        code: number
        data: { url: string }
        message?: string
      }>(VITE_APP_BASE_API + '/file/upload', uploadFormData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })

      if (data.code !== 0) {
        throw new Error(data.message || '文件上传失败')
      }
      return { url: data.data.url }
    })

    const urls = await Promise.all(uploadPromises)
    files.forEach((item, index) => {
      item.status = 'done'
      item.message = '上传成功'
      item.url = urls[index].url
    })

  } catch (error) {
    showConfirmDialog({
      title: '上传失败',
      message: error instanceof Error ? error.message : '未知错误'
    })
  } finally {
    uploading.value = false
  }
}

// 初始化
onMounted(() => {
  const id = route.params.id
  if (id) {
    const idStr = Array.isArray(id) ? id[0] : id
    if (idStr) {
      isEditMode.value = true
      goodsId.value = parseInt(idStr, 10)
      if (!isNaN(goodsId.value)) {
        loadGoodsData(goodsId.value)
      } else {
        showFailToast('商品ID无效')
        router.back()
      }
    }
  }
})

// 提交表单
const submitForm = async () => {
  submitting.value = true

  try {
    // 表单验证
    if (!formData.goodsName.trim()) {
      showFailToast('请输入商品名称')
      submitting.value = false
      return
    }
    if (!formData.price || formData.price <= 0) {
      showFailToast('请输入有效的价格')
      submitting.value = false
      return
    }

    if (isEditMode.value && goodsId.value) {
      // 编辑商品
      await updateGoods(goodsId.value, {
        goodsName: formData.goodsName,
        price: formData.price,
        stock: formData.stock,
        status: formData.status,
        autoApproval: formData.autoApproval,
        coverImg: formData.coverImg || undefined,
        usageInstruction: formData.usageInstruction || undefined,
        corpid: formData.corpid || undefined
      })
      showSuccessToast('更新成功')
    } else {
      // 新增商品
      await addGoods({
        goodsName: formData.goodsName,
        price: formData.price!,
        stock: formData.stock,
        status: formData.status,
        autoApproval: formData.autoApproval,
        coverImg: formData.coverImg || undefined,
        usageInstruction: formData.usageInstruction || undefined,
        corpid: formData.corpid || undefined
      })
      showSuccessToast('添加成功')
    }

    // 返回商品列表
    router.push('/manage/goods')
  } catch (error) {
    console.error('提交失败:', error)
    showFailToast('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 返回确认
const handleBack = () => {
  showConfirmDialog({
    title: '提示',
    message: '确定放弃编辑并返回吗？'
  }).then(() => {
    router.back()
  }).catch(() => {
    // 取消
  })
}
</script>

<template>
  <div class="goods-add-edit-page">
    <!-- 加载中 -->
    <van-loading v-if="loading" size="24px" vertical>加载中...</van-loading>

    <!-- 表单 -->
    <van-form v-else @submit="submitForm">
      <van-cell-group inset>
        <!-- 商品名称 -->
        <van-field
          v-model="formData.goodsName"
          label="商品名称"
          placeholder="请输入商品名称"
          :rules="[{ required: true, message: '请输入商品名称' }]"
        />

        <!-- 价格 -->
        <van-field
          v-model.number="formData.price"
          label="价格"
          type="number"
          placeholder="请输入价格"
          :rules="[{ required: true, message: '请输入价格' }]"
        >
          <template #extra>
            <span v-if="formData.price !== undefined">¥{{ formData.price.toFixed(2) }}</span>
          </template>
        </van-field>

        <!-- 库存 -->
        <van-field
          v-model.number="formData.stock"
          label="库存"
          type="number"
          placeholder="请输入库存数量"
        />

        <!-- 状态 -->
        <van-field name="status" label="状态">
          <template #input>
            <van-radio-group v-model="formData.status" direction="horizontal">
              <van-radio :name="1">上架</van-radio>
              <van-radio :name="2">下架</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <!-- 免审批 -->
        <van-field name="autoApproval" label="免审批">
          <template #input>
            <van-radio-group v-model="formData.autoApproval" direction="horizontal">
              <van-radio :name="0">否</van-radio>
              <van-radio :name="1">是</van-radio>
            </van-radio-group>
          </template>
        </van-field>





        <!-- 封面图 -->
        <van-field name="coverImg" label="封面图">
          <template #input>
            <van-uploader
              v-model="fileList"
              :max-count="1"
              :after-read="handleFileUpload"
              :disabled="uploading"
            />
          </template>
        </van-field>


        <!-- 使用说明 -->
        <van-field
          v-model="formData.usageInstruction"
          label="使用说明"
          type="textarea"
          placeholder="请输入商品使用说明"
          rows="2"
          autosize
        />


      </van-cell-group>

      <!-- 提交按钮 -->
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit" :loading="submitting">
          {{ submitting ? '提交中...' : '提交' }}
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style scoped>
.goods-add-edit-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.van-form {
  padding-top: 12px;
}

.van-field__label {
  min-width: 90px;
}
</style>