<route lang="json5">
{ layout: 'tabbar', style: { navigationBarTitleText: '我的', navigationStyle: 'custom' } }
</route>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import {
  getOrders,
  getVendorAppInfo,
  getYearTarget,
  getDesignerStatistics,
  getFollowStatistics,
  getBroker,
} from '../../core/libs/requests'

import { storeToRefs } from 'pinia'
import SectionHeading from '@designer-hub/app/src/components/section-heading.vue'
import Card from '@designer-hub/app/src/components/card.vue'
import { desinTopBg } from '@designer-hub/assets/src/svgs'
import NavBarEvo from '@designer-hub/app/src/components/navbar-evo.vue'
import dayjs from 'dayjs'
import PageHelper from '../../components/page-helper.vue'
import { useUserStore } from '@/store'
import AgentMine from './components/agent-mine.vue'
import PageHelperEvo from '@/components/page-helper-evo.vue'
import { ComponentExposed } from 'vue-component-type-helpers'
import type { CalendarInstance } from 'wot-design-uni/components/wd-calendar/types'

const calendar = ref<CalendarInstance>()
const pageHelperRef = ref<ComponentExposed<typeof PageHelperEvo>>()
const userStore = useUserStore()
const publishState = ref(false)
const { isLogined, userInfo, isMerchant, isAgent } = storeToRefs(userStore)
const { data, run: setData } = useRequest(() => getVendorAppInfo())
const { data: orders, run: setOrders } = useRequest(() => getOrders({}))
const { data: yearTarget, run: setYearTarget } = useRequest(() => getYearTarget())
const { data: designerData, run: setdesignerData } = useRequest(() => getDesignerStatistics())
const { data: followData, run: setFollowData } = useRequest(() => getFollowStatistics())
const { data: agent, run: setAgent } = useRequest(() =>
  getBroker({ brokerId: String(userInfo.value.userId) }),
)

const status = ref<any>({
  '0': '已报名',
  '1': '已完成',
  '2': '未核销',
  '3': '已取消',
  '4': '待交付',
})
const verifyTime = ref<Date[] | number[]>([])
const filterQuery = ref<{
  orderStatus?: number | null
  dateTimeType?: number
  verifyTime?: string
}>({
  orderStatus: null,
  dateTimeType: 1,
  verifyTime: '',
})
const query = ref({})
const toInfoSeting = () => {
  uni.navigateTo({ url: '/pages/mine/merchant/merchant_settings' })
}
const openCalendar = () => {
  console.log('打开日历')
  calendar.value?.open()
}
const toOrder = (order: any) => {
  uni.navigateTo({ url: `/pages/mine/merchant/orders/detail/index?id=${order.id}` })
}
const handleSubmit = async () => {
  console.log('时间 查询')
  query.value = { ...filterQuery.value, pageNo: 1, pageSize: -1 }
  await pageHelperRef.value?.refresh()
  publishState.value = false
}
const transformState = () => {
  publishState.value = true
}
const radioChange = (value: number) => {
  if (value !== 4) {
    filterQuery.value.verifyTime = ''
    verifyTime.value = []
  } else {
    verifyTime.value = [new Date().getTime(), new Date().getTime()]
  }
}
function handleConfirm({ value }) {
  verifyTime.value = value
  if (value.length) {
    filterQuery.value.verifyTime = `${dayjs(value[0]).format('YYYY-MM-DD hh:mm:ss')},${dayjs(value[1]).format('YYYY-MM-DD hh:mm:ss')}`
    console.log(filterQuery.value.verifyTime)
  } else {
    filterQuery.value.verifyTime = ''
  }
}
onShow(async () => {
  if (isLogined.value && isMerchant?.value) {
    await setData()
    await setOrders()
	await pageHelperRef.value?.refresh()
  }

  if (isLogined.value && isAgent?.value) {
    await setAgent()
    await Promise.all([setYearTarget(), setdesignerData(), setFollowData()])
  }
})
onMounted(async () => {})
const navBarProps = ref({ customClass: 'bg-transparent!' })
onPageScroll(({ scrollTop }: { scrollTop: number }) => {
  console.log(scrollTop)
  navBarProps.value.customClass = scrollTop === 0 ? 'bg-transparent!' : ''
})
</script>

<template>
  <view>
    <NavBarEvo title="我的" transparent dark placeholder></NavBarEvo>
    <template v-if="isAgent">
      <AgentMine></AgentMine>
    </template>

    <template v-if="isMerchant">
      <view class="p-[16px]">
        <div class="aspect-[1.575/1] absolute left-0 right-0 top-0">
          <wd-img width="100%" height="100%" :src="desinTopBg" custom-class="vertical-top"></wd-img>
        </div>
        <div
          @click="toInfoSeting"
          class="bg-white rounded-2xl shadow relative mt-[28px] py-[29px] px-[14px] flex items-center"
        >
          <div>
            <wd-img width="64" height="64" round :src="data?.avatar" />
          </div>
          <div class="ml-[10px]">
            <div
              class="text-black/90 text-lg font-normal font-['PingFang_SC'] leading-[10.18px]"
              style="margin-top: -5px"
            >
              商家：{{ data?.vendorName }}
            </div>
            <!--            <div-->
            <!--              class="h-6 px-1.5 py-1 bg-[#f5f6fa] rounded justify-center items-center gap-2.5 inline-flex mt-[17px]"-->
            <!--            >-->
            <!--              <div class="text-[#8b8b8b] text-xs font-normal font-['PingFang_SC'] leading-none">-->
            <!--                {{ data?.id }}-->
            <!--              </div>-->
            <!--            </div>-->
          </div>
        </div>
        <div class="flex items-center mt-[20px]">
          <div class="w-1 h-[19px] bg-[#2357e9] rounded-md"></div>
          <div
            class="text-black w-[100%] flex justify-between text-lg font-normal font-['PingFang_SC'] leading-normal ml-[8px]"
          >
            <div>记录</div>
            <div class="flex justify-end items-center font-['PingFang_SC']" @click="transformState">
              <div class="text-sm font-normal">
                {{ dayjs().format('YYYY-MM-DD') }}
              </div>
              <wd-icon name="fill-arrow-down" size="22px"></wd-icon>
            </div>
          </div>
        </div>
        <div class="mt-[16px]">
          <PageHelperEvo ref="pageHelperRef" :request="getOrders" :query="query">
            <template #default="{ source }">
              <div class="flex flex-col gap-4">
                <template v-for="(it, i) in source?.list" :key="i">
                  <Card custom-class="py-4">
                    <div class="bg-white rounded-2xl flex flex-col" @click="toOrder(it)">
                      <div class="flex items-center justify-between">
                        <div
                          class="text-black/90 text-sm font-normal font-['PingFang_SC'] leading-normal"
                        >
                          支付时间：
                          {{ dayjs(it.completeTime).format('YYYY-MM-DD HH:mm') }}
                        </div>
                        <div
                          class="text-xs font-normal font-['PingFang_SC'] leading-normal"
                          :class="
                            ['2', '4'].includes(it.orderStatus) ? 'text-[#ff2d2d]' : 'text-black/30'
                          "
                        >
                          {{ status[it.orderStatus] }}
                        </div>
                      </div>

                      <div class="flex mt-[19px] items-center">
                        <div class="w-[86px] h-[86px] bg-[#f6f6f6] rounded-[10px] overflow-hidden">
                          <wd-img
                            width="86"
                            height="86"
                            custom-class="vertical-bottom bg-[#f6f6f6]"
                            :src="it.orderImgUrl"
                          ></wd-img>
                        </div>
                        <div class="ml-[16px] flex-1">
                          <div
                            class="text-black text-base font-normal font-['PingFang_SC'] leading-normal"
                          >
                            {{ it.projectName }}
                          </div>
                          <div
                            class="text-left text-black/30 text-sm font-normal font-['PingFang_SC'] leading-normal"
                          >
                            数量x{{ it.orderQuantity }}
                          </div>
                          <div
                            class="text-left text-black/30 text-sm font-normal font-['PingFang_SC'] leading-normal"
                          >
                            {{ it.points }}积分
                          </div>
                        </div>
                      </div>
                    </div>
                  </Card>
                </template>
              </div>
            </template>
          </PageHelperEvo>
        </div>
      </view>
      <wd-action-sheet v-model="publishState" @close="publishState = false">
        <view class="flex flex-col p-4 overflow-y-auto">
          <SectionHeading custom-class="mb-[10px]" title="交易时间"></SectionHeading>
          <wd-radio-group
            cell
            shape="button"
            v-model="filterQuery.dateTimeType"
            @change="radioChange"
          >
            <template
              v-for="(tag, index) in [
                { label: '本月', value: 1 },
                { label: '上月', value: 2 },
                { label: '近三月', value: 3 },
                { label: '自定义', value: 4 },
              ]"
              :key="index"
            >
              <wd-radio :value="tag.value">
                {{ tag.label }}
              </wd-radio>
            </template>
          </wd-radio-group>
          <SectionHeading custom-class="my-[10px]" title="自定义"></SectionHeading>
          <div class="text-[#999] text-xs text-center child-value mt-[10px]" @click="openCalendar">
            <text :class="[verifyTime[0] ? 'text-[#333]' : 'text-[#999]']">
              {{ verifyTime[0] ? dayjs(verifyTime[0]).format('YYYY-MM-DD') : '开始时间' }}
            </text>
            <view class="w-[10%]">至</view>
            <text :class="[verifyTime[0] ? 'text-[#333]' : 'text-[#999]']">
              {{ verifyTime[1] ? dayjs(verifyTime[1]).format('YYYY-MM-DD') : '结束时间' }}
            </text>
          </div>
          <wd-calendar
            ref="calendar"
            type="daterange"
            :with-cell="false"
            v-model="verifyTime"
            @confirm="handleConfirm"
          />
          <!-- <wd-datetime-picker
            custom-value-class="text-[#333] child-value w=[100%]"
            :disabled="filterQuery.dateTimeType !== 4"
            v-model="verifyTime"
            type="date"
            @confirm="handleConfirm"
          ></wd-datetime-picker> -->
          <SectionHeading custom-class="my-[10px]" title="订单状态"></SectionHeading>
          <wd-radio-group cell shape="button" v-model="filterQuery.orderStatus">
            <template
              v-for="(tag, index) in [
                { label: '已报名', value: 0 },
                { label: '已完成', value: 1 },
                { label: '未核销', value: 2 },
                { label: '已取消', value: 3 },
                { label: '待交付', value: 4 },
              ]"
              :key="index"
            >
              <wd-radio :value="tag.value">
                {{ tag.label }}
              </wd-radio>
            </template>
          </wd-radio-group>
          <SectionHeading></SectionHeading>
          <div class="mt-[10px]">
            <wd-button block :round="false" @click="handleSubmit">确 认</wd-button>
            <!-- <wd-button block :round="true" @click="getOrders">重 置</wd-button> -->
          </div>
          <!-- <div class="mt-[10px]">
            <wd-button block :round="false" @click="getOrders">重置</wd-button>
          </div> -->
        </view>
      </wd-action-sheet>
    </template>
  </view>
</template>

<style scoped lang="scss">
::v-deep .wd-radio__label {
  line-height: 30px !important;
}
.child-value {
  display: flex;
  align-items: center;
  justify-content: space-between;
  > text {
    display: inline-block;
    width: 40%;
    padding-left: 10px;
    line-height: 30px;
    background-color: #f0f0f0;
    border-radius: 4px;
  }
}
</style>
