<template>
  <avue-form :option="option" v-model="form" @submit="onSubmit">
    <template slot="goodsTypeList">
      <el-transfer v-model="form.goodsTypeList" filterable :data="categories_selections"
        :titles="['备选项', '已选项']"></el-transfer>
    </template>
  </avue-form>
</template>

<script lang="ts">
import Vue from 'vue'
import httpx, { AxiosResponse } from '@/utils/httpx'
import formOption from "@/avue/form/prodinfo"
import { ICategory, IProdInfo } from '@/utils/vo'
import { isInteger } from 'lodash'
import { database2real, real2database } from "@/utils/currency"

interface ISelection {
  key: number,
  label: string,
  disabled?: boolean
  hidden?: boolean
}

interface ICategoryProdRelation {
  goodsId: number
  goodsTypeId: number
}

export default Vue.extend({
  data() {
    return {
      form: {
        name: "",
        desc: "",
        price: 0,
        deliverPrice: 0,
        stockAmount: 0,
        // soldAmount: 0,
        cover: [],
        kind: "",
        platform: "",
        link: "",
        needAddr: true,
        goodsTypeList: [],
        adminId: 0,
        title: "新增商品",
      } as IProdInfo,
      option: formOption,
      categories: [] as ICategory[],
      new: false,
      id: 0,
    }
  },
  mounted() {
    this.getCategoryList("")
    const id_str = this.$route.params.id
    const id = parseInt(id_str)
    if (isNaN(id) || !isInteger(id)) {
      if (id_str === "new") {
        this.new = true
      } else {
        this.notFound()
      }
    } else {
      this.new = false
      this.id = id
      this.form.title = '修改商品'
      this.getProductInfo(id)
    }
  },

  methods: {
    getProductInfo(id: number) {
      return httpx.post(
        httpx.makeurl("/goods/editGood"),
        id
      ).then(({ data }) => {
        if ((data?.goodList?.length || 0) === 0) {
          this.notFound()
        }
        const item = data.goodList[0]
        const categories_raw: ICategoryProdRelation[] = data?.goodsGoodsTypesEntityList || []
        const categories = categories_raw.map(v => v.goodsTypeId)
        this.form = {
          name: item.name,
          desc: item.desc,
          price: database2real(item.price),  // 数据库内单位为分
          deliverPrice: database2real(item.deliverPrice),  // 数据库内单位为分
          stockAmount: item.stockAmount,
          // soldAmount: item.soldAmount,
          platform: item.platform,
          cover: [item.cover],
          kind: item.kind,
          link: item.link,
          needAddr: item.needAddr,
          goodsTypeList: categories,
          adminId: item.adminId,
          title: `修改商品 ${item.name}`,
        }
      })
    },
    getCategoryList(name: string = "") {
      return httpx.post(httpx.makeurl("/goodsTypes/queryGoodsTypeList"), {
        name: name, limit: 1000, page: 1
      }).then(({ data }: AxiosResponse<{ goodsTypeList: ICategory[], total: number }>) => {
        this.categories = data.goodsTypeList
      })
    },
    onSubmit(form: IProdInfo, done: Function) {
      console.log(form)
      const path = this.new ? "/goods/addGood" : "/goods/updateGood"
      const id_form: { id?: number } = this.new ? {} : { id: this.id }
      const data = Object.assign(form, id_form)
      data.price = real2database(data.price)
      data.deliverPrice = real2database(data.deliverPrice)
      // @ts-ignore
      data.cover = data.cover[0] || ""
      // @ts-ignore
      delete data.title;

      console.log(data)

      httpx.post(path, data).then((data) => {
        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 1500
        })
        this.$router.back()
      })
      done()
    },
    notFound() {
      this.$router.replace("/404")
    }
  },

  computed: {
    categories_selections(): ISelection[] {
      return this.categories.map((v, i) => {
        return {
          key: v.id,
          label: v.name,
        }
      })
    }
  },
})
</script>