<script setup>
import { ElMessage } from 'element-plus'
import FormCategory from '../components/FormCategory.vue'
import FormBaseInfo from '../components/FormBaseInfo.vue'
import FormGraphicInfo from '../components/FormGraphicInfo.vue'
import FormPrice from '../components/FormPrice.vue'
import FormService from '../components/FormService.vue'
import { createProduct, updateProduct, getProduct } from '../api'

const router = useRouter()
const route = useRoute()
const props = defineProps(['action'])
const actonMap = { add: '添加', update: '编辑', view: '查看' }

const isUpdate = computed(() => props.action === 'update')
const title = computed(() => actonMap[props.action] + '商品')

const formRef = ref()
const form = reactive({
  live_commodity_type_id: '',
  title: '',
  shopping_guide_short_title: '',
  live_commodity_attrs: {
    importance_attrs: [],
    unimportance_attrs: [],
  },
  picture_addreses: [],
  picture_34_addreses: [],
  video_url: '',
  info: {
    delivery_mode: '1', // 发货模式
    delivery_time: '1', // 发货时间
    reference_price: '', // 参考价格
    order_stock_count: '1',
    shipping_template: '', // 运费模板
    after_sales_policy: [], // 售后政策
    specs: [], // 规格列表
    sku: [], // SKU列表（通过规格笛卡尔积生成）
  },
})
provide('form', form)

async function fetchInfo() {
  const res = await getProduct({ id: route.query.id })
  const detail = res.data.detail
  const attrs = JSON.parse(detail.live_commodity_attrs)
  Object.assign(form, detail, {
    live_commodity_attrs: {
      importance_attrs: Array.isArray(attrs.importance_attrs)
        ? attrs.importance_attrs
        : Object.values(attrs.importance_attrs || {}),
      unimportance_attrs: Array.isArray(attrs.unimportance_attrs)
        ? attrs.unimportance_attrs
        : Object.values(attrs.unimportance_attrs || {}),
    },
    picture_addreses: JSON.parse(detail.picture_addreses),
    picture_34_addreses: JSON.parse(detail.picture_34_addreses),
    info: JSON.parse(detail.info),
  })
}
watchEffect(() => {
  if (props.action !== 'add') fetchInfo()
})

const activeName = ref(1)

async function checkForm() {
  return formRef.value && (await formRef.value.validate())
}
function handlePrev() {
  activeName.value--
}
async function handleNext() {
  await checkForm()
  activeName.value++
}

async function handleSubmit() {
  await checkForm()
  const params = {
    ...form,
    live_commodity_attrs: JSON.stringify({
      importance_attrs: form.live_commodity_attrs.importance_attrs.filter((item) => item.id && item.value),
      unimportance_attrs: form.live_commodity_attrs.unimportance_attrs.filter((item) => item.id && item.value),
    }),
    picture_addreses: JSON.stringify(form.picture_addreses),
    picture_34_addreses: JSON.stringify(form.picture_34_addreses),
    info: JSON.stringify(form.info),
  }
  isUpdate.value ? handleUpdate(params) : handleAdd(params)
}
// 新建
async function handleAdd(params) {
  await createProduct(params)
  ElMessage({ message: '创建成功', type: 'success' })
  router.replace({ path: '/live/product/management' })
}

// 编辑
async function handleUpdate(params) {
  await updateProduct(params)
  ElMessage({ message: '修改成功', type: 'success' })
  router.replace({ path: '/live/product/management' })
}
</script>

<template>
  <AppCard :title="title" class="product">
    <el-tabs v-model="activeName" stretch class="product-tabs">
      <el-tab-pane label="商品类目" :name="1"></el-tab-pane>
      <el-tab-pane label="基础信息" :name="2"></el-tab-pane>
      <el-tab-pane label="图文信息" :name="3"></el-tab-pane>
      <el-tab-pane label="价格库存" :name="4"></el-tab-pane>
      <el-tab-pane label="服务与履约" :name="5"></el-tab-pane>
    </el-tabs>
    <el-row justify="center" style="min-height: 400px">
      <el-col :xl="16">
        <!-- <el-card shadow="never"> -->
        <el-form label-position="top" :model="form" :disabled="action == 'view'" ref="formRef" @submit.prevent>
          <!-- 商品类目 -->
          <FormCategory v-if="activeName === 1"></FormCategory>
          <!-- 基础信息 -->
          <FormBaseInfo v-if="activeName === 2"></FormBaseInfo>
          <!-- 图文信息 -->
          <FormGraphicInfo v-if="activeName === 3"></FormGraphicInfo>
          <!-- 价格库存 -->
          <FormPrice v-if="activeName === 4"></FormPrice>
          <!-- 服务与履约 -->
          <FormService v-if="activeName === 5"></FormService>
        </el-form>
        <el-row justify="center" style="margin: 100px 0 50px">
          <el-button type="primary" plain v-if="activeName === 1" @click="$router.back()">取消</el-button>
          <el-button type="primary" plain @click="handlePrev" v-if="activeName > 1">上一步</el-button>
          <el-button type="primary" @click="handleNext" v-if="activeName < 5">下一步</el-button>
          <el-button type="primary" @click="handleSubmit" v-if="activeName === 5 && action !== 'view'">保存</el-button>
        </el-row>
        <!-- </el-card> -->
      </el-col>
    </el-row>
  </AppCard>
</template>

<style lang="scss">
.product-tabs {
  .el-tabs__header {
    width: 600px;
    margin: 0 auto 20px;
  }
  .el-tabs__nav-wrap::after {
    display: none;
  }
}
.product {
  .el-card {
    background-color: rgba(242, 242, 242, 0.49);
  }

  .form-tips {
    position: absolute;
    right: 0;
    top: -30px;
    z-index: 100;
    line-height: 22px;
    color: #92939a;
  }
}
</style>
