import ColHeader from '@/components/col-header'
import ColResult from '@/components/col-result'
import request from '@/helpers/request'
import { Button, Cell, CellGroup, Dialog, Image, List, Tab, Tabs } from 'vant'
import { defineComponent } from 'vue'
import styles from './index.module.less'
import { orderState } from '@/views/shop-mall/shop-mall'
import { cartConfirm } from '@/views/cart/cart'
import Item from './item'
import AfterSaleBtns from './components/after-sale-btns'

export default defineComponent({
  name: 'shop-order',
  data() {
    return {
      active: 0,
      list: [],
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      params: {
        search: '',
        groupStatus: 'APPLY',
        page: 1,
        rows: 20
      },
      page: {
        pageNum: 1,
        pageSize: 20
      }
    }
  },
  watch: {
    active(val) {
      this.init()
      this.getList()
    }
  },
  methods: {
    init() {
      this.page.pageNum = 1
      this.finished = false
      this.list = []
      this.dataShow = true
    },
    async getList() {
      if (this.loading || this.finished) {
        return
      }
      this.loading = true
      try {
        let { code, data } = await request.get('/api-mall-portal/order/list', {
          params: {
            ...this.page,
            status:
              this.active === 0 ? '0,6' : this.active === 1 ? '1,2' : '3,4'
          }
        })

        if (code === 200 && data.list) {
          this.page.pageNum += 1
          this.list = [].concat(this.list as any, data.list)
        }
        if (this.list.length >= data.total) {
          this.finished = true
        }

        if (this.list.length === 0) {
          this.dataShow = false
        }
      } catch (error) {
        this.finished = true
        this.dataShow = false
      }
      this.loading = false
    },
    onClickRight() {
      this.$router.push('/afterSale')
    },

    async cancelOrder(item: any) {
      let dialog = await Dialog.confirm({
        title: '提示',
        message: '确认取消订单?',
        confirmButtonText: '取消订单',
        confirmButtonColor: 'var(--van-primary)'
      })
      if (dialog === 'confirm') {
        let { code, data } = await request.post(
          '/api-mall-portal/order/cancelUserOrder',
          { params: { orderId: item.id } }
        )
        if (code === 200) {
          this.init()
          this.getList()
        }
      }
    },
    payOrder(item: any) {
      cartConfirm.orderInfo = item
      this.$router.push({ path: '/cartConfirmAgin' })
    },

    // 再来一单
    async onAginOrder(item: any) {
      try {
        let res = await request.post('/api-mall-portal/order/oneOrder', {
          params: {
            orderId: item.id
          }
        })
        let { code, data } = res
        if (code === 200) {
          cartConfirm.calcAmount = data.calcAmount
          cartConfirm.cartPromotionItemList = data.cartPromotionItemList
          cartConfirm.memberReceiveAddressList = data.memberReceiveAddressList
          this.$router.push({
            path: '/cartConfirm'
          })
        }
        console.log(res)
      } catch (error) {}
    },

    // 确认收货
    async onConfirmReceipt(item: any) {
      let dialog = await Dialog.confirm({
        title: '提示',
        message: '确认收货?',
        confirmButtonText: '收货',
        confirmButtonColor: 'var(--van-primary)'
      })
      if (dialog === 'confirm') {
        let res = await request.post(
          '/api-mall-portal/order/confirmReceiveOrder',
          { params: { orderId: item.id } }
        )
        if (res.code === 200) {
          this.init()
          this.getList()
        }
      }
    }
  },
  render() {
    const tabs = [
      { name: 0, title: '待支付' },
      { name: 1, title: '待收货' },
      { name: 2, title: '已完成' }
    ]

    return (
      <div class={styles.shopOrder}>
        <ColHeader
          ref="colHeader"
          class="header"
          // rightText="售后服务"
          // onClickRight={this.onClickRight}
        />
        <Tabs
          v-model:active={this.active}
          color="var(--van-primary)"
          lineWidth={28}
          animated
          swipeable
        >
          {tabs.map(tab => (
            <Tab name={tab.name} title={tab.title}>
              {this.active === tab.name && this.dataShow ? (
                <List
                  loading={this.loading}
                  finished={this.finished}
                  finishedText=" "
                  class={[styles.goodsList]}
                  onLoad={this.getList}
                >
                  {this.list.map((item: any) => (
                    <>
                      <CellGroup
                        class={styles.cellGroup}
                        border={false}
                        onClick={() => {
                          this.$router.push({
                            path: '/shopOrderDetail',
                            query: { id: item.id }
                          })
                        }}
                      >
                        <Cell
                          title={item.createTime}
                          titleClass={styles.payTime}
                          value={orderState[item.status]}
                          valueClass={
                            [0, 4, 5, 6].includes(item.status)
                              ? styles.payStatus
                              : styles.paySuccess
                          }
                        ></Cell>
                        {item.orderItemList && item.orderItemList.length
                          ? item.orderItemList.map((n: any) => (
                              <Item item={n} />
                            ))
                          : null}
                        <AfterSaleBtns
                          item={item}
                          onCancelOrder={this.cancelOrder}
                          onPayOrder={this.payOrder}
                          onConfirmReceipt={this.onConfirmReceipt}
                          onAginOrder={this.onAginOrder}
                        />
                      </CellGroup>
                    </>
                  ))}
                </List>
              ) : (
                <ColResult
                  btnStatus={false}
                  classImgSize="SMALL"
                  tips="暂无订单"
                />
              )}
            </Tab>
          ))}
        </Tabs>
      </div>
    )
  }
})
