<template>
  <BasePage>
    <ManagerPopup v-model="managerPopupVisible" />
    <div class="merchant">
      <div class="shopinfo">
        <img class="tx" :src="$file(data.shopimg)">
        <div class="info">
          <b>{{ truncatedShopname }}</b>
          <p>账号：{{ data.shopphone }}</p>
        </div>

        <div class="service-box" @click="$showManagerPopup()">
          管理中心
          <van-icon name="arrow"></van-icon>
        </div>
      </div>

      <div class="wallet">
        <div class="tit">
          <span @click="$navigate('MerchantIncome')"> 营业收入(元) <van-icon name="arrow"></van-icon>
          </span>
          <div class="line">
            <b @click="$navigate('MerchantIncome')">
              {{ data.shangjiashouru?.toFixed(2) }}
            </b>
            <!--  v-if="data.Income" -->
            <div @click="$navigate('MerchantCashout')">
              <span>提现中金额
              </span>
              <p>￥{{ data.withdrawing?.toFixed(2) }}</p>
            </div>
          </div>
        </div>
        <div class="cc">
          <div class="ll" @click="$navigate('Balance')">
            <span>
              可用余额<van-icon name="arrow"></van-icon>
            </span>
            <b>{{ data.keyongyue?.toFixed(2) }}</b>
          </div>
          <div class="ll" @click="$navigate('CV')">
            <span>
              会员卡额度<van-icon name="arrow"></van-icon>
            </span>
            <b>{{ data.huiyuanka?.toFixed(2) }}</b>
          </div>
        </div>
      </div>

      <!-- <div class="block">
        <div class="d1" @click="$navigate('MerchantTrade')">
          <b>订单记录</b>
          <p>查看订单记录</p>
          <van-badge :content="expiring ? expiring : ''" :offset="[60, -40]">
            <button>立即查看</button>
          </van-badge>
          <img src="/img/bbb1.png">
        </div>
        <div class="_r">
          <div class="d2" @click="$navigate('MerchantTrade')">
            <b>订单记录</b>
            <p>查看订单记录</p>
            <button>立即查看</button>
            <img src="/img/bbb2.png">
          </div>
          <div class="d3" @click="$navigate('MerchantProduct')">
            <b>产品列表</b>
            <p>查看我的产品</p>
            <button>立即查看</button>
            <img src="/img/bbb3.png">
          </div>
        </div>

      </div> -->

      <div class="fastTo">
        <div class="ft1" @click="showBottom = true">
          <span>收款码</span>
          <img src="/img/ft_i1.png" alt="">
        </div>

        <div class="ft2" @click="$navigate('MerchantTrade')">
          <span>订单记录</span>
          <img src="/img/ft_i2.png" alt="">
        </div>

        <div class="ft3" @click="$navigate('MerchantIntroduction')">
          <span>商家资料</span>
          <img src="/img/ft_i3.png" alt="">
        </div>
      </div>

      <div class="countbox">
        <div class="title">
          <b>经营数据</b>
        </div>
        <div class="box line">
          <span>截止{{ data.endTimes }}</span>
          <p class="refresh" @click="getCount">刷新</p>
          <p class="cou r" @click="$navigate('Statistics')">统计<van-icon name="arrow"></van-icon></p>
        </div>

        <div class="list">
          <div class="item">
            <span>
              今日营业额（元）
            </span>
            <b>{{ countData.todayyingyee?.toFixed(2) }}</b>
            <p>昨日<span>{{ countData.yesterdayyingyee?.toFixed(2) }}</span></p>
          </div>

          <div class="item">
            <span>
              今日应收（元）
            </span>
            <b>{{ countData.todayyingshou?.toFixed(2) }}</b>
            <p>昨日<span>{{ countData.yesterdayingshou?.toFixed(2) }}</span></p>
          </div>

          <div class="item">
            <span>
              今日订单数
            </span>
            <b>{{ countData.todaydingdanshu }}</b>
            <p>昨日<span>{{ countData.yesterdaydingdanshu }}</span></p>
          </div>

          <div class="item">
            <span>
              今日惠利金额（元）
            </span>
            <b>{{ countData.todayyouhui?.toFixed(2) }}</b>
            <p>昨日<span>{{ countData.yesterdayyouhui?.toFixed(2) }}</span></p>
          </div>
        </div>
      </div>


    </div>

    <van-action-sheet v-model:show="showBottom" title="收款码" @click-overlay="onCloseBottom" @opened="onOpenBottom">
      <div class="paycode-wrap">
        <div class="paycode-original" ref="paycodeOriginal" v-show="!paycodeImg">
          <img src="/img/paycode.jpg" alt="" style="width: 100%; display: block;">
          <div class="info">
            <img :src="$file(data.shopimg)" alt="" style="border-radius: 50%;">
          </div>
          <div class="name">
            <span>{{ data.shopname }}</span>
          </div>
          <div class="code">
            <vue-qr v-if="!loading" :margin="0" :text="link" backgroundColor="rgb(255,255,255)"
              colorLight="rgb(255,255,255)"></vue-qr>
          </div>
        </div>
        <div class="paycode-result" v-if="paycodeImg">
          <img :src="paycodeImg" style="width: 100%;" alt="收款码">
        </div>
      </div>
    </van-action-sheet>
  </BasePage>

</template>

<script>
import { html2canvas } from '@/utils/html2image'
import ManagerPopup from "@/components/ManagerPopup.vue"

export default {
  name: 'Merchant',
  components: { ManagerPopup },
  mounted() {
    this.init()
    window.addEventListener('showManagerPopup', this.onShowManagerPopup)
    window.addEventListener('closeManagerPopup', this.onCloseManagerPopup)
  },
  beforeUnmount() {
    window.removeEventListener('showManagerPopup', this.onShowManagerPopup)
    window.removeEventListener('closeManagerPopup', this.onCloseManagerPopup)
  },
  data() {
    return {
      managerPopupVisible: false,
      showInfo: false,
      showBottom: false,
      paycodeImg: '',
      isCapturing: false,
      link: '',
      id: this.$route.query.id,
      data: {
        id: 'merchant_001',
        MerchantAvatar: '',
        MerchantName: '泰古润直营店',
        MerchantPhone: '13800138000',
        Income: 12868.50,
        Point: 5680.00,
        TodayAmount: 5680.00,
        YesterdayAmount: 4200.00,
        TodayDeduct: 1280.00,
        YesterdayDeduct: 980.00,
        TodayQty: 45,
        YesterdayQty: 38,
        MonthIncome: 45600.00,
        PrevMonthIncome: 38500.00,
        endTimes: new Date().toLocaleString('zh-CN', { hour12: false })
      },
      countData: {},
      States: 0,
      expiring: 3,
      loading: false,
    }
  },
  computed: {
    truncatedShopname() {
      if (!this.data.shopname) return ''
      return this.data.shopname.length > 8 ? this.data.shopname.slice(0, 8) + '...' : this.data.shopname
    }
  },
  methods: {
    onShowManagerPopup() {
      this.managerPopupVisible = true
    },
    onCloseManagerPopup() {
      this.managerPopupVisible = false
    },
    init() {
      Promise.all([
        this.$get(`/v1/client/DShopsClient/${this.id}`).then(res => {
          // console.log(res);
          this.data = res.data;
          this.data.endTimes = new Date().toLocaleString('zh-CN', { hour12: false });
          this.$ls.set('merchant_shopname', res.data.shopname);
          this.$ls.set('merchant_shopimg', res.data.shopimg);
          this.$ls.set('merchant_cellphone', res.data.cellphone);

          this.link = `${location.origin}${location.pathname}#/Checkout?id=${res.data.userid}`
        }),
        this.getCount()
      ]
      )
    },
    async onOpenBottom() {
      this.paycodeImg = ''
      this.$nextTick(async () => {
        const el = this.$refs.paycodeOriginal
        if (!el) return

        const scale = 2
        const elRect = el.getBoundingClientRect()

        // 不画全图，改为各部分分别截图再合成
        // 创建最终画布
        const canvas = document.createElement('canvas')
        const w = el.offsetWidth * scale
        const h = el.offsetHeight * scale
        canvas.width = w
        canvas.height = h
        const ctx = canvas.getContext('2d')

        // 画背景图（只截取背景img）
        const bg = el.querySelector('img')
        const bgCanvas = await html2canvas(bg, { scale, useCORS: true, width: el.offsetWidth, height: el.offsetHeight })
        ctx.drawImage(bgCanvas, 0, 0, w, h)

        // 截取头像并画成圆形
        const infoEl = el.querySelector('.info')
        const avatarEl = infoEl.querySelector('img')
        const avatarCanvas = await html2canvas(avatarEl, { scale, useCORS: true, backgroundColor: 'transparent' })

        const infoRect = infoEl.getBoundingClientRect()
        const avatarSize = 30 * scale
        const avatarX = (infoRect.left - elRect.left) * scale
        const avatarY = (infoRect.top - elRect.top) * scale

        ctx.save()
        ctx.beginPath()
        ctx.arc(avatarX + avatarSize / 2, avatarY + avatarSize / 2, avatarSize / 2, 0, Math.PI * 2)
        ctx.clip()
        ctx.drawImage(avatarCanvas, avatarX, avatarY, avatarSize, avatarSize)
        ctx.restore()

        // 截取二维码
        const codeEl = el.querySelector('.code')
        const codeCanvas = await html2canvas(codeEl, { scale, useCORS: true, backgroundColor: '#ffffff' })
        const codeRect = codeEl.getBoundingClientRect()
        ctx.drawImage(
          codeCanvas,
          (codeRect.left - elRect.left) * scale,
          (codeRect.top - elRect.top) * scale,
          codeRect.width * scale,
          codeRect.height * scale
        )

        // 画商户名文字 (根据.name样式定位)
        const nameEl = el.querySelector('.name')
        const nameRect = nameEl.getBoundingClientRect()
        const fontSize = 20 * scale
        ctx.font = `${fontSize}px 'PingFang SC'`
        ctx.fillStyle = '#333'
        ctx.textBaseline = 'middle'
        if (this.data.shopname)
          ctx.fillText(this.truncatedShopname, (nameRect.left - elRect.left) * scale, (nameRect.top - elRect.top) * scale + fontSize / 2)

        this.paycodeImg = canvas.toDataURL('image/png')
      })
    },
    onCloseBottom() {
      this.showBottom = false
      // this.paycodeImg = ''
    },
    getCount() {
      this.$get('/v1/client/DShopsClient/statistics').then(res => {
        this.countData = res.data;
        this.data.endTimes = new Date().toLocaleString('zh-CN', { hour12: false });
      })
    },
  },
}

</script>

<style lang="less">
.paycode-original {
  position: relative;
  width: 100%;
  font-family: 'PingFang SC';

  >img {
    width: 100%;
    display: block;
  }

  .info {
    display: flex;
    align-items: center;
    position: absolute;
    left: 30.67vw;
    top: 32.27vw;

    img {
      width: 6.4vw;
      height: 6.4vw;
      border-radius: 50%;
    }
  }

  .name {
    position: absolute;
    left: 39.33vw;
    top: 33.47vw;

    span {
      font-size: 4vw;
      color: #333;
    }
  }

  .code {
    position: absolute;
    top: 42.4vw;
    left: 23.33vw;

    canvas,
    img {
      width: 53.33vw;
      height: 53.33vw;
    }
  }
}
</style>