<route lang="json">
{ "style": { "navigationStyle": "custom" } }
</route>
<script setup lang="ts">
import Card from '@/components/card.vue'
import SectionHeading from '@/components/section-heading.vue'
import {
  getMaterialDetail,
  getByDictType,
  getMaterialHomePage,
  downloadMaterials,
} from '../../../core/libs/requests'
import NavbarEvo from '@/components/navbar-evo.vue'
import { DictType } from '../../../core/libs/models'
import { close, phone } from '../../../core/libs/svgs'
import { handleCall, openLocation, previewImage } from '../../../core/utils/common'
import router from '@designer-hub/assets/src/assets/svgs/router'
import { isVideoUrl } from 'wot-design-uni/components/common/util'
import { useUserStore } from '@/store'
import { AnalysisEventType, useAnalysis } from '@/composables/analysis'
import { usePermissions } from '@/composables/permissions'
const dealerPanelState = ref(false)
const { clickByPermission } = usePermissions()
const userStore = useUserStore()
const { option } = useAnalysis(true, false)
const id = ref()
const downloading = ref(false)
const currentBanner = ref(0)
const handleSwiperChange = ({ detail: { current, source } }) => {
  currentBanner.value = current 
}
const { data, run: setData } = useRequest(() => getMaterialDetail({ id: id.value }))
const { data: materialHomePageData, run: setMaterialHomePageData } = useRequest(
  () => getMaterialHomePage(id.value),
  { initialData: {} },
)
const { data: materialBrandLevels, run: setMaterialBrandLevels } = useRequest(
  () => getByDictType(DictType.memberMaterialsBrandLevel),
  { initialData: [] },
)
const { data: materialOperationTypes, run: setMaterialOperationTypes } = useRequest(
  () => getByDictType(DictType.memberMaterialsOperationType),
  { initialData: [] },
)
const { data: materialBrandTypes, run: setMaterialBrandTypes } = useRequest(
  () => getByDictType(DictType.memberMaterialsBrandType),
  { initialData: [] },
)
const { data: materialsManageBrands, run: setMaterialsManageBrands } = useRequest(
  () => getByDictType(DictType.materialsManageBrand),
  { initialData: [] },
)
const copy = (url) =>{
	uni.setClipboardData({
		data:url,
		success: () => {
			console.log("已复制")
		}
	})
}
const handleDownload = async () => {
  downloading.value = true
  const { filePath } = await uni.downloadFile({
    url: data.value.agreementFileUrl,
    filePath: `${uni.env.USER_DATA_PATH}/${data.value.materialsName}的素材包.zip`,
    header: {
      'Content-Type': 'application/x-zip-compressed',
    },
  })
  downloading.value = false
  await downloadMaterials({ materialsId: id.value })
  const { deviceType } = await uni.getDeviceInfo()
  if (deviceType === 'pc') {
    uni.saveFileToDisk({
      filePath,
      success: (res) => {
        console.log('saveFileToDisk success', res)
      },
      fail: (err) => {
        console.log('saveFileToDisk fail', err)
      },
    })
  } else {
    uni.openDocument({
      filePath,
      success: (res) => {
        console.log('openDocument success', res)
      },
      fail: (err) => {
        console.log('openDocument fail', err)
      },
    })
  }
}
onLoad(async (query: { id: number }) => {
  id.value = query.id
  await setData()
  option.value = {
    remark: `最近浏览品牌: ${data.value?.materialsName}`,
  }
  await setMaterialHomePageData()
  console.log(data.value)
  await Promise.all([
    setMaterialBrandLevels(),
    setMaterialBrandTypes(),
    setMaterialOperationTypes(),
    setMaterialsManageBrands(),
  ])
})
onShareAppMessage(() => ({
  title: data.value?.materialsName,
}))
onShareTimeline(() => ({
  title: data.value?.materialsName,
}))
</script>
<template>
  <view class="flex-grow flex flex-col">
    <div
      class="w-full aspect-[1.16/1] bg-[url(https://image.zhuchaohui.com/zhucaohui/9da274c73312f5ff828b60457bf4a469e631c001a4bf1c1f355338887b19f035.png)] bg-[length:100%]"
      :style="{ backgroundImage: `url(${materialHomePageData?.bannerUrl})` }"
    ></div>
    <NavbarEvo transparent></NavbarEvo>
    <div class="flex flex-col gap-6 relative top--14 px-3.5">
      <Card>
        <div class="flex flex-col gap-4">
          <div class="flex gap-5">
            <wd-img
              round
              width="78"
              height="78"
              custom-class="border border-[#f2f2f2] border-solid"
              :src="data?.logoUrl"
            ></wd-img>
            <div class="flex flex-col gap-2.5">
              <div class="flex gap-2 items-center">
                <div class="text-black/90 text-lg font-normal font-['PingFang_SC']">
                  <!-- IMOLA瓷砖 -->
                  {{ data?.materialsName }}
                </div>

                <!--                <div-->
                <!--                  class="w-[52px] h-[17px] px-2 bg-[#ef4343] rounded-[3px] justify-center items-center gap-2.5 inline-flex"-->
                <!--                >-->
                <!--                  <div-->
                <!--                    class="text-white text-[10px] font-normal font-['PingFang_SC'] leading-normal"-->
                <!--                  >-->
                <!--                    &lt;!&ndash; 自营品牌 &ndash;&gt;-->
                <!--                    {{-->
                <!--                      materialBrandLevels.find(({ value }) => value === String(data.materialsType))-->
                <!--                        ?.label-->
                <!--                    }}-->
                <!--                  </div>-->
                <!--                </div>-->
              </div>
              <div class="text-black/40 text-xs font-normal font-['PingFang_SC'] leading-[10.18px]">
                {{
                  materialBrandTypes.find(({ value }) => value === String(data?.brandType))?.label
                }}
                |
                {{
                  materialOperationTypes.find(({ value }) => value === String(data?.manageType))
                    ?.label
                }}
              </div>
              <div>
                <span
                  class="text-black/40 text-xs font-normal font-['PingFang_SC'] leading-[10.18px]"
                >
                  经营品牌：
                </span>
                <span
                  class="text-black/40 text-xs font-normal font-['PingFang_SC'] uppercase leading-[10.18px]"
                >
                  <!-- imola / chedit -->
                  {{
                    materialsManageBrands.find(({ value }) => value === String(data?.manageBrand))
                      ?.label
                  }}
                </span>
              </div>
              <!--              <div class="flex gap-2.5">-->
              <!--                <div-->
              <!--                  class="w-[77px] h-5 px-2 py-px bg-neutral-100 rounded-[3px] justify-center items-center gap-2.5 inline-flex"-->
              <!--                >-->
              <!--                  <div-->
              <!--                    class="text-black/60 text-[10px] font-normal font-['PingFang_SC'] leading-normal"-->
              <!--                  >-->
              <!--                    积分比例:{{ data?.pointsExchangeRate }}%-->
              <!--                  </div>-->
              <!--                </div>-->
              <!--                <div-->
              <!--                  class="w-[92px] h-5 px-2 py-px bg-neutral-100 rounded-[3px] justify-center items-center gap-2.5 inline-flex"-->
              <!--                >-->
              <!--                  <div-->
              <!--                    class="text-black/60 text-[10px] font-normal font-['PingFang_SC'] leading-normal"-->
              <!--                  >-->
              <!--                    门店打卡:{{ data?.clockPoints }}积分-->
              <!--                  </div>-->
              <!--                </div>-->
              <!--              </div>-->
            </div>
          </div>
          <template
            v-for="({ shopAddr, shopName, shopContactPhone, ...shop }, i) in data?.shopList"
            :key="i"
          >
            <div class="bg-neutral-50 rounded-2.5 p-3.5 flex items-center">
              <div class="text-black/40 flex-1 border-r-2 border-r-[#f6f6f6] border-r-solid pr-4">
                <div class="text-black/90 text-lg font-normal font-['PingFang_SC'] leading-normal">
                  {{ shopName }}
                </div>
                <div>
                  <wd-icon name="location" size="15"></wd-icon>
                  <span
                    class="text-black/40 text-xs font-normal font-['PingFang_SC'] leading-normal"
                  >
                    {{ shopAddr }}
                  </span>
                </div>
              </div>
              <wd-button
                type="text"
                size="small"
                custom-class=" bg-[#f2f2f2]! p-0! ml-4"
                @click="handleCall(shopContactPhone)"
              >
                <wd-img width="28" height="28" :src="phone"></wd-img>
              </wd-button>
              <wd-button
                type="text"
                size="small"
                custom-class=" bg-[#f2f2f2]! p-0! ml-4"
                @click="
                  openLocation({
                    latitude: shop.latitude,
                    longitude: shop.longitude,
                    name: shopName,
                    address: shopAddr,
                  })
                "
              >
                <wd-img width="28" height="28" :src="router"></wd-img>
              </wd-button>
            </div>
          </template>
        </div>
      </Card>
      <Card>
        <div class="flex flex-col gap-4">
          <div
            class="text-black/90 text-lg font-normal font-['PingFang_SC'] leading-[10.18px] pt-4"
          >
            品牌介绍
          </div>
          <div
            v-if="(materialHomePageData.brandAdvantageUrl ?? '') !== ''"
            class="rounded-2xl overflow-hidden aspect-[1.72/1] whitespace-pre-wrap"
          >
            <!-- <wd-img
              width="100%"
              height="100%"
              :src="materialHomePageData.brandAdvantageUrl"
              mode="aspectFill"
              custom-class=""
            ></wd-img> -->
            <template v-if="isVideoUrl(materialHomePageData.brandAdvantageUrl)">
              <video class="w-full h-full" :src="materialHomePageData.brandAdvantageUrl"></video>
            </template>
            <template v-else>
              <wd-img
                width="100%"
                height="100%"
                :src="materialHomePageData.brandAdvantageUrl"
                mode="aspectFill"
                custom-class=""
              ></wd-img>
            </template>
          </div>
          <!--          <div class="text-black/90 text-base font-normal font-['PingFang_SC'] leading-[10.18px]">-->
          <!--            {{-->
          <!--              materialsManageBrands.find(({ value }) => value === String(data?.manageBrand))?.label-->
          <!--            }}-->
          <!--          </div>-->
          <div
            class="text-justify text-black/60 text-sm font-normal font-['PingFang_SC'] leading-[25px] whitespace-pre-wrap"
          >
            {{ materialHomePageData.brandAdvantageDesc }}
          </div>
        </div>
      </Card>
      <template v-if="materialHomePageData.productDOList?.length">
        <SectionHeading title="产品展示"></SectionHeading>
      </template>
      <template v-for="(it, index) in materialHomePageData.productDOList" :key="index">
        <div class="aspect-[1.66/1] rounded-2xl overflow-hidden relative">
          <swiper class="h-[55.7vw]" @change="handleSwiperChange">
            <template v-for="(img, index) in it?.productImgUrl?.split(',')" :key="img">
              <swiper-item class="h-full">
                <wd-img
                  width="100%"
                  height="100%"
                  class=""
                  :src="img"
                  mode="aspectFill"
                  @click="previewImage(index, it?.productImgUrl?.split(','))"
                />
              </swiper-item>
            </template>
          </swiper>
          <div
            class="absolute bottom-0 w-full h-[66px] bg-gradient-to-t from-black to-[#5e5e5e00] rounded-bl-2xl rounded-br-2xl flex items-center px-4.5"
          >
            <div class="text-white text-base font-normal font-['PingFang_SC'] leading-[10.18px]">
              {{ it.productTitleName }}
            </div>
          </div>
		  <div class="absolute flex gap-1 dots">
		    <template v-for="(img, i) in it?.productImgUrl?.split(',')" :key="i">
		      <div
		        class="w-1 h-1 rounded-full"
		        :class="`${currentBanner === i ? 'bg-white bg-active' : 'bg-white/40'}`"
		      ></div>
		    </template>
		  </div>
        </div>
      </template>

      <!-- <wd-button
        custom-class="w-full! rounded-lg!"
        :disabled="(data?.agreementFileUrl ?? '') === ''"
        :loading="downloading"
        @click="clickByPermission('download', () => handleDownload())"
      >
        {{ downloading ? '下载中...' : '下载所有素材包' }}
      </wd-button> -->
	  <wd-button
	    custom-class="w-full! rounded-lg!"
	    :disabled="(data?.agreementFileUrl ?? '') === ''"
		@click="clickByPermission('download', () => dealerPanelState = true)"
	  >
	    下载所有素材包
	  </wd-button>
    </div>
	<wd-overlay :show="dealerPanelState" @click="dealerPanelState = false">
	  <view class="wrapper flex flex-col justify-end h-full">
	    <div class="w-full flex justify-end mb-4">
	      <div class="mr-3.5">
	        <wd-button type="text" custom-class="w-8! h-8! p-0!" size="small">
	          <wd-img :src="close" width="28" height="28" custom-class="vertical-bottom"></wd-img>
	        </wd-button>
	      </div>
	    </div>
		<div class="bg-neutral-100 rounded-tl-2xl rounded-tr-2xl p-3.5" @click.stop="">
			<div class="deal-title">请复制以下链接，打开默认浏览器，粘贴到浏览器进行下载</div>
			<div class="deal-link">{{ data?.agreementFileUrl }}</div>
			<wd-button custom-class="custom-shadow" @click="copy(data?.agreementFileUrl)">复制链接</wd-button>
		</div>
	  </view>
	</wd-overlay>
  </view>
</template>
<style scoped>
	.dots{
		bottom: 30rpx;
		left: 50%;
		transform: translateX(-50%);
	}
	.bg-active{
		width:40rpx;
	}
	.deal-title{
		font-size:32rpx;
		text-align: center;
		font-weight: bold;
		padding:60rpx 0;
	}
	.deal-link{
		padding: 20rpx 30rpx;
		font-size: 28rpx;
		color: rgba(0, 0, 0, 0.45);
		background-color: rgba(200, 200, 200, 0.w);
		border-radius: 20rpx;
		margin-bottom:60rpx;
		word-wrap: break-word;
	}
	:deep(.custom-shadow){
		width:100% !important;
	}
</style>