import { moneyFormat } from '@/helpers/utils'
import {
  Button,
  Cell,
  Dialog,
  Image,
  Loading,
  Radio,
  RadioGroup,
  Stepper,
  Tag,
  Toast
} from 'vant'
import { defineComponent, PropType } from 'vue'
import styles from './index.module.less'
import iconSellOut from '../../images/icon-sell-out.png'
import request from '@/helpers/request'
import { getCartCount } from '../../shop-mall'

export default defineComponent({
  name: 'add-goods-cart',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    item: {
      type: Object,
      default: {}
    },
    defaultRadio: {
      type: Number,
      default: 0
    },
    showType: {
      type: String,
      default: 'cart'
    },
    onGetCartCount: {
      type: Function,
      default: (n: any) => {}
    }
  },
  watch: {
    show(val) {
      // 添加购物车显示
      if (val) {
        this.totalData = {}
        this.total = 1
        this.radio = ''
        this.setList()
      }
    }
  },
  data() {
    return {
      radio: '',
      total: 1,
      totalData: {},
      skuStockList: []
    }
  },
  computed: {
    selectItem() {
      const radio = this.radio
      const select = this.skuStockList.find((n: any) => n.id == radio) as any
      if (select) {
        let stock: number = select.stock - select.lockStock //- select.cartNum
        return {
          ...select,
          stock
        }
      }
      return {
        stock: 0
      }
    }
  },
  mounted() {
    this.setList()
  },
  methods: {
    setList() {
      // 处理规格
      let skuStockList = [] as any
      const item = JSON.parse(JSON.stringify(this.item))
      if (Array.isArray(item.skuStockList)) {
        skuStockList = item.skuStockList.map((n: any) => {
          n.pic = n.pic || item.pic
          n.cartNum = 0
          if (n.spData) {
            const spData = JSON.parse(n.spData)
            let str = ''
            spData.forEach((sp: any) => {
              str += `${sp.value}`
            })
            n.spDataJson = str
          } else {
            n.spDataJson = '默认'
          }
          n.lockStock = n.lockStock > 0 ? n.lockStock : 0
          return {
            ...n
          }
        })
      }
      if (!skuStockList.length) return skuStockList
      // 处理默认显示
      let index = 0
      if (this.defaultRadio) {
        let i = skuStockList.findIndex(n => n.id == this.defaultRadio)
        index = i > -1 ? i : 0
      }
      this.radio = skuStockList[index].id
      this.skuStockList = skuStockList
      // this.getProductAddCartCount(skuStockList[index].id)
    },
    async onAddCart() {
      const selectItem = this.selectItem
      const item = this.item
      const body = {
        price: selectItem.price, //添加到购物车的价格
        productSkuId: selectItem.id,
        quantity: this.total, // 数量
        productId: item.id,
        hidden: this.showType === 'cart' ? 0 : 1,
        promoterId: this.$route.query.promoterId
          ? this.$route.query.promoterId
          : undefined
      }
      // console.log(body)
      try {
        let { code, data } = await request.post('/api-mall-portal/cart/add', {
          data: body
        })
        if (code === 200) {
          // this.getProductAddCartCount(selectItem.id, true)
          if (this.showType === 'cart') {
            this.onGetCartCount()
            this.$nextTick(() => {
              setTimeout(() => {
                Toast({
                  icon: 'success',
                  message: '添加商品成功'
                })
              }, 500)
            })
          } else {
            this.$router.push({
              path: '/cartConfirm',
              query: {
                cartIds: data.id
              }
            })
          }
          getCartCount()
        }
      } catch (error) {
        // let msg : string = (error as any).message
        // if (msg === "库存不足") {
        //   for(let i = 0; i < this.skuStockList.length; i++){
        //     if ((this.skuStockList[i] as any).id === this.selectItem.id){
        //       (this.skuStockList[i] as any).stock = 0
        //     }
        //   }
        // }
      }
    },

    // 获取购物车当前产品的数量
    async getProductAddCartCount(id?: any, isRest = false) {
      id = id ? id : this.selectItem.id
      if (this.totalData.hasOwnProperty(id) && !isRest) {
        this.setProductStock(this.totalData[id])
        return
      }
      if (!id) return
      try {
        let res = await request.get(`/api-mall-portal/product/cart/${id}`)
        this.setProductStock(res.data || 0)
        this.totalData[id] = res.data || 0
      } catch (err) {}
    },

    // 更新产品规格的库存
    setProductStock(n: number) {
      // 根据当前用户的购物车,当前产品规格的数量,限制库存
      for (let i = 0; i < this.skuStockList.length; i++) {
        if ((this.skuStockList[i] as any).id === this.radio) {
          ;(this.skuStockList[i] as any).cartNum = n
        }
      }
    }
  },
  render() {
    return (
      <div class={styles.addGoodsCart}>
        <Cell
          titleStyle={{ paddingLeft: '12px' }}
          v-slots={{
            icon: () => (
              <div class={styles.goodsSection}>
                <Image
                  src={this.selectItem.pic}
                  class={styles.goodsImg}
                  fit="cover"
                />
                {this.selectItem.stock <= 0 && (
                  <div class={styles.sellOut}>
                    <Image
                      src={iconSellOut}
                      fit="cover"
                      class={styles.sellOutImg}
                    />
                  </div>
                )}
              </div>
            ),
            title: () => (
              <div class={styles.goodsInfo}>
                <p class={styles.goodsPrice}>
                  <span>￥</span>
                  {moneyFormat(this.selectItem.price)}
                </p>
                <p class={styles.goodsStore}>库存：{this.selectItem.stock}</p>
              </div>
            )
          }}
        />
        <Cell
          v-slots={{
            title: () => <div class={styles.title}>规格</div>,
            label: () => (
              <RadioGroup class={styles['radio-group']} modelValue={this.radio}>
                {this.skuStockList.map((item: any) => {
                  const isActive = item.id === this.radio
                  const type = isActive ? 'primary' : 'default'
                  return (
                    <Radio
                      class={styles.radio}
                      name={item.id}
                      onClick={() => {
                        if (this.radio == item.id) return
                        this.radio = item.id
                        // this.getProductAddCartCount(item.id)
                      }}
                    >
                      <Tag size="large" plain={isActive} type={type}>
                        {item.spDataJson}
                      </Tag>
                    </Radio>
                  )
                })}
              </RadioGroup>
            )
          }}
        />
        <Cell
          title="购买数量"
          style={{ margin: '12px 0' }}
          border={false}
          titleClass={styles.title}
          center
        >
          <Stepper
            v-model={this.total}
            inputWidth="50px"
            theme="round"
            buttonSize="24px"
            max={this.selectItem.stock > 200 ? 200 : this.selectItem.stock}
            min={1}
            disabled={this.selectItem.stock <= 0}
            integer
          />
        </Cell>
        <div class={['btnGroup']} style={{ marginBottom: '8px' }}>
          <Button
            block
            round
            type="primary"
            text="确定"
            disabled={this.selectItem.stock <= 0}
            onClick={() => this.onAddCart()}
          />
        </div>
      </div>
    )
  }
})
