<template>
  <a-collapse-panel :key="`${provider.providerId}`" >
    <template #extra>
      <div class="flex space-x-4 items-center">
        <div>更新时间：{{dayjs(provider.updatedAt).format('YYYY-MM-DD HH:mm:ss')}}</div>
        <a-button v-if="provider.providerId==='us-coach-outlet'" type="primary" @click="OneClickWatch(provider.pid, provider.pid)">一键蹲货</a-button>
        <div v-if="provider.skuID">抓取：<a-switch :checked="!provider.exclude" @click="onClickExclude"/></div>
      </div>
    </template>
    <template #header>
      <div>
        <span class="text-lg">{{header}}</span>
      </div>
    </template>
    <div class="flex flex-col space-y-8">
      <div class="flex space-x-4  ">
        <div class="w-full">货号：{{provider.pid || '-'}}</div>
<!--        <div class="w-50">SpuID: {{provider.spuID || '-'}} </div>-->
        <div class="w-full">SkuID:
          <a-button type="link" :href="provider.link" target="_blank" v-if="provider.skuID">{{provider.skuID}}</a-button>
          <span v-else>-</span>
        </div>
        <div class="w-full">可以购买：{{provider.available ? '是':'否'}}</div>
      </div>
      <div class="flex space-x-4 items-center">
        <div class="w-full">当前售价：$ {{provider.cost.originalPrice || '-'}}</div>

        <div v-if="provider.cost.calMark" class="w-full flex items-center space-x-4">
          <a-popover  trigger="hover">
            <template #content>
                    <span class="whitespace-pre">
                      {{provider.cost.calMark}}
                    </span>
            </template>
            <div>当前到手价：￥ {{provider.cost.finalPrice || '-'}}</div>
          </a-popover>
          <a-button type="primary" @click="fetchArticle(provider)" :loading="fetchLoading">拉取价格</a-button>
        </div>
        <div class="w-full flex items-center space-x-4" v-else>
          <div>当前到手价：￥ {{provider.cost.finalPrice || '-'}}</div>
          <a-button type="primary" @click="fetchArticle(provider)" :loading="fetchLoading">拉取价格</a-button>
        </div>
        <div class="w-full flex items-center space-x-4">
          <div>库存：{{provider.ast }}</div>
          <a-button type="primary" @click="fetchArticleAts(provider)" :loading="fetchLoading">拉取库存</a-button>
        </div>
      </div>
      <v-chart class="h-400px w-full" :option="options" />
    </div>
  </a-collapse-panel>
</template>
<script setup>
import dayjs from "dayjs";
import {GetProviderHistory, UpdateProviderArticle} from "@/api/articles.js";
import {message} from "ant-design-vue";
import {computed, ref, watch} from "vue";
import VChart from "vue-echarts";
import {OneClickWatch} from "@/componse/one-click-watch.js";

const props = defineProps({
  provider: {
    type: Object,
    default: () => {
      return {
        providerId: '',
        updatedAt: 0,
        skuID:'',
        pid: '',
        cost: {
          originalPrice: 0,
          finalPrice: 0,
          calMark: ''
        }
      }
    }
  },
  providerDict:{
    type: Array,
    default: () => {
      return []
    }
  },
  open: {
    type: Boolean,
    default: false
  }
})

const header = computed(() => {
  return props.providerDict.find(s => s.providerId === props.provider.providerId)?.name
})

const onClickExclude = (checked, e) => {
  props.provider.exclude = !checked
  UpdateProviderArticle(props.provider).then(res => {
    if (res.code !== 200) {
      message.error(`更新失败:${res.msg}`)
    } else {
      message.success('更新成功')
    }
  }).catch(err => {
    message.error('更新失败')
    console.log(err)
  })
}

watch(() => props.open, (newVal) => {
  if (newVal && !(props.provider.historyPrice?.length > 0)) {
    GetProviderHistory(props.provider.id).then(res => {
      if (res.code !== 200) {
        message.error(`获取历史数据失败:${res.msg}`)
      } else {
        props.provider.historyPrice = res.data
      }
    })
  }
})

//   图表

import { use } from 'echarts/core'
import { LineChart } from 'echarts/charts'
import { GridComponent, TitleComponent, TooltipComponent, LegendComponent  } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import {FetchProviderArticleAts, FetchProviderArticlePrice} from "@/api/provider.js";

use([GridComponent, LineChart, CanvasRenderer, TitleComponent , TooltipComponent, LegendComponent ])

const options = computed(()=> {
  return {
    title: {
      text: "历史价格",
      left: "center"
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c}'
    },
    legend: {
      left: 'left'
    },
    xAxis: {
      type: 'category',
      name: '日期',
      data: (props.provider.historyPrice|| []).map(p => dayjs(p.createdAt).format('YYYY-MM-DD'))
    },
    yAxis: {
      name: '价格'
    },
    series: [
      {
        type: 'line',
        name: '原价',
        data: (props.provider.historyPrice|| []).map(p => p.originalPrice)
      },
      {
        type: 'line',
        name: '到手价',
        data: (props.provider.historyPrice|| []).map(p => p.finalPrice)
      }
    ]
  }
})

const fetchLoading = ref(false)
// 拉取单个商品价格
const fetchArticle = (pArticle) => {
  fetchLoading.value = true
  FetchProviderArticlePrice(pArticle).then(res=>{
    if(res.code !== 200){
      message.error(`拉取失败:${res.msg}`)
    }else {
      message.success('拉取成功')
    }
  }).catch(err => {
    message.error('拉取失败')
    console.log(err)
  }).finally(()=>{
    fetchLoading.value = false
    emits('fetched')
  })
}

const fetchArticleAts = (pArticle) => {
  fetchLoading.value = true
  FetchProviderArticleAts(pArticle).then(res=>{
    if(res.code !== 200){
      message.error(`拉取失败:${res.msg}`)
    }else {
      message.success('拉取成功')
    }
  }).catch(err => {
    message.error('拉取失败')
    console.log(err)
  }).finally(()=>{
    fetchLoading.value = false
    emits('fetched')
  })
}

const emits = defineEmits(['fetched'])
</script>


<style scoped>

</style>