<template>
  <div class="" ref="orderRef">
    <el-tabs v-model="activeName" @tab-click="tabsHandlerClick" class="no-border dark sticky-header">
      <el-tab-pane label="全部订单" name="all"></el-tab-pane>
      <el-tab-pane label="待支付" name="pay"></el-tab-pane>
      <el-tab-pane label="已完成" name="finish"></el-tab-pane>
      <el-tab-pane label="待开票" name="invoice"></el-tab-pane>
      <el-tab-pane label="历史发票" name="invoiceHistory"></el-tab-pane>
      <div v-if="activeName!='invoiceHistory'" class="order-bar rounded row">
        <div class="item" style="width: 280px !important; min-width: 280px; text-align: left;"
        :class="[activeName=='invoice'?'cursor-pointer':'']"
        @click="activeName=='invoice'?(datas.selectAll=!datas.selectAll,setSelecAll()):''">
          <el-checkbox v-if="activeName=='invoice'&&orders.length>0" class="fz14" 
          label="全选" v-model="datas.selectAll" 
          :indeterminate="datas.indeterminate"
          @click.stop=""
          @change="setSelecAll" :disabled="orders.length==0"
          style="position: relative;top: 2px;"/>
          商品信息</div>
        <div class="item col">时长</div>
        <div class="item col" >单价</div>
        <div class="item col">数量</div>
        <div class="item none-width">
          <div style="background-color: rgba(0,0,0,.08);width:1px">&nbsp;</div>
        </div>
        <div class="item col">实付款</div>
        <div class="item col">订单状态</div>
        <div class="item row items-center">
          
          <el-tooltip v-if="activeName=='invoice'&&orders.length>0"
            class="box-item"
            effect="dark"
            content="发票"
            placement="top"
          >
            <el-button link class="q-ml-md" @click="MakeOutInvoice">
              <el-icon><Printer /></el-icon>
            </el-button>
          </el-tooltip>
          <span v-else>操作</span>
        </div>
      </div>
      <div v-else class="order-bar rounded row order-InvoiceH">
        <div class="item" style="width: 180px !important; min-width: 180px; text-align: left;">
          申请时间
        </div>
        <div class="item" style="width: 200px !important; min-width: 200px;">抬头</div>
        <div class="item col" >开票金额</div>
        <div class="item col">税号</div>
        <!-- <div class="item none-width">
          <div style="background-color: rgba(0,0,0,.08);width:1px">&nbsp;</div>
        </div> -->
        <div class="item col">联系邮箱</div>
        <div class="item col">开具方式 </div>
        <div class="item row items-center">
          操作
        </div>
      </div>
    </el-tabs>

    <template v-if="activeName!='invoiceHistory'&&orders && orders.length>0 && !loading">
      <div v-loading="CancelLoading">
        <div class="order-body q-mt-lg" v-for="x in orders" :key="x.orderid">
          <div class="order-item rounded">
            <div class="title" @click="activeName=='invoice'?getCheck(x,1):''"
            :class="[activeName=='invoice'?'cursor-pointer':'']">
              <el-checkbox v-if="activeName=='invoice'" class="fz14 q-pr-md" v-model="x.check" 
                @click.stop="getCheck(x)"
                style="position: relative;top: 2px;"/>
              <span>{{ x.create }}</span>
              <span class="q-ml-md">{{ x.ordernum }}</span>
            </div>
  
            <div class="bg-white rounded row items-center">
              <div class="item row items-center"  style="width: 280px !important; min-width: 280px; text-align: left;padding:24px;">
                <img :src="x.cover" style="width:72px;" class="rounded" >
                <div class="q-ml-lg">{{ x.pricetypename }}_{{ x.vipname }}</div>
              </div>
              <div class="item col">{{ x.productname }}</div>
              <div class="item col">¥{{ x.price.toFixed(2) }}</div>
              <div class="item col">{{ x.use }}席位</div>
              <div class="item none-width">
                <div style="background-color: rgba(0,0,0,.08);width:1px;height:72px;">&nbsp;</div>
              </div>
              <div class="item col">
                <div class="text-weight-bold q-mb-sm" style="font-size: 16px">¥{{ x.price.toFixed(2) }}</div>
                <!-- <div class="row items-center flex-end">
                  <span class="text-grey-8 q-mr-md">已优惠 ¥10.00</span>
                  <IconHelp :size="16" class="cursor-pointer"></IconHelp>
                </div> -->
              </div>
              <div class="item col">
                <div class="q-mb-sm" :class="{'text-waring':x.status==1,'text-grey-8':x.status==3}">{{ x.statusname }}</div>
                <el-button  link  @click="forwardOrderDetail(x.orderid)">订单详情</el-button>
              </div>
              <div class="item column">
                <el-button type="primary" v-if="x.status==2&&!x.invoiceId" @click="MakeOutInvoice(x)">发票</el-button>
                <br />
                <el-button type="default" v-if="x.status==2" @click="redicetTo('https://work.weixin.qq.com/kfid/kfc378aada578ca8b0e')">售后</el-button>
                <el-button type="warning" v-if="x.status==1" @click="goControls(1,x.orderid)">支付</el-button>
                <br />
                <el-button type="default" v-if="x.status==1" @click="goControls(2,x.orderid)">取消</el-button>
              </div>
            </div>
  
          </div>
        </div>
      </div>
      
    </template>
    <template v-if="activeName=='invoiceHistory'&&orders && orders.length>0 && !loading">
      <div v-loading="CancelLoading">
        <div class="order-body order-InvoiceC" v-for="x in orders" :key="x.orderid">
          <div class="order-item">
  
            <div class="bg-white row items-center">
              <div class="item row items-center"  style="width: 180px !important; min-width: 180px; text-align: left;padding:24px;">
                <div>{{ x.CreateTime }}</div>
              </div>
              <div class="item" style="width: 200px !important; min-width: 200px;">
                {{ x.InvoiceTitle }}
              </div>
              <div class="item col"> 
                <div class="text-weight-bold q-mb-sm" style="font-size: 16px">¥ {{x.Money.toFixed(2)}}</div>
              </div>
              <div class="item col">{{x.InvoiceTaxNo}}</div>
              <!-- <div class="item none-width">
                <div style="background-color: rgba(0,0,0,.08);width:1px;height:72px;">&nbsp;</div>
              </div> -->
              <div class="item col">
                {{ x.Email }}
              </div>
              <div class="item col">
                {{ x.IssuedType==1?'电子普通发票':'增值税专用发票' }}
              </div>
              <div class="item">
                <el-button @click="getInvoiceDetails(x)">详情</el-button>
              </div>
            </div>
  
          </div>
        </div>
      </div>
    </template>
    <div v-if="loading" style="height: 200px;margin-top: 100px;" v-loading="loading"></div>
    <div v-if="(!orders || orders.length==0) && !loading">
      <el-empty class="q-ma-xl" description="暂无数据" />
    </div>
  </div>
  <openInvoice :show="showOpenInvoice" :InvoiceDatas="InvoiceDatas" 
  @close="showOpenInvoice=false" 
  @success="successInvoice"></openInvoice> 
  <Invoice :show="showInvoice" :InvoiceDetails="InvoiceDetails" 
  @close="showInvoice=false"></Invoice> 
</template>

<script lang="ts" setup>
import { ApiResult } from "@/configs/axios";
import OrderService from "@/services/OrderService";
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { openNewBlank } from '@/utils/common'
import WePay from '@/components/Pay/WePay.vue'
import openInvoice from './components/openInvoice.vue'
import Invoice from './components/InvoiceDetails.vue'
import { ElMessageBox } from "element-plus";

const props = defineProps({
  firm: 0 as Number,
})
const activeName = ref<string>('all')
const parameters = ref({
  pageIndex:1,
  pageSize:15,
  starttime:'',
  endtime:'',
  orderstatus:0
})
const datas = reactive({
    selectAll: false,
    indeterminate: false,// 未全选状态
})
const orders = ref<any[]>([])
const orderid = ref<Number>(0)
const count = ref(0)
const loading = ref(false)
const router = useRouter()
const showPay = ref(false)
const orderRef = ref<any>()
const CancelLoading = ref(false)
const showOpenInvoice = ref(false)
const showInvoice = ref(false)
const InvoiceDatas = reactive({
  total: 0,
  Ids: [],
  orderid: [],
  isMore: 0,
} as any)
const InvoiceDetails = ref({})

const getInvoiceDetails = (item:any) => {
  InvoiceDetails.value = item
  showInvoice.value = true
}

const successInvoice = () => {
  showOpenInvoice.value = false
  datas.selectAll = false
  datas.indeterminate = false
  InvoiceDatas.Ids = []
  InvoiceDatas.orderid = []
  search()
}

const MakeOutInvoice = (item:any) => {
  SumUp()
  if(item&&item.orderid){
    InvoiceDatas.orderid = []
    InvoiceDatas.isMore = 0
    InvoiceDatas.total = item.price
    InvoiceDatas.orderid.push(item.orderid)
  }else{
    InvoiceDatas.isMore = 1
    if(InvoiceDatas.Ids.length==0) return ElMessage.warning({
        showClose: true,
        message: `请勾选需要发票的数据`,
      })
    
  }
  showOpenInvoice.value = true
}

const getCheck = (item:any,type:any) => {
  if(type) item.check = !item.check
  let filter = InvoiceDatas.Ids.filter(x=>x==item.orderid)
  if(filter.length==0&&(!item.check||item.check)) {
    InvoiceDatas.Ids.push(item.orderid)
  }else {
    let newIds = InvoiceDatas.Ids.filter(x=>x!=item.orderid)
    InvoiceDatas.Ids = newIds
  }
  CheckStatus() 
}

const CheckStatus = () => {
  if(InvoiceDatas.Ids.length==0) {
    datas.selectAll = false
    datas.indeterminate = false
  }else if(InvoiceDatas.Ids.length>0){
    if(orders.value.length==InvoiceDatas.Ids.length){
      datas.selectAll = true
      datas.indeterminate = false
    }else if(orders.value.length>InvoiceDatas.Ids.length){
      datas.selectAll = false
      datas.indeterminate = true
    }
  }
}

const setSelecAll = () => {
  if(datas.selectAll||datas.indeterminate) {
    InvoiceDatas.Ids = orders.value.map(x=>{return x.orderid})
    orders.value.forEach(y=>{
      y.check = true
    })
    if(datas.indeterminate) datas.selectAll = true
    datas.indeterminate = false
  }else {
    orders.value.forEach(y=>{
      y.check = false
    })
    InvoiceDatas.Ids = []
    datas.indeterminate = false
  }
}

const SumUp = () => {
  if(InvoiceDatas.Ids.length>0){
    let total = 0
    for(let i=0;i<orders.value.length;i++){
      let filter = InvoiceDatas.Ids.filter(x=>x==orders.value[i].orderid)
      if(filter.length>0) total+=(orders.value[i].price*100)
    }
    InvoiceDatas.total = total/100
  }
}

const newDatasSelected = () =>{
    if(InvoiceDatas.Ids.length==0) {
      for(let i=0;i<orders.value.length;i++){
        orders.value[i].check = false
      }
      datas.selectAll = false
      datas.indeterminate = false
    }else if(InvoiceDatas.Ids.length>0){
      if(orders.value.length==InvoiceDatas.Ids.length){
        for(let i=0;i<orders.value.length;i++){
          orders.value[i].check = true
        }
        datas.selectAll = true
        datas.indeterminate = false
      }else if(orders.value.length>InvoiceDatas.Ids.length){
        for(let i=0;i<orders.value.length;i++){
          let x = orders.value[i]
          let findObj = InvoiceDatas.Ids.find(y=> y==x.orderid)
          if(findObj) orders.value[i].check = true
        }
        datas.selectAll = false
        datas.indeterminate = true
      }
    }
  }

const goControls = (type:Number,id:any) => {
  orderid.value = id
  if(type==1) showPay.value = true
  else if(type==2) {
    ElMessageBox.confirm(
        `此操作将取消该订单，是否确定?`,
        "提示",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
        .then(async () => {
            try {
              await CanceltOrders()
            } catch (error) { }
        })
        .catch(() => { });
  }
}
const CanceltOrders = async ()=>{
  if(CancelLoading.value)return
  CancelLoading.value=true
  const response = await OrderService.CancelPPTOrder(orderid.value)
  if(response.data.resultCode == ApiResult.SUCCESS){
    await search()
  }

  CancelLoading.value=false
}
const redicetTo = (url:string)=>openNewBlank(url)
  
const tabsHandlerClick = (e:any)=>{
  activeName.value = e.props.name
  if(e.props.name=='all') parameters.value.orderstatus = 0
  if(e.props.name=='pay') parameters.value.orderstatus = 1
  if(e.props.name=='finish') parameters.value.orderstatus = 2
  if(e.props.name=='invoice') parameters.value.orderstatus = 4
  if(e.props.name=='invoiceHistory') searchHistorical()
  else search()
  
}

const searchHistorical = async () => {
  orders.value = []
  parameters.value.pageIndex=1
  await HistoricalInvoice()
}
const HistoricalInvoice = async () => {
  const response = await OrderService.GetPPTUserInvoicePage(parameters.value.pageIndex,parameters.value.pageSize)
  if(response.data.resultCode == ApiResult.SUCCESS){
    orders.value = response.data.data.pageData
    count.value = response.data.data.pageCount
  }
}

const search = async () => {
  parameters.value.pageIndex=1
  await getOrders()
}
const getOrders = async ()=>{
  if(loading.value)return
  loading.value=true

  const response = await OrderService.GetOrders(parameters.value)
  if(response.data.resultCode == ApiResult.SUCCESS){
    let arrList = function(list){
      list.forEach(x=>{
        x.check = false
      })
    }
    arrList(response.data.data.pageData)
    orders.value = response.data.data.pageData
    count.value = response.data.data.pageCount
    
  }

  loading.value=false
  if(parameters.value.orderstatus==4){
    newDatasSelected()
  }
}

const scrollingHandler = () =>{
    if(orderRef.value && !loading.value){
        let maxHeight = orderRef.value.scrollHeight - orderRef.value.offsetHeight
        let scrollTop = orderRef.value.scrollTop
        if(maxHeight - scrollTop==0 && parameters.value.pageCount > parameters.value.pageIndex) {
          parameters.value.pageIndex++
          if(activeName.value=='invoiceHistory') HistoricalInvoice()
          else getOrders()
        }
    }
    
}

const forwardOrderDetail = (id:string)=>{
  if(props.firm) router.push('/u/order/'+encodeURIComponent(id)+'/'+props.firm)
  else router.push('/u/order/'+encodeURIComponent(id))
}

getOrders()
onMounted(()=>{
    orderRef.value.addEventListener("scroll", scrollingHandler);
})
</script>

<style scoped>
.sticky-header{
  position: sticky;
  top: 0;
  left: 0;
  background: #FFF;
}
.order-bar{
  background: #f6f7f9 !important;
}
.order-bar .item,
.order-body .order-item .item{
  padding: 0 24px;
  height: 42px;
  line-height: 42px;
  font-size: 14px;
  color:gray;
  text-align: right;
  min-width: 108px;
}
.order-bar .item.none-width,
.order-body .order-item .item.none-width{
  min-width: unset;
}
.order-body{

}
.order-body .order-item{
  background: #f6f7f9;
  border:1px solid rgba(0,0,0,.08);
  font-size: 14px;
  
}
.order-body .order-item .title{
  padding: 0 24px;
  height: 45px;
  line-height: 45px;
  color:grey;
  white-space: nowrap;
  overflow: hidden;
}
.order-body .order-item .item{
  height: auto;
  line-height: 1;
  color: #000;
  white-space: nowrap;
  overflow: hidden;
}
.order-body.order-InvoiceC .order-item{
  border: 0;
  border-bottom: 1px solid rgba(0,0,0,.08);
}
.order-bar.order-InvoiceH .item, .order-body.order-InvoiceC .order-item .item{
  text-overflow: ellipsis;
}
.order-bar.order-InvoiceH .item,.order-body.order-InvoiceC .order-item .item{
  text-align: left;
}
</style>