<template>
  <PageLayout>
    <template #header-right>
      <q-btn flat dense label="派奖记录" :to="{path:'/order/sendprize/history',query:{t:Date.now()}}" />
    </template>
    <infinite-scroll :load="load" :list="list" ref="scrollRef">
      <!-- DELAY 暂无合作派奖 -->
      <!-- <template #prepend>
        <div class="q-px-md q-pb-sm bg-white">
          <q-tabs
            v-model="form.filter"
            no-caps
            dense
            square
            active-bg-color="primary"
            active-color="white"
            indicator-color="primary"
            class="text-primary tabs-button text-body3"
          >
            <template v-for="(item, i) in filters" :key="i">
              <q-separator
                v-if="i != 0"
                vertical
                size="0.5px"
                color="primary"
              />
              <q-tab :name="item.filter" class="col-4 q-px-none">
                {{ item.name }}
              </q-tab>
            </template>
          </q-tabs>
        </div>
      </template> -->
      <template v-slot="{ item,index }">
        <q-item
          class="bg-white q-mt-sm q-pl-sm"
          :to="{ path: '/order/' + item.order_sn }"
        >
          <q-item-section side class="q-px-xs">
            <q-checkbox v-model="selected" :disable="batching" :val="item.order_sn" checked-icon="check_circle" unchecked-icon="panorama_fish_eye" />
          </q-item-section>
          <q-item-section avatar>
            <img width="42" :src="'/statics/lottery/' + item.lottery_type?.type + '.png'"/>
          </q-item-section>
          <q-item-section>
            <q-item-label>{{ item.lottery_type.name }}<q-badge v-if="item.shop_cooperate_id>0" color="accent" outline class="q-ml-xs">合作</q-badge></q-item-label>
            <q-item-label class="text-grey" caption="">
              出票时间{{ item.draft_at }}
            </q-item-label>
            <q-item-label class="text-red" caption="">
              派奖金额：{{ formatMoney(item.lottery_should_send_prize) }}
              <!-- <q-btn v-if="store.user.enable_send_prize==1" outline color="red" label="修改奖金" /> -->
            </q-item-label>
          </q-item-section>
          <q-item-section side v-if="store.user.enable_send_prize==1">
            <q-item-label class="text-red">
              <q-btn color="primary" unelevated label="派奖" @click.prevent.stop="sendPrize(item,index)" />
            </q-item-label>
          </q-item-section>
        </q-item>
      </template>
    </infinite-scroll>
    <template #footer>
      <q-footer class="bg-white text-dark row justify-between items-center q-pl-sm">
        <q-checkbox v-model="selectedAll"
        indeterminate-value="maybe"
        :true-value="true"
        :false-value="false"
        checked-icon="check_circle"
        unchecked-icon="panorama_fish_eye"
        indeterminate-icon="remove_circle"
        label="全选" />
        <div class="">
          合计：{{ formatMoney(totalPrize) }}
          <q-btn @click="batchSendPrize"
          color="primary"
          :disable="selected.length==0 || batching"
          unelevated square class="q-py-sm q-ml-sm q-px-lg">派奖</q-btn>
        </div>
      </q-footer>
    </template>
  </PageLayout>
</template>
<script setup>
import { ref, onMounted, reactive, watch, shallowReactive,computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useSelfStore } from "stores/self";
import { api } from "boot/axios";
import { useQuasar } from "quasar";
import { LOTTERY_STATE } from "src/utils/const";
import { Rules,formatMoney} from 'src/utils/tools'
import { useInfiniteScroll } from 'src/composables/infiniteScroll';
const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const store = useSelfStore();

const filters = shallowReactive([
  {
    filter: "feat_instore",
    name: "店内派奖"
  },
  {
    filter: "2",
    name: "合作派奖(出票)"
  },
  {
    filter: "3",
    name: "合作派奖(派单)"
  }
]);

// api.getOrderFilterOptions().then(res=>{
//   res.filter.forEach((item,i)=>{
//     filters[i] = item
//   })
// })

const showSearch = ref(false);
const form = reactive({
  filter:'feat_instore',
});
const { list, refresh, load,scrollRef }  = useInfiniteScroll((page)=>{
  return api
    .getWinOrderList({
      page
    })
})
// setTimeout(()=>{
//   list.push({lottery_type:{},order_sn:1})
//   list.push({lottery_type:{},order_sn:2})
// },3000)
watch(()=>{
  return form.filter
}, refresh);

function sendPrize(item,index){
  $q.dialog({
    cancel: true,
    title:`派奖确认`,
    message:'请确认派奖金额',
    prompt: {
      model: formatMoney(item.lottery_should_send_prize),
      type: "number",
      isValid: Rules.required
    }
  }).onOk((val) => {
    $q.loading.show()
    api.sendPrize({order_sn:item.order_sn, prize : val }).then((res) => {
      $q.notify({ type: "positive", message: res.message || '派奖成功！' });
      list.splice(index, 1)
      // list[index].lottery_send_prize = val
    })
    .catch((e) => {
      $q.notify({ type: "negative", message: e.message });
    }).finally(()=>{
      $q.loading.hide()
    });
  });
}
const selected = ref([])
const selectedAll = computed({
  get: () => {
    if(selected.value.length == 0){
      return false
    }
    if(selected.value.length == list.length){
      return true
    }
    return null
  },
  set: (val) => {
    selected.value = val?list.map(item=>item.order_sn):[]
  }
})
const prizeMap = computed(()=>{
  return list.reduce((total,item,index)=>{
    total[item.order_sn] = {index,prize:item.lottery_should_send_prize*1,title:item.lottery_type.name}
    return total
  },{})
})
const totalPrize = computed(()=>{
  return selected.value.reduce((total,item)=>{
    return total + prizeMap.value[item].prize
  },0)
})

const batching = ref(false)
function batchSendPrize(){
  $q.loading.show()
  batching.value = true
  let arr = selected.value.map((item,i)=>{
    return api.sendPrize({order_sn:item, prize : prizeMap.value[item].prize }).then((res) => {
      return {
        order_sn: item,
        status: true
      }
    }).catch(e=>{
      return {
        order_sn: item,
        status: false,
        error:e.message
      }
    })
  })
  Promise.all(arr).then((res)=>{
    let error = []
    res.forEach((item)=>{
      let data = prizeMap.value[item.order_sn]
      if(item.status){
        list.splice(data.index, 1)
        selected.value.splice(selected.value.indexOf(item.order_sn),1)
      }else{
        error.push(data.title+"派奖¥"+data.prize+"："+item.error)
      }
    })
    $q.notify({
      type: error.length?'negative':"positive",
      message: error.length?(error.length+'条派奖失败!<br/>'+error.join('<br/>')):'派奖成功！',
      html: true
    });
    batching.value = false
  }).finally(()=>{
    $q.loading.hide()
  })
}
</script>
<style lang="scss" scoped></style>
