import { defineComponent, onMounted, reactive } from 'vue'
import {
  List,
  Popup,
  Icon,
  Tabs,
  Tab,
  DatetimePicker,
  CellGroup,
  Button,
  Dialog,
  Cell,
  Image
} from 'vant'
import Search from '@/components/col-search'
import request from '@/helpers/request'
import iconMember from '@common/images/icon_member.png'
// import Item from './item'

import { useRouter } from 'vue-router'
import ColResult from '@/components/col-result'
import styles from './index.module.less'
import ColHeader from '@/components/col-header'
import bgImg from '../images/bg-image-1.png'
import { dateFormat, formatterDate, moneyFormat } from '@/helpers/utils'
import TheSticky from '@/components/the-sticky'
import { tradeOrder } from './tradeOrder'
import dayjs from 'dayjs'
import { goodsType, orderType } from '@/constant'

export default defineComponent({
  name: 'MusicList',
  setup() {
    const router = useRouter()
    const state = reactive({
      actions: [
        { name: '待支付', status: 'WAIT_PAY' },
        { name: '支付中', status: 'PAYING' },
        { name: '已付款', status: 'PAID' },
        { name: '已关闭', status: 'CLOSE' },
        // { name: '已退费', status: 'REFUND' },
        { name: '支付失败', status: 'FAIL' }
      ],
      timeStatus: false,
      currentSearchDate: new Date(),
      currentDate: new Date(),
      list: [],
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      searchName: '全部',
      params: {
        status: '',
        keyword: '',
        page: 1,
        rows: 20
      },
      type: 'buy'
    })
    const getList = async () => {
      if (state.loading) return
      state.loading = true
      try {
        const params = {
          ...state.params,
          searchDate: dayjs(state.currentSearchDate).format('YYYY-MM')
        }

        const url =
          state.type === 'buy'
            ? '/api-student/userOrder/page'
            : '/api-student/userOrderRefunds/page'
        const { code, data } = await request.post(url, {
          data: {
            ...params,
            dateTime: state.type === 'refund' ? params.searchDate : undefined,
            timeType: state.type === 'refund' ? 'MONTH' : undefined
          }
        })
        if (code === 200) {
          const result = data || {}
          result.rows?.forEach((item: any) => {
            const orderDetails = item.orderDetailList || []
            orderDetails.forEach((item: any) => {
              const bizContent = item.bizContent
                ? JSON.parse(item.bizContent)
                : {}
              if (bizContent && bizContent.purchaseType) {
                const template = {
                  MONTH: 1,
                  QUARTERLY: 3,
                  YEAR_HALF: 6,
                  YEAR: 12
                }
                if (bizContent.purchaseType === 'DAY') {
                  item.unit = '天'
                } else {
                  item.unit = '个月'
                  item.bizInfo.bizValidTime =
                    item.bizInfo.bizValidTime *
                    template[bizContent.purchaseType]
                }
              } else {
                item.unit = '个月'
              }
            })
          })
          state.list = state.list.concat(result.rows || [])
          state.finished = result.pageNo >= result.totalPage
          state.params.page = result.pageNo + 1
          state.dataShow = state.list.length > 0
        }
      } catch {
        state.dataShow = false
        state.finished = true
      }
      state.loading = false
    }
    const onDetail = (item: any) => {
      if (state.type === 'refund') return
      router.push({
        path: '/goodsDetail',
        query: {
          orderNo: item.orderNo,
          path: 'tradeRecord'
        }
      })
    }
    const onConfirm = (date: Date) => {
      state.currentDate = date
      state.currentSearchDate = date
      state.timeStatus = false
      onSearch()
    }
    const onSearch = (val?: any) => {
      state.dataShow = true
      state.loading = false
      state.finished = false
      state.list = []
      state.params.page = 1
      state.params.keyword = val
      getList()
    }
    const onCancelPay = async (item: any) => {
      Dialog.confirm({
        message: '是否取消订单？',
        confirmButtonText: '确定',
        confirmButtonColor: 'var(--van-primary)',
        cancelButtonText: '取消'
      }).then(async () => {
        try {
          await request.post('/api-student/userOrder/orderCancel', {
            data: {
              orderNo: item.orderNo
            }
          })
          // Toast('取消成功')
          onSearch()
        } catch {
          //
        }
      })
    }
    const onPay = async (item: any) => {
      try {
        const res = await request.get(
          `/api-student/userOrder/detailByOrderNo/${item.orderNo}`
        )
        const result = res.data
        tradeOrder({ ...result, paymentConfig: item.paymentConfig }, () => {
          router.push({
            path: '/orderDetail',
            query: {
              orderType: result.orderType
            }
          })
        })
      } catch {
        //
      }
    }

    onMounted(() => {
      getList()
    })
    return () => (
      <>
        <div class={styles.sticky}>
          <TheSticky>
            <ColHeader
              background="transparent"
              isFixed={false}
              border={false}
              color="#131415"
            />
            <Search
              onSearch={onSearch}
              type="tenant"
              background="transparent"
              inputBackground="transparent"
              v-slots={{
                left: () => (
                  <div
                    class={styles.label}
                    onClick={() => (state.timeStatus = true)}
                  >
                    {dateFormat(state.currentSearchDate, 'YYYY-MM')}

                    <Icon
                      classPrefix="iconfont"
                      name="down"
                      size={12}
                      color="#948D93"
                    />
                  </div>
                )
              }}
            />
            <Tabs
              color="var(--van-primary)"
              background="transparent"
              lineWidth={20}
              shrink
              class={styles.tagTabs}
              onClick-tab={(obj: any) => {
                state.type = obj.name === 'REFUND' ? 'refund' : 'buy'
                state.params.status = obj.name
                onSearch()
              }}
            >
              <Tab title="全部" name=""></Tab>
              {state.actions.map((tag: any) => (
                <Tab title={tag.name} name={tag.status}></Tab>
              ))}
            </Tabs>
          </TheSticky>
          <img class={styles.bgImg} src={bgImg} />
        </div>
        <div class={styles.tradeList}>
          {state.dataShow ? (
            <List
              // loading={state.loading}
              finished={state.finished}
              finishedText=" "
              class={[styles.list]}
              onLoad={getList}
            >
              {state.list.map((item: any) => (
                <CellGroup
                  border={false}
                  onClick={() => {
                    onDetail(item)
                  }}
                >
                  <Cell
                    border={false}
                    title={dayjs(item.createTime).format('YYYY-MM-DD HH:mm')}
                    value={
                      state.type === 'buy'
                        ? orderType[item.status]
                        : item.operateReason
                    }
                    valueClass={styles.tradeType}
                  />
                  {item.orderDetailList &&
                    item.orderDetailList.map((orderDetail: any) => (
                      <Cell
                        border={false}
                        class={styles.orderSection}
                        v-slots={{
                          icon: () => (
                            <Image
                              src={
                                orderDetail.goodType === 'VIP'
                                  ? iconMember
                                  : orderDetail.bizInfo?.bizCover
                              }
                              class={styles.tradeLogo}
                            />
                          ),
                          title: () => (
                            <div class={styles.goodsSection}>
                              <div class={[styles.title]}>
                                <span class={[styles.name, 'van-ellipsis']}>
                                  {orderDetail.bizInfo?.bizName}
                                </span>
                                <span class={styles.desc}>
                                  ¥{moneyFormat(orderDetail.actualPrice)}
                                </span>
                              </div>

                              <div class={styles.description}>
                                <span class={[styles.d, 'van-ellipsis']}>
                                  {orderDetail.bizInfo?.bizDesc}
                                </span>
                                {orderDetail.goodType !== 'VIP' && (
                                  <>
                                    {orderDetail.goodType === 'TENANT_ALBUM' ? (
                                      <span class={styles.t}>
                                        x{orderDetail.bizInfo?.bizValidTime}
                                        {orderDetail.unit}
                                      </span>
                                    ) : (
                                      <span class={styles.t}>永久</span>
                                    )}
                                  </>
                                )}
                              </div>

                              {/* {orderDetail.bizInfo?.bizMusicCount > 0 && (
                                <span class={styles.songLength}>
                                  共{orderDetail.bizInfo?.bizMusicCount}首
                                </span>
                              )} */}
                            </div>
                          )
                        }}
                      />
                    ))}

                  <div class={styles.paymentPrice}>
                    {['PAYING', 'WAIT_PAY'].includes(item.status)
                      ? '需付款'
                      : item.status === 'CLOSE'
                      ? '订单金额'
                      : '实付款'}
                    <span>
                      <i>¥</i>
                      {moneyFormat(item.actualPrice)}
                    </span>
                  </div>
                  {item.status === 'PAYING' || item.status === 'WAIT_PAY' ? (
                    <div class={styles.btnList}>
                      <Button
                        size="small"
                        round
                        onClick={(e: any) => {
                          e.stopPropagation()
                          onCancelPay(item)
                        }}
                      >
                        取消订单
                      </Button>
                      <Button
                        size="small"
                        round
                        type="primary"
                        onClick={(e: any) => {
                          e.stopPropagation()
                          onPay(item)
                        }}
                      >
                        继续付款
                      </Button>
                    </div>
                  ) : null}
                </CellGroup>
              ))}
            </List>
          ) : (
            <ColResult
              btnStatus={false}
              classImgSize="CERT"
              tips={state.type === 'buy' ? '暂无购买记录' : '暂无退款记录'}
            />
          )}
        </div>

        <Popup
          v-model:show={state.timeStatus}
          position="bottom"
          round
          closeOnPopstate
        >
          <DatetimePicker
            type="year-month"
            v-model={state.currentDate}
            formatter={formatterDate}
            onCancel={() => {
              state.timeStatus = false
            }}
            onConfirm={onConfirm}
          />
        </Popup>
      </>
    )
  }
})
