import { defineComponent, ref } from 'vue'
import ColHeader from '@/components/col-header'
import styles from './index.module.less'
import { Checkbox, SubmitBar, Card, Stepper, CheckboxGroup } from 'vant'
import request from '@/helpers/request'
import { cartConfirm } from './cart'
import ColResult from '@/components/col-result'
import { moneyFormat } from '@/helpers/utils'

export default defineComponent({
  name: 'cart',
  data() {
    return {
      dataShow: false,
      isManage: false,
      cartList: [],
      selectItems: []
    }
  },
  computed: {
    checkAll() {
      let selectLen = this.selectItems.length as any
      let cartLen = this.cartList.length as any
      return selectLen === cartLen
    },
    len() {
      let n = this.selectItems.length as any
      return n
    },
    totalPrice() {
      let price = 0
      const items = this.selectItems as any
      this.cartList.forEach((n: any) => {
        if (items.includes(n.id) && typeof n.price === 'number') {
          price += n.price * n.quantity
        }
      })
      return price * 100
    }
  },
  mounted() {
    this.getCartList()
  },
  methods: {
    async getCartList() {
      this.cartList = []
      try {
        let { code, data } = await request.get('/api-mall-portal/cart/list')
        code === 200 && (this.cartList = data)
      } catch (err) {}
      this.dataShow = true
    },
    setCheckAll() {
      const selectItems = [] as any
      if (!this.checkAll) {
        this.cartList.forEach((n: any) => {
          selectItems.push(n.id)
        })
      }
      this.selectItems = selectItems
    },

    async setCartItem(item: any) {
      try {
        let { code, data } = await request.get(
          '/api-mall-portal/cart/update/quantity',
          {
            params: {
              id: item.id,
              quantity: item.quantity
            },

            hideLoading: true
          }
        )
      } catch (err) {}
    },

    onChecked(id: number) {
      const items = this.selectItems as number[]
      if (items.includes(id)) {
        items.splice(items.indexOf(id), 1)
      } else {
        items.push(id)
      }
      this.selectItems = items as []
    },

    async onDeleteCartItem() {
      const ids = this.selectItems.join(',')
      try {
        let { code, data } = await request.post(
          '/api-mall-portal/cart/delete?ids=' + ids
        )
        if (code === 200) {
          this.getCartList()
          this.selectItems = []
          this.isManage = false
        }
      } catch (error) {}
    },
    //生成确认订单
    async generateConfirmOrder() {
      const ids: number[] = [...this.selectItems]
      try {
        let { code, data } = await request.post(
          '/api-mall-portal/order/generateConfirmOrder',
          {
            params: {
              cartIds: ids.join(',')
            }
          }
        )
        if (code === 200) {
          cartConfirm.calcAmount = data.calcAmount
          cartConfirm.cartPromotionItemList = data.cartPromotionItemList
          cartConfirm.memberReceiveAddressList = data.memberReceiveAddressList
          // alert(JSON.stringify(data.memberReceiveAddressList))
          this.$router.push({
            path: '/cartConfirm'
          })
        }
      } catch (error) {}
    },
    gotoShopMall() {
      this.$router.push({
        path: '/shopMall'
      })
    }
  },
  render() {
    return (
      <>
        {this.dataShow ? (
          <div>
            {!this.cartList.length ? (
              <ColResult
                tips="购物车空空如也"
                buttonText="去商城逛逛"
                onClick={() => this.gotoShopMall()}
              ></ColResult>
            ) : (
              <>
                <ColHeader
                  onClickRight={() => (this.isManage = !this.isManage)}
                  v-slots={{
                    right: () => (
                      <span style={{ color: '#333', fontSize: '14px' }}>
                        {this.isManage ? '完成' : '管理'}
                      </span>
                    )
                  }}
                ></ColHeader>
                <div class={styles.cartBox}>
                  <CheckboxGroup v-model={this.selectItems}>
                    {this.cartList.map((item: any) => (
                      <div class={styles.cartItem}>
                        <Checkbox name={item.id}>
                          <Card
                            price={moneyFormat(item.price)}
                            desc={item.productAttr}
                            title={item.productName}
                            thumb={item.productPic}
                            v-slots={{
                              num: () => (
                                <Stepper
                                  v-model={item.quantity}
                                  onClick={e => {
                                    e.stopPropagation()
                                  }}
                                  onChange={() => this.setCartItem(item)}
                                  inputWidth="50px"
                                  buttonSize="24px"
                                  min={1}
                                />
                              )
                            }}
                          ></Card>
                        </Checkbox>
                      </div>
                    ))}
                  </CheckboxGroup>
                  <div style={{ height: 'var(--van-submit-bar-height)' }}></div>

                  {this.isManage ? (
                    <div class={styles.delete}>
                      <SubmitBar
                        buttonText="删除"
                        buttonColor="var(--van-primary)"
                        disabled={this.totalPrice === 0}
                        onSubmit={() => this.onDeleteCartItem()}
                      >
                        <Checkbox
                          modelValue={this.checkAll}
                          onClick={value => this.setCheckAll()}
                        >
                          全选
                        </Checkbox>
                      </SubmitBar>
                    </div>
                  ) : (
                    <div class={styles.submit}>
                      <SubmitBar
                        price={this.totalPrice}
                        buttonText={`结算(${this.len})`}
                        buttonColor="var(--van-primary)"
                        disabled={this.totalPrice === 0}
                        onSubmit={() => this.generateConfirmOrder()}
                      >
                        <Checkbox
                          modelValue={this.checkAll}
                          onClick={value => this.setCheckAll()}
                        >
                          全选
                        </Checkbox>
                      </SubmitBar>
                    </div>
                  )}
                </div>
              </>
            )}
          </div>
        ) : null}
      </>
    )
  }
})
