import ColHeader from '@/components/col-header'
import ColResult from '@/components/col-result'
import request from '@/helpers/request'
import { state } from '@/state'
import {
  ActionSheet,
  Button,
  Cell,
  CellGroup,
  Dialog,
  Field,
  Image,
  List,
  Tab,
  Tabs,
  Toast
} from 'vant'
import { defineComponent } from 'vue'
import Item from './item'
import styles from './index.module.less'

const returnState = {
  0: '待处理',
  1: '退货中',
  2: '已完成',
  3: '已拒绝'
}
type good = {
  description: string
  memberUsername: string
  orderId: number
  orderSn: string
  productAttr: string
  productBrand: string
  productCount: number
  productId: number
  productName: string
  productPic: string
  productPrice: number
  productRealPrice: number
  proofPics: string
  returnName: string
  returnPhone: string
  orderItemId: string
}

export default defineComponent({
  name: 'after-sale',
  data() {
    return {
      active: '0',
      list: [],
      dataShow: false, // 判断是否有数据
      loading: false,
      finished: false,
      show: false,
      kmsShow: false,
      params: {
        pageNum: 1,
        pageSize: 20
      },

      returnGood: {} as good,
      reason: '', // 退货原因
      returnOrderSn: '', // 退货快递单号
      returnGoodId: 0 // 退货申请服务单号
    }
  },
  watch: {
    active() {
      this.init()
      this.getList()
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    init() {
      this.params.pageNum = 1
      this.finished = false
      this.list = []
    },

    async getList() {
      //避免重复请求
      console.log(this.loading, this.finished)
      if (this.loading && this.finished) {
        return
      }
      this.loading = true
      let res: any
      if (this.active === '0') {
        // 可退货列表
        res = await this.getIsReturnOrderList()
      } else {
        // 退货申请列表
        res = await this.getReturnList()
      }
      if (res && res.code === 200 && res.data.list) {
        let data = res.data
        if (Array.isArray(data.list)) {
          let list = [] as any
          // 过滤一个订单里面所有商品都申请了退货
          for (let i = 0; i < data.list.length; i++) {
            if (data.list[i].orderItemList) {
              let isHave =
                data.list[i].orderItemList.findIndex(n => n.returnStatus < 0) >
                -1
              if (isHave) {
                list.push(data.list[i])
              }
            } else {
              list.push(data.list[i])
            }
          }
          this.list = this.list.concat(this.list, list)
        }
        // this.list = [].concat(this.list, res.data.list)

        this.params.pageNum = res.data.pageNum + 1
      }
      this.finished = this.params.pageNum >= res?.data?.totalPage
      this.loading = false
    },

    //获取可退货列表
    async getIsReturnOrderList(): Promise<object> {
      try {
        let res = await request.get('/api-mall-portal/order/list', {
          params: {
            ...this.params,
            status: '1,2,3'
          }
        })
        return res
      } catch (error) {}
      return {}
    },

    // 获取退货申请
    async getReturnList(): Promise<object> {
      try {
        let res = await request.post('/api-mall-portal/returnApply/list', {
          data: {
            ...this.params,
            status: this.active === '1' ? '0,1' : '2,3'
          }
        })
        return res
      } catch (error) {}
      return {}
    },

    // 设置退货参数
    setReturnParams(item: any, n: any): void {
      this.returnGood.memberUsername = state.user.data.username
      this.returnGood.orderId = item.id
      this.returnGood.orderSn = item.orderSn
      this.returnGood.productAttr = n.productAttr
      this.returnGood.productBrand = n.productBrand
      this.returnGood.productCount = n.productQuantity
      this.returnGood.productId = n.productId
      this.returnGood.productName = n.productName
      this.returnGood.productPic = n.productPic
      this.returnGood.productPrice = n.productPrice
      this.returnGood.productRealPrice = n.productPrice
      this.returnGood.proofPics = ''
      this.returnGood.returnName = item.receiverName
      this.returnGood.returnPhone = item.receiverPhone
      this.returnGood.orderItemId = n.id
      console.log(this.returnGood)
    },
    // 退商品
    async setReturnShop(): Promise<void> {
      if (!this.reason) {
        Toast('请填写退货原因!')
        return
      }
      try {
        let res = await request.post('/api-mall-portal/returnApply/create', {
          data: {
            ...this.returnGood,
            reason: this.reason
          }
        })
        if (res.code === 200) {
          Toast({
            message: '退货申请成功',
            icon: 'success'
          })
          setTimeout(() => {
            this.show = false
            this.reason = ''
            this.returnOrderSn = ''
            this.active = '1'
          }, 500)
        }
      } catch (error) {}
      this.returnGood = {} as good
    },

    // 填写快递单号
    async setReturnApplySn(): Promise<void> {
      if (!this.returnOrderSn) {
        Toast('请填写退货快递单号')
        return
      }

      try {
        let { code, data } = await request.post(
          '/api-mall-portal/returnApply/deliverySn',
          {
            data: {
              deliverySn: this.returnOrderSn,
              id: this.returnGoodId
            }
          }
        )
        if (code === 200) {
          this.returnOrderSn = ''
          this.kmsShow = false
          this.init()
          this.getList()
        }
      } catch (error) {}
    },
    //撤销申请
    deleteReturnApply(): void {
      Dialog.confirm({
        title: '提示',
        message: '是否撤销退货申请?',
        confirmButtonText: '撤销',
        confirmButtonColor: 'var(--van-primary)'
      }).then(async () => {
        try {
          let { code, data } = await request.post(
            '/api-mall-portal/returnApply/delete/' + this.returnGoodId
          )
          if (code === 200) {
            this.init()
            this.getList()
          }
        } catch (err) {}
      })
    }
  },
  render() {
    const tabs = [
      { name: '0', title: '全部' },
      { name: '1', title: '处理中' },
      { name: '2', title: '已处理' }
    ]
    return (
      <div class={styles.shopOrder}>
        <ColHeader />

        <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.list.length ? (
                <List
                  loading={this.loading}
                  finished={this.finished}
                  finishedText=" "
                  class={[styles.goodsList]}
                  onLoad={this.getList}
                >
                  {this.active === tab.name &&
                    this.list.map((item: any) => (
                      <>
                        {item.orderItemList && item.orderItemList.length ? (
                          item.orderItemList.map((n: any) => (
                            <CellGroup class={styles.cellGroup}>
                              <Item item={n} />
                              <Cell
                                center
                                v-slots={{
                                  default: () => (
                                    <div class={styles.btnList}>
                                      {this.active === '0' &&
                                      n.returnStatus < 0 && (item.status == 3 ? (item.afterSale == 0) : true) ? (
                                        <Button
                                          size="small"
                                          round
                                          type="primary"
                                          onClick={() => {
                                            this.show = true
                                            this.setReturnParams(item, n)
                                          }}
                                        >
                                          退货申请
                                        </Button>
                                      ) : null}
                                      {n.returnStatus >= 0 ? (
                                        <div>{returnState[n.returnStatus]}</div>
                                      ) : null}
                                    </div>
                                  )
                                }}
                              ></Cell>
                            </CellGroup>
                          ))
                        ) : (
                          <CellGroup class={styles.cellGroup}>
                            <Cell
                              title={item.createTime}
                              titleClass={styles.payTime}
                              value={returnState[item.status]}
                              // valueClass={}
                            ></Cell>
                            <Item item={item} />
                            <Cell
                              center
                              v-slots={{
                                default: () => (
                                  <div class={styles.btnList}>
                                    {item.status === 1 && !item.deliverySn ? (
                                      <Button
                                        size="small"
                                        round
                                        onClick={() => {
                                          this.returnGoodId = item.id
                                          this.kmsShow = true
                                        }}
                                      >
                                        填写退货快递单号
                                      </Button>
                                    ) : null}
                                    {item.status <= 1 ? (
                                      <Button
                                        size="small"
                                        round
                                        type="primary"
                                        onClick={() => {
                                          this.returnGoodId = item.id
                                          this.deleteReturnApply()
                                        }}
                                      >
                                        撤销申请
                                      </Button>
                                    ) : null}
                                    {item.status === 2 ? (
                                      <div class={styles.returnDes}>
                                        该商品金额已于 {item.handleTime}{' '}
                                        原路退还
                                      </div>
                                    ) : item.status === 3 ? (
                                      <div class={styles.returnDes}>
                                        拒绝原因: {item.handleNote}
                                      </div>
                                    ) : null}
                                  </div>
                                )
                              }}
                            ></Cell>
                          </CellGroup>
                        )}
                      </>
                    ))}
                </List>
              ) : (
                <ColResult
                  btnStatus={false}
                  classImgSize="SMALL"
                  tips="暂无数据"
                />
              )}
            </Tab>
          ))}
        </Tabs>

        <ActionSheet v-model:show={this.show} title="退货原因">
          <div style={{ paddingTop: '15px' }}>
            <Field
              class={[styles.field]}
              placeholder="请输入退货原因"
              type="textarea"
              rows={3}
              v-model={this.reason}
            />
          </div>
          <div class={styles['btn-group']}>
            <Button
              type="primary"
              block
              round
              onClick={() => this.setReturnShop()}
            >
              确定
            </Button>
          </div>
        </ActionSheet>
        <ActionSheet v-model:show={this.kmsShow} title="填写退货快递单号">
          <Field
            v-model={this.returnOrderSn}
            class={[styles.field]}
            placeholder="请输入退货快递单号"
          />
          <div class={styles['btn-group']}>
            <Button
              type="primary"
              block
              round
              onClick={() => this.setReturnApplySn()}
            >
              确定
            </Button>
          </div>
        </ActionSheet>
      </div>
    )
  }
})
