<template>
  <view class="Mall4j page-invoice-detail">
    <!-- 发票状态 -->
    <view class="status-box">
      <view class="bg">
        <image src="@/static/images/status-bg.jpg" />
      </view>
      <view
        v-if="invoiceInfo.invoiceState === 2"
        class="status"
      >
        发票状态：已开票
      </view>
      <view
        v-else
        class="status"
      >
        发票状态：申请中
      </view>
    </view>

    <!-- 发票信息 -->
    <view class="invoice-info">
      <view class="item">
        <view class="tit">
          发票类型
        </view>
        <view class="text">
          电子普通发票
        </view>
      </view>
      <view class="item">
        <view class="tit">
          发票内容
        </view>
        <view class="text">
          商品明细
        </view>
      </view>
      <view class="item">
        <view class="tit">
          发票抬头
        </view>
        <view
          v-if="invoiceInfo.headerType === 1"
          class="text"
        >
          {{ invoiceInfo.headerName }}
        </view>
        <view
          v-else
          class="text"
        >
          {{ invoiceInfo.headerName || '个人' }}
        </view>
      </view>
      <view
        v-if="invoiceInfo.headerType === 1"
        class="item"
      >
        <view class="tit">
          公司税号
        </view>
        <view class="text">
          {{ invoiceInfo.invoiceTaxNumber }}
        </view>
      </view>
      <view
        v-if="invoiceInfo.invoiceState === 2"
        class="item"
      >
        <view class="tit">
          开票时间
        </view>
        <view class="text">
          {{ invoiceInfo.uploadTime }}
        </view>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="prods-box">
      <view
        class="shop"
        @tap="onToShopIndex(invoiceInfo.shopId)"
      >
        <view class="icon">
          <image src="/static/images/shop.png" />
        </view>
        <view class="name text-arrow">
          {{ invoiceInfo.shopName }}
        </view>
      </view>
      <view
        v-for="(item) in invoiceInfo.orderItemVOList"
        :key="item.orderItemId"
        class="prod-item"
        @tap="onToSpuDetail(item.spuId)"
      >
        <!-- 单商品 -->
        <view class="single-prod">
          <view class="prod-img">
            <img-show
              :src="item.pic"
              img-mode="aspectFit"
            />
          </view>
          <view class="text-box">
            <view class="name">
              {{ item.spuName }}
            </view>
            <view class="sku">
              <text
                v-if="item.skuName"
                class="sku-text"
              >
                {{ item.skuName }}
              </text>
              <text class="text-box-sku-item">
                x{{ item.count }}
              </text>
              <text class="text-box-sku-item">
                ￥{{ price ( item.price) }}
              </text>
            </view>
          </view>
        </view>
      </view>
      <!-- 订单信息 -->
      <view class="order-msg">
        <view class="item">
          <view class="tit">
            实付金额
          </view>
          <view
            v-if="invoiceInfo.amount"
            class="text"
          >
            ￥{{ price(invoiceInfo.amount) }}
          </view>
        </view>
        <view class="item">
          <view class="tit">
            订单状态
          </view>
          <view class="text">
            {{ ['','待付款','待发货','待收货','待收货','已完成','已取消', '待成团','','待付尾款'][invoiceInfo.orderState] }}
          </view>
        </view>
        <view class="item">
          <view class="tit">
            订单编号
          </view>
          <view class="text">
            {{ invoiceInfo.orderId }}
          </view>
        </view>
        <view class="item">
          <view class="tit">
            下单时间
          </view>
          <view class="text">
            {{ invoiceInfo.orderCreateTime }}
          </view>
        </view>
      </view>
    </view>

    <!-- 常见问题 -->
    <view class="invoice-notice">
      <view class="tit">
        常见问题
      </view>
      <view class="text">
        1、发票类型说明：默认开具电子普通发票，电子普通发票和纸质普通发票具备同等法律效力，可支持报销入账和售后维权，如需开具增值税专用发票，请与商家联系；
      </view>
      <view class="text">
        2、发票开具时间：订单确认收货后，将由商家开具，可在“个人中心 - 我的订单 - 查看发票”页面查看进度；
      </view>
      <view class="text">
        3、发票开具金额：开票金额为您实际支付金额，不包括优惠券、积分、红包等支付金额；
      </view>
      <view class="text">
        4、发票开具内容：依照税局最新开票法规，发票内容均为商品明细，将显示详细商品名称与价格信息；
      </view>
      <view class="text">
        5、发票哪里下载：订单完成后，可在“个人中心 - 我的订单 - 查看发票”页面下载发票。
      </view>
    </view>

    <!-- 底部 -->
    <view class="foot-box">
      <view class="btn-box">
        <!-- <view class="btn">咨询客服</view> -->
        <view
          class="btn"
          @tap="onShowInvoicePopup"
        >
          申请换开
        </view>
        <!-- #ifdef APP-PLUS || MP-WEIXIN -->
        <view
          v-if="filePath"
          class="btn btn-r"
          @tap="onDownloadInvoice"
        >
          下载发票
        </view>
        <!-- #endif -->

        <!-- #ifdef H5 -->
        <a
          v-if="filePath"
          class="btn btn-r"
          style="text-decoration:none;"
          target="_blank"
          rel="noopener noreferrer"
          :href="resourcesUrl+filePath"
        >下载发票</a>
        <!-- #endif -->
      </view>
    </view>
    <invoiceEdit
      v-if="isShowInvoicePopup"
      ref="invoiceAddOrUpdateRef"
      :data="invoiceEditData"
      :order-id="invoiceInfo.orderId"
      :shop-id="invoiceInfo.shopId"
      :order-invoice-id="invoiceInfo.orderInvoiceId"
      @close-popup="onClosePopup"
      @get-data="onGetInvoiceDetail"
    />
  </view>
</template>

<script setup>
import invoiceEdit from '@/package-user/components/invoice-edit/index.vue'

const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL
let orderInvoiceId = ''
const invoiceInfo = ref({})
const filePath = ref('')
const isShowInvoicePopup = ref(false) // 发票弹窗
onLoad((options) => {
  orderInvoiceId = options.orderInvoiceId
  onGetInvoiceDetail()
})

const onToSpuDetail = (spuId) => {
  uni.navigateTo({
    url: '/pages/detail/detail?spuId=' + spuId
  })
}
const onToShopIndex = (shopId) => {
  onGetShopInfo(shopId)
  // uni.navigateTo({
  //   url: '/package-shop/shop-page/shop-index?shopId=' + shopId
  // })
}
/**
   * 获取店铺信息
   */
const onGetShopInfo = (shopId) => {
  const params = {
    url: '/mall4cloud_admin/ua/shop_detail/head_info',
    method: 'GET',
    data: {
      shopId,
      imgType: 0 // 图片类型：0.app(h5) 1.pc
    }
  }
  http.request(params).then((res) => {
    uni.setStorageSync('cloudShopInfo', res)
    uni.redirectTo({
      url: res.renovationId ? '/package-shop/shop-page/feature-index/feature-index?shopId=' + res.shopId +
            '&renovationId=' + res.renovationId : '/package-shop/shop-page/shop-index/shop-index?shopId=' + shopId
    })
  })
}
// 保存发票
const onDownloadInvoice = () => {
  uni.downloadFile({
    url: resourcesUrl + filePath.value, // 文件链接
    // header: {
    //   'Authorization': uni.getStorageSync('cloudToken')
    // },
    success: (res) => {
      // statusCode状态为200表示请求成功，tempFIlePath临时路径
      if (res.statusCode === 200) {
        // 保存到本地
        uni.saveFile({
          tempFilePath: res.tempFilePath,
          success: (res) => {
            // res.savedFilePath文件的保存路径
            // 保存成功并打开文件
            uni.showToast({
              title: '发票保存成功',
              icon: 'none'
            })
            uni.openDocument({
              filePath: res.savedFilePath,
              showMenu: true,
              success: () => {
                // console.log('成功打开文档')
              }
            })
          },
          fail: () => {
            // console.log('下载失败')
          }
        })
      }
    },
    fail: () => {
      // console.log('下载失败')
    }
  })
}
const onGetInvoiceFile = () => {
  const params = {
    url: '/mall4cloud_biz/attach_file/get_file_by_id',
    method: 'GET',
    data: {
      fileId: invoiceInfo.value.fileId
    }
  }
  http.request(params).then(res => {
    filePath.value = res.filePath
  })
}
// 获取发票详情
const onGetInvoiceDetail = () => {
  const params = {
    url: '/mall4cloud_order/order_invoice',
    method: 'GET',
    data: {
      orderInvoiceId
    }
  }
  http.request(params).then(res => {
    for (let i = 0; i < res.orderItemVOList.length; i++) {
      const prodItem = res.orderItemVOList[i]
      if (prodItem.pic) {
        prodItem.pic = prodItem.pic.indexOf('http') > -1 ? prodItem.pic : resourcesUrl + prodItem.pic
      }
    }
    invoiceInfo.value = res
    if (res.fileId) {
      onGetInvoiceFile()
    }
  })
}

// 关闭弹窗
const onClosePopup = () => {
  isShowInvoicePopup.value = false
}
// 发票信息弹窗
const invoiceAddOrUpdateRef = ref(null)
const invoiceEditData = ref(null)
const onShowInvoicePopup = () => {
  invoiceEditData.value = {
    headerName: invoiceInfo.value.headerName,
    headerType: invoiceInfo.value.headerType,
    invoiceContext: invoiceInfo.value.invoiceContext,
    invoiceState: invoiceInfo.value.invoiceState,
    invoiceTaxNumber: invoiceInfo.value.invoiceTaxNumber,
    invoiceType: invoiceInfo.value.invoiceType
  }
  isShowInvoicePopup.value = true
}
const price = (value) => {
  return (value / 100).toFixed(2)
}

</script>

<style lang="scss" scoped>
@use "./invoice-detail.scss";
</style>
