<route lang="json5">
{
  layout: 'tabbar',
  style: {
    navigationBarTitleText: '首页',
    navigationBarBackgroundColor: '#fff',
    navigationStyle: 'custom',
  },
}
</route>

<script lang="ts" setup>
import dayjs from 'dayjs'
import {
  getDesignerPointsActivities,
  getTaskList,
  getTodoPage,
  getTodos,
  scanCodeCheckPaper,
} from '../../core/libs/requests'
import SectionHeading from '@/components/section-heading.vue'
import Card from '@designer-hub/app/src/components/card.vue'
import { merchantPageHeaderBg, scanIcon, bookIcon } from '@designer-hub/assets/src/svgs'
import { useUserStore } from '../../store'
import { storeToRefs } from 'pinia'
import { qrCodeString2Object, requestToast } from '@designer-hub/app/src/core/utils/common'
import { QrCodeBusinessType } from '../../core/libs/enums'
import { useRouter } from '../../composables/router'
import PageHelperEvo from '@/components/page-helper-evo.vue'
import TaskCard from '../agent/components/task-card.vue'
import { getTasks } from '../../core/libs/agent-requests'
import { ComponentExposed } from 'vue-component-type-helpers'

defineOptions({
  name: 'Home',
})
const router = useRouter()
const userStore = useUserStore()
const { isLogined, userInfo, isAgent, isMerchant } = storeToRefs(userStore)
const orderAmount = ref()
const todoPageHelperRef = ref<ComponentExposed<typeof PageHelperEvo>>()
const pointsAmount = computed(() => orderAmount.value * 10)
const todosQuery = computed(() => ({
  brokerId: String(userInfo.value.userId),
  executionTime: [
    dayjs().startOf('days').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().endOf('days').format('YYYY-MM-DD HH:mm:ss'),
  ].join(','),
}))
const designerPointsActivitiesQuery = computed(() => ({
  brokerId: String(userInfo.value.userId),
}))
const { data: tasks, run: setTasks } = useRequest(
  () => getTasks({ brokerId: userInfo.value.userId, status: '1,2', pageNo: 1, pageSize: -1 }),
  { initialData: { list: [], total: 0 } },
)
const toDesigner = () => {
  uni.navigateTo({ url: '/pages/designer/index' })
}
const handleScanning = async () => {
  console.log('handleScanning')

  const { result } = await uni.scanCode({ scanType: ['qrCode'] })
  const { type, options } = qrCodeString2Object(result)
  if (type !== QrCodeBusinessType.InStoreWriteOff) {
    uni.showToast({ title: '不支持此二维码/条码', icon: 'none', duration: 5000 })
    return
  }
  await requestToast(() => scanCodeCheckPaper({ orderNo: options.no }), {
    success: true,
    successTitle: '验券成功',
  })
}
const handle2Settlement = () => {
  if ((orderAmount.value ?? '') === '') {
    uni.showToast({ title: '请输入金额', icon: 'none', duration: 5000 })
    return
  }
  router.push(
    `/pages/home/merchant/settlement?orderAmount=${orderAmount.value}&pointsAmount=${pointsAmount.value}`,
  )
}
const toAddReporting = () => {
  uni.navigateTo({ url: '/pages/home/merchant/add-reporting-information' })
}
onShow(async () => {
  if (isAgent.value) {
    await Promise.all([setTasks(), todoPageHelperRef.value?.refresh()])
  }
})
onLoad(() => {
  console.log(isLogined.value)
  if (!isLogined.value) {
    uni.reLaunch({ url: '/pages/login/index' })
  }
})
onShareAppMessage(() => ({}))
</script>

<template>
  <view class="flex-grow relative">
    <template v-if="isAgent">
      <div class="aspect-[0.96/1] absolute left-0 right-0 top--1">
        <wd-img
          width="100%"
          height="100%"
          :src="merchantPageHeaderBg"
          custom-class="vertical-bottom"
        ></wd-img>
      </div>
      <wd-navbar custom-class="bg-transparent!" safe-area-inset-top :bordered="false">
        <template #left>
          <div
            class="ml-1 text-center text-white text-lg font-normal font-['PingFang_SC'] leading-relaxed"
          >
            今日待办
          </div>
        </template>
      </wd-navbar>
      <div class="flex flex-col gap-8 p-4 relative box-border">
        <div>
          <div class="text-white text-sm font-normal font-['PingFang_SC'] leading-relaxed my-2.5">
            {{ dayjs().format('YYYY-MM-DD') }}
          </div>
          <Card>
            <div>
              <PageHelperEvo ref="todoPageHelperRef" :request="getTodoPage" :query="todosQuery">
                <template #default="{ source }">
                  <div class="flex flex-col py-6">
                    <template v-for="(it, index) in source?.list" :key="index">
                      <div>
                        <div class="grid grid-cols-[56px_12px_1fr] items-center gap-4">
                          <div
                            class="w-14 text-end text-black text-base font-normal font-['PingFang_SC'] leading-none"
                          >
                            {{ dayjs(it.executionTime).format('HH:mm') }}
                          </div>
                          <div class="w-3 h-3 relative">
                            <div
                              class="w-3 h-3 left-0 top-0 absolute rounded-full"
                              :class="`${it.status === 1 ? 'bg-[#517df8]/10' : 'bg-[#5e5e5e]/10'}`"
                            ></div>
                            <div
                              class="w-1.5 h-1.5 left-[3px] top-[3px] absolute rounded-full"
                              :class="`${it.status === 1 ? 'bg-[#517df8]' : 'bg-[#a8a8a8]'}`"
                            ></div>
                          </div>
                          <div class="text-black/60 text-sm font-normal font-['PingFang_SC']">
                            {{ it.content }}
                          </div>
                        </div>
                        <div
                          v-if="index < (source?.list?.length ?? 0) - 1"
                          class="grid grid-cols-[56px_12px_1fr] gap-4"
                        >
                          <div class=""></div>
                          <div class="w-3 flex justify-center">
                            <div class="w-.25 h-10 bg-[#EDEDED]"></div>
                          </div>
                          <div></div>
                        </div>
                      </div>
                    </template>
                  </div>
                </template>
              </PageHelperEvo>
              <div
                class="flex items-center justify-center b-t b-t-solid b-t-[#f6f6f6] pt-3.5"
                @click="router.push('/pages/agent/todo/index')"
              >
                <div class="text-[#2357e9] text-xs font-normal font-['PingFang_SC'] leading-none">
                  全部待办
                </div>
                <wd-icon name="arrow-right" size="10" color="#2357e9" />
              </div>
            </div>
          </Card>
        </div>
        <div>
          <SectionHeading
            title="任务"
            path="/pages/agent/tasks/index"
            end-text="查看全部"
            custom-class="mb-5"
          ></SectionHeading>
          <div class="flex overflow-x-auto whitespace-nowrap mx--4 px-4 gap-4 box-border">
            <Card custom-class="w-full" v-if="!tasks.list.length">
              <wd-status-tip image="search" tip="当前暂无未开始/进行中的任务" />
            </Card>

            <template v-for="(it, i) in tasks.list" :key="i">
              <div class="inline-block">
                <div class="w-[calc(75vw)]">
                  <TaskCard :options="it" @change="setTasks()"></TaskCard>
                </div>
              </div>
            </template>
          </div>
        </div>
        <div>
          <SectionHeading title="设计师" path="" custom-class="mb-5"></SectionHeading>
          <div class="flex flex-col gap-4">
            <template
              v-for="{ label, color, ...it } of [
                {
                  label: '关系报备',
                  color: 'white',
                  path: '/pages/agent/report-infos/index',
                },
                {
                  label: '全部设计师',
                  color: '#7199FF',
                  path: '/pages/agent/designer/index?title=全部设计师',
                },
                {
                  label: '重点跟进设计师',
                  color: '#FF523F',
                  path: '/pages/agent/designer/index?title=重点跟进设计师&tags=1',
                },
                {
                  label: '本月新增设计师',
                  color: '#FFE786',
                  path: '/pages/agent/designer/index?title=本月新增设计师&tags=2',
                },
                {
                  label: '超过30天未跟进',
                  color: '#89F4E3',
                  path: '/pages/agent/designer/index?title=超过30天未跟进&tags=3',
                },
                {
                  label: '超过60天未产生积分设计师',
                  color: '#FFBA6A',
                  path: '/pages/agent/designer/index?title=超过60天未产生积分设计师&tags=4',
                },
                {
                  label: '超过60天未消耗积分设计师',
                  color: '#C494FF',
                  path: '/pages/agent/designer/index?title=超过60天未消耗积分设计师&tags=5',
                },
                {
                  label: '未成交过设计师',
                  color: '#FF9EE2',
                  path: '/pages/agent/designer/index?title=未成交过设计师&tags=6',
                },
              ]"
              :key="label"
            >
              <div class="h-12 bg-white rounded-lg shadow flex items-center hover:bg-[#fff6f5]">
                <div
                  class="w-1.5 h-12 rounded-tl-lg rounded-bl-lg shadow"
                  :style="{ background: color }"
                ></div>
                <div class="flex-1 mx-3">
                  <SectionHeading :title="label" :path="it.path" size="sm"></SectionHeading>
                </div>
              </div>
            </template>
          </div>
        </div>
        <div>
          <SectionHeading title="设计师最新动态" path="" custom-class="mb-5"></SectionHeading>
          <PageHelperEvo
            :request="getDesignerPointsActivities"
            :query="designerPointsActivitiesQuery"
          >
            <template #default="{ source }">
              <div class="flex flex-col gap-4">
                <template v-for="(it, i) in source?.list" :key="i">
                  <Card>
                    <div
                      class="text-black/90 text-sm font-normal font-['PingFang_SC'] leading-none"
                    >
                      {{ it.content }}
                    </div>
                    <div
                      class="mt-3 text-black/30 text-xs font-normal font-['PingFang_SC'] leading-none"
                    >
                      {{ dayjs(it.createTime).format('YYYY-MM-DD HH:mm') }}
                    </div>
                  </Card>
                </template>
              </div>
            </template>
          </PageHelperEvo>
        </div>
      </div>
    </template>
    <template v-if="isMerchant">
      <div
        class="bg-white backdrop-blur-[60px] my-[16px] flex flex-col justify-center items-center p-[16px] mt-[20px]"
      >
        <div
          class="w-[68px] h-[68px] bg-[#2357e9] rounded-full mt-[37px] flex items-center justify-center"
        >
          <wd-img width="36px" height="36px" :src="scanIcon"></wd-img>
        </div>
        <div class="w-full mt-[45px]">
          <wd-button block :round="false" @click="handleScanning">
            <div
              class="text-center text-white text-base font-normal font-['PingFang_SC'] leading-normal"
            >
              扫码验券
            </div>
          </wd-button>
        </div>
      </div>
      <div
        class="bg-white backdrop-blur-[60px] flex flex-col justify-center items-center p-[16px] mt-[20px]"
      >
        <div
          class="w-[68px] h-[68px] bg-[#2357e9] rounded-full mt-[34px] flex items-center justify-center"
        >
          <wd-img width="36px" height="36px" :src="bookIcon"></wd-img>
        </div>
        <div class="w-full flex items-center mt-[40px] gap-5">
          <div
            class="text-black/90 text-base font-normal font-['PingFang_SC'] leading-relaxed w-[96px]"
          >
            输入订单金额
          </div>
          <div class="flex-1 bg-[#f5f7f9] rounded-lg flex items-center p-3.5">
            <wd-input
              custom-class="bg-transparent! flex-1"
              type="number"
              no-border
              placeholder="请输金额"
              v-model="orderAmount"
            />
          </div>
        </div>
        <div class="w-full flex items-center mt-[20px] gap-5">
          <div
            class="text-black/90 text-base font-normal font-['PingFang_SC'] leading-relaxed w-[96px]"
          >
            需支付积分
          </div>
          <div class="text-[#ff2d2d] text-base font-normal font-['PingFang_SC'] leading-relaxed">
            {{ pointsAmount }} 积分
          </div>
        </div>
        <div class="w-full mt-[45px]">
          <wd-button block :round="false" @click="handle2Settlement">
            <div
              class="text-center text-white text-base font-normal font-['PingFang_SC'] leading-normal"
            >
              积分结账
            </div>
          </wd-button>
        </div>
      </div>
    </template>
  </view>
</template>

<style></style>
