<template>
    <view class="time-root">
      <!-- 选择平台 -->
      <!-- <picker
        @change="handleVendorChange"
        range-key="vendorStoreName"
        :range="vendorArr"
      >
        <view class="select-root" style="width: 60rpx;">
          <text class="all-text">{{ vendorArr[+pickValue].vendorStoreName }}</text>
        </view>
      </picker> -->
  
      <view class="slect-edit">
          <picker
            :value="fromTime"
            mode="date"
            @change="fnChangeFrom"
            :end="timeFormatD(+new Date())"
          >
            <view class="time-item">
              <jx-icon
                icon="xiangzuojiantou"
                :size="28"
                color="#919191"
              ></jx-icon>
              <text>{{ fromTime }}</text>
              <jx-icon
                icon="xiangyoujiantou"
                :size="28"
                color="#919191"
              ></jx-icon>
            </view>
          </picker>
          <text class="middle-text">至</text>
          <picker
            :value="toTime"
            mode="date"
            @change="fnChangeTo"
            :end="timeFormatD(+new Date())"
          >
            <view class="time-item">
              <jx-icon
                icon="xiangzuojiantou"
                :size="28"
                color="#919191"
              ></jx-icon>
              <text>{{ toTime }}</text>
              <jx-icon
                icon="xiangyoujiantou"
                :size="28"
                color="#919191"
              ></jx-icon>
            </view>
          </picker>
    
      </view>
      <button size="mini" class="query-button" @tap="queryInvoice" style="height: 50rpx;line-height: 50rpx;font-size: 30rpx;">查询</button>
    </view>
      
    <view style="margin-top: 20px;">
      <view v-for="(item,index) in invoiceList" :key="index" style="margin-bottom: 20px;border: 1rpx solid #eee;box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 12px 0px;">
        <view  class="order-id pd20" >
          <view class="id" style="margin-left: 10rpx;">
            订单号:{{ item.order_id }}
            <jx-icon
              icon="fuzhi"
              :size="40"
              color="#777777"
              @tap.stop="
                copyOrderNum(
                  item.order_id
                )
              "
            ></jx-icon>
          </view>
          <!-- <view class="time">{{ item.createdAt }}</view>  :disabled="item.invoiceId"-->
           <button size="mini" class="uploadBut" @tap.stop="uploadInvoive(item)" style="height: 50rpx;line-height: 50rpx;font-size: 30rpx;">上传发票</button>
        </view>
        <view style="border: 0;margin-left: 10rpx;">
          <view style="margin-top: 10px;" >创建时间：{{ item.createdAt }}</view>
          <view>发票任务id:{{ item.invoiceTaskId }}</view>
        </view>
       
      </view>
    </view>
       
    <!-- 饿百 -->
    <view v-for="(item,index) in invoiceListEB" :key="index" style="margin-bottom: 20px;border: 1rpx solid #eee;box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 12px 0px;">
      <view class="order-id pd20">
        <view class="id" style="margin-left: 10rpx;">
          订单号:{{ item.order_list.order_id }}
          <jx-icon
            icon="fuzhi"
            :size="40"
            color="#777777"
            @tap.stop="
              copyOrderNum(
                item.order_list.order_id
              )
            "
          ></jx-icon>
        </view>
        <view style="border: 0;margin-left: 10rpx;">
          <view>建议开票金额：{{ item.order_list.invoice_amount }}</view>
          <view>抬头类型：{{ item.buyer_title.title_type === 'PERSONAL' ? '个人' : item.buyer_title.title_type === 'ENTERPRISE' ? '企业' : item.buyer_title.title_type === 'GOVERNMENT' ? '政府' :'未知' }}</view>
          <view>抬头名称：{{ item.buyer_title.title_name }}</view>
          <view>纳税人识别号：{{ item.buyer_title.tax_payer_num }}</view>
          <view>注册地址：{{ item.buyer_title.register_address }}</view>
          <view>注册电话：{{ item.buyer_title.register_phone }}</view>
          <view>开户行名称：{{ item.buyer_title.bank_name }}</view>
          <view>开户行账号：{{ item.buyer_title.bank_account }}</view>
          <view>申请编号：{{ item.application_no }}</view>
          <view>发票材质：{{ item.invoice_material === 'PAPER' ? '纸质发票' : '电子发票' }}</view>
          <view>发票种类：{{ item.invoice_class === 'VAT_COMMON' ? '普通发票' : '专用发票' }}</view>
          <view>申请状态：{{ item.status }}</view>
          <view>发票任务id: {{ item.invoiceTaskId }}</view>
          <view>开票总金额: {{ item.total_invoice_amount }}</view>
          <view>开票总金额: {{ item.total_invoice_amount }}</view>
          <view>创建时间: {{ (new Date(item.order_list.create_time)) }}</view>
          <view>用户联系人邮箱: {{ item.buyer_contact.email }}</view>
        </view>
        
      </view>
    </view>


    <uni-popup ref="popupDialog" type="top">
      <view class="jx-popup-update" >
        <view class="text">上传发票（美团）</view>
        <view class="tip-new">订单号：{{ currentInvoiceItem.order_id }}</view>
        <view class="ipt-box">
          <input
            class="ipt"
            :type="'number'"
            v-model="invoiceId"
            :placeholder="'请输入发票号码'"
            placeholder-style="font-size:30rpx"
            :cursor-spacing="0"
            style="font-size: 30rpx;"
          />
          <!-- 上传图片 -->
          <jx-upload-img
            :title="'发票图片:'"
            :type="'invoiceImg'"
            :img="invoiceImg"
            @imgChange="imgChangeInvoice"
          ></jx-upload-img>
  
        </view>
        <view class="btn-root">
          <view class="btn-esc" @tap="popupDialog.close()">取消</view>
          <view class="btn-ok" @tap="sureStockOrCode">确定</view>
        </view>
      </view>
    </uni-popup>
  
    <!-- 公共组件 -->
    <jx-loading />
  
  </template>
  
  <script lang="ts" setup>
  import { store } from '@/store'
  import { onLoad, onShow } from '@dcloudio/uni-app';
  import order from '@/api/https/order'
  import { getStorage } from '@/utils/storage';
  import { ref } from 'vue';
  import { clearList, timeFormatD } from "@/utils/tools";
  import toast from '@/utils/toast';
  import merchant from '@/api/https/merchant';
  import { qiniuyun } from '@/utils/qiniuUploader';
  
  // console.log('store',store)
  
  const fromTime = ref(`${timeFormatD(+new Date() - 7 * 24 * 60 * 60 * 1000)}`)
  const toTime = ref(`${timeFormatD()}`)
  const invoiceList =  ref<Array<AnyObject>>([])  // 美团发票列表
  const invoiceListEB =  ref<Array<AnyObject>>([])  // 美团发票列表
  const popupDialog = ref<any>(null)
  const currentInvoiceItem = ref<AnyObject>({})
  const invoiceId =  ref('')  // 发票id
  const invoiceImg = ref('')  // 发票图片地址
  const qiniuyunUploadImg = qiniuyun()        // 七牛云sdk
  
  
  onLoad(async() => {
    if(store.getters['storeInfo/imMtStatus'] && store.getters['storeInfo/imMtStatus'].length>0) queryInvoice('mt') // 存在美团门店

    if(store.getters['storeInfo/platformInfo'] && store.getters['storeInfo/platformInfo'].length>0){
      let findItem = store.getters['storeInfo/platformInfo'].filter((item:AnyObject) => item.vendorID === 3)
      if(JSON.stringify(findItem) !== '{}') queryInvoice('eb',findItem[0])
    }
})
  
//   uni.getSystemInfoSync().platform == 'ios'
  
  
  /**
   * 上传发票图片
   */
  const imgChangeInvoice = (data: AnyObject) => {
      // 删除
      if (data.type == 'delet') {
          invoiceImg.value = ''
      }
      // 上传
      if (data.type == 'upload') {
          uploadImg(data, 'licence')
      }
  }
  
  const uploadUrl = ref<string>('https://image.jxc4.com/')
  async function uploadImg(data: AnyObject, img: string) {
        let suffix = data.img.indexOf('.png') === -1 ? '.jpg' : '.png'
        let params = {
            suffix
        }
        let res = await merchant.get_qiniu_upload_token(params)
        if (res.code == 0) {
            let filePath = data.img
            qiniuyunUploadImg.upload(
                filePath,
                (res: any) => {
                    // 得到图片网址
                    let imgUrl = uploadUrl.value + res.key
                    // imgUrls.value[img] = imgUrl
                    invoiceImg.value = imgUrl
  
                },
                (err: AnyObject) => {
                    toast('上传失败，请重试', 2)
                },
                {
                    uploadURL: 'https://up-z2.qiniup.com/',
                    key: res.data.fileName,
                    uptoken: res.data.token,
                }
            )
        } else {
            toast('上传失败', 2)
        }
    }
  
  
  /**
   * 上传发票打开弹框
   */
  const uploadInvoive = (item:AnyObject) => {
    currentInvoiceItem.value = item
    popupDialog.value.open()
  }
  
  /**
   * 上传发票 确认弹框
   */
  const sureStockOrCode = async () =>{
    try {
      if(!invoiceId.value) return toast('请输入发票id')
      if(!invoiceImg.value) return toast('请上传发票图片')
      
      let obj = {
        orderId:currentInvoiceItem.value.order_id,
        invoiceId:invoiceId.value,
        invoiceUrl:invoiceImg.value
      }
      let res = await order.upload_invoice_img(obj)
      toast('上传成功', 1)
    } catch (error) {
      toast('系统异常')
    }
  }
  
  
  /**
   * 复制订单号
   */
   function copyOrderNum(orderNum: string) {
    uni.setClipboardData({
      data: orderNum,
      success() {
        toast('复制订单号成功', 1)
      },
    })
  }
  
  
   /*************************************************
       * 自定义开始日期
       */
       function fnChangeFrom(e: AnyObject) {
          fromTime.value = e.detail.value
      }
      // 自定义结束时间
      function fnChangeTo(e: AnyObject) {
          toTime.value = e.detail.value
      }
  
      
  /**
   * 查询发票信息
   */
  const queryInvoice = async (type:string,ebStore?:any) => {
    if(type === 'mt'){
      let data:AnyObject = {
          storeId: getStorage('storeID'),
          startTime: fromTime.value + ' 00:00:00',
          endTime:toTime.value + ' 23:59:59',
          pageSize: -1,
          offset: 0
      }
      let res = await order.query_mt_invoice(data)
      if(res.code === '0') invoiceList.value = res.data.data
    }else if(type === 'eb'){
      let res = await order.get_invoice_info({
          vendorId:'3',
          vendorStoreID:'' + ebStore.vendorStoreID,
          storeID:+ebStore.storeID
      })
      if(res.code === '0') invoiceListEB.value = res.data.record_list
    }
  }
  </script>
  
  <style lang="scss" scoped>
      .time-root {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 15rpx 0;
            background-color: #fafafa;
            border-top: 1rpx solid #e2e2e2;
            border-bottom: 1rpx solid #e2e2e2;
            font-size: 28rpx;
            color: #919191;
            padding: 10rpx 5rpx;
  
            .slect-edit {
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  padding: 0 20rpx;
                  width: 100%;
  
                  .time-item {
                      display: flex;
                      align-items: center;
                      background-color: #e6e6e6;
                      padding: 10rpx 20rpx;
                      border-radius: 10rpx;
                  }
  
                  button {
                      background-color: $jx-primary;
                      color: #fff;
                      margin: 0;
                  }
            }
      }
  
      .query-button{
        background-color: #4eb331;
        color: #fff;
        margin: 0;
        width: 160rpx;
        // width: fit-content;

      }
  
      .uploadBut{
        background-color: #4eb331;
        color: #fff;
        margin: 0;
        // width: 168rpx;
        width: fit-content;
        margin-right: 20rpx;
      }
  
      .select-root {
        display: flex;
        justify-content: space-between;
        background-color: #fff;
        padding: 10rpx 20rpx;
        margin-bottom: 20rpx;
  
        .all-text {
            font-weight: bold;
        }
  
        .slect-text {
            color: $jx-primary;
            text-decoration: underline;
        }
      }
  
      .order-id {
          background: rgba(207, 228, 125, 0.2);
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 80rpx;
  
          .id {
              font-size: 30rpx;
              color: #333;
              font-weight: 400;
          }
  
          .time {
              font-size: 24rpx;
              color: #999;
              font-weight: 400;
          }
      }
  
      .jx-popup-update {
        box-sizing: border-box;
        padding: 20rpx;
        background-color: #fff;
        border-radius: 0 0 15rpx 15rpx;
  
        .text {
            display: block;
            width: 100%;
            text-align: center;
            margin-bottom: 25rpx;
            padding-bottom: 10rpx;
            border-bottom: 2rpx solid rgb(209, 209, 209);
        }
  
        .tip-new{
            padding: 2rpx 0;
            height: 66rpx;
            line-height: 66rpx;
            text-align: left;
            border-bottom:1px dashed #999;
  
            .money {
                color: $jx-primary;
            }
        }
        
        .ipt-box{
            margin: 10rpx 0;
            // height: 86rpx;
            // line-height: normal;
          }
  
        .tip {
            padding: 10rpx 0;
  
            .money {
                color: $jx-primary;
            }
        }
  
        .ipt {
            border: 2rpx solid rgb(209, 209, 209);
            text-align: center;
            border-radius: 5rpx;
            height: 86rpx;
            line-height: normal;
            // -webkit-appearance: none;
            // border-radius: 0
        }
  
        .title {
            width: 100%;
            text-align: center;
            margin-bottom: 20rpx;
        }
  
        .btn-root {
            display: flex;
            justify-content: space-between;
            margin: 40rpx 0 0rpx 0;
  
            .btn-esc,
            .btn-ok {
                text-align: center;
                width: 100%;
                padding: 15rpx 0;
                border-radius: 10rpx;
                border: 2rpx solid $jx-primary;
                color: $jx-primary;
            }
  
            .btn-ok {
                background-color: $jx-primary;
                color: #fff;
                margin-left: 10rpx;
            }
  
            .btn-esc {
                margin-right: 10rpx;
            }
        }
        
        .delete {
            margin-top: 50rpx;
            margin-bottom: 20rpx;
            background-color: $jx-warring;
            text-align: center;
            color: #fff;
            padding: 20rpx;
            border-radius: 15rpx;
        }
    }
  </style>