<template>
  <!-- [ ] "lottery_is_wined": true, // true中奖；false未中奖 -->
  <page-layout :loading="loading">
    <template #header-title v-if="!props.isSelfBuyPlan">
      订单详情 - {{ info.lottery_type?.name }}{{ ORDER_TYPE[info.type] }}
    </template>
    <div v-if="info.cooperate" class="q-pa-md row bg-primary text-center text-white items-center">
      <div class="col">
        <div class="text-h6 ellipsis">{{ info.shop?.name }}</div>
        <div class="text-caption text-teal-2 ellipsis">
          <a v-if="info.shop.id!=store.shop.id" :href="'tel:'+info.shop?.seller_phone" class="row flex-center ellipsis no-wrap">
            <q-icon name="phone"></q-icon>{{ info.shop?.seller_phone }}</a>
          <template v-else>{{ info.shop?.seller_phone }}</template>
        </div>
      </div>
      <div class="col-auto q-px-md relative-position">
        <q-separator color="teal-2" class="absolute-center full-width" size="0.5px"/>
        <div class="text-caption text-teal-2 inline bordered relative-position rounded-borders-xs q-px-xs bg-primary">合作出票</div>
      </div>
      <div class="col">
        <div class="text-h6 ellipsis">{{ info.cooperate.name }}</div>
        <div class="text-caption text-teal-2  ellipsis">
          <a v-if="info.cooperate.id!=store.shop.id" :href="'tel:'+info.cooperate?.seller_phone" class="row flex-center ellipsis no-wrap">
            <q-icon name="phone"></q-icon>{{ info.cooperate?.seller_phone }}</a>
          <template v-else>{{ info.cooperate?.seller_phone }}</template>
        </div>
      </div>
    </div>
    <div class="q-px-md q-py-sm">
      <div class="row q-gutter-md items-stretch">
        <div class="col">
          <div class="bordered-grey fit bg-white text-center q-pa-xs">
            <div class="text-red text-weight-bold">{{ formatMoney(info.money) }}元</div>
            <div class="text-grey-7 text-caption">方案金额</div>
          </div>
        </div>
        <div class="col">
          <div class="bordered-grey fit bg-white text-center q-pa-xs">
            <div class="text-weight-bold">
              {{ LOTTERY_STATE[info.lottery_state] || "—" }}
            </div>
            <div class="text-grey-7 text-caption">方案状态</div>
          </div>
        </div>
        <div class="col">
          <div class="bordered-grey fit bg-white text-center q-pa-xs">
            <div class="text-primary text-weight-bold">
              <template
                v-if="info.lottery_state == 1 || info.lottery_state == 7"
              >
                {{ formatMoney(info.lottery_tax_prize) }}元
              </template>
              <template v-else>—</template>
            </div>
            <div class="text-grey-7 text-caption">税后奖金</div>
          </div>
        </div>
      </div>
    </div>
    <div
      v-if="info.lottery_state == 6"
      class="q-mx-md q-mb-sm bg-orange-2 q-pa-xs rounded-borders-xs"
    >
      <div class="text-deep-orange q-pa-sm">店主撤单原因</div>
      <div class="bg-white q-pa-sm rounded-borders-xs">{{ info.revoke_message }}</div>
    </div>
    <div class="bg-white">
      <template v-if="!info.sellings?.length">
        <div class="q-mx-md q-py-sm">
          <span class="q-pr-sm">方案内容</span>
        </div>
        <q-separator />
        <div
          class="column items-center justify-center q-py-md text-grey-7 text-caption"
        >
          <q-avatar
            icon="lock"
            size="54px"
            color="grey-2"
            text-color="grey"
            class="q-mb-sm"
          />
          接单后显示订单详细信息
        </div>
      </template>
      <template v-else>
        <div class="q-px-md q-py-xs">
          <div class="text-subtitle text-weight-bold">
            {{ info.lottery_type?.name }}
            <span v-if="info.play_type_name && info.play_type_name!=info.lottery_type?.name" class="q-ml-sm">{{ info.play_type_name }}</span>
            <span v-if="!isNumberTottery(info.lottery_type.type) && info.issue_num" class="q-ml-sm">第{{ info.issue_num }}期</span>
            <span v-if="info.optimize_type" class="text-red q-ml-sm">{{ OPTIMIZE_TYPE[info.optimize_type] }}</span>
            <span v-if="info.enable_add" class="text-red q-ml-sm">追加投注</span>
          </div>
          <template v-if="isNumberTottery(info.lottery_type.type)">
            <div>
              <span class="q-pr-sm text-caption text-grey">投注信息：</span>
              <span class="text-primary text-weight-bold">第{{ info.issue_num }}期</span>
              <span v-if="info.piao_num>0" class="text-primary text-red text-weight-bold q-ml-sm">{{ info.piao_num }}张</span>
            </div>
            <div v-if="info.dlt && info.dlt.qian && info.dlt.hou">
              <span class="q-pr-sm text-caption text-grey">本期开奖：</span>
              <span class="text-red text-weight-bold">{{ info.dlt.qian.join(' ') }}</span>
              <span class="text-blue text-weight-bold q-ml-sm">{{ info.dlt.hou.join(' ') }}</span>
            </div>
            <div v-else-if="info[info.lottery_type.type]?.result">
              <span class="q-pr-sm text-caption text-grey">本期开奖：</span>
              <span class="text-red text-weight-bold">{{ info[info.lottery_type.type].result.join?.(' ') }}</span>
            </div>
          </template>
          <template v-else>
            <div>
              <span class="q-pr-sm text-caption text-grey">场数/过关：</span>
              <span class="text-primary text-weight-bold">{{ info.sellings?.length }}场</span>
              <span class="text-red text-weight-bold q-py-sm q-ml-sm"
                v-for="(mode, i) in info.pass_mode_name"
                :key="i"
                outline
                color="red"
                >{{ mode }}</span>
            </div>
            <div>
              <span class="q-pr-sm text-caption text-grey">注数/倍数<span v-if="info.piao_num>0">/票数</span>：</span>
              <span class="text-primary text-weight-bold">{{ info.zhu_num }}注</span>
              <span class="text-red text-weight-bold q-ml-sm">{{ info.bets_num }}倍</span>
              <span v-if="info.piao_num>0" class="text-primary text-weight-bold q-ml-sm">{{ info.piao_num }}张</span>
            </div>
          </template>
        </div>
        <SellingsTable :sellings="info.sellings" :lottery="info.lottery_type" :win="info[info.lottery_type.type]" />
        <div v-if="info.prize_max>0 && isVieTottery(info.lottery_type.type) && !info.optimize_type" class="text-center q-pa-sm">
          预计最高奖金：<span class="text-red">{{ formatMoney(info.prize_max) }}</span>元
        </div>
        <div class="text-center q-pa-sm" v-if="enableTickets">
          <q-btn
            outline
            dense
            color="primary"
            class="q-px-md"
            @click="showTickets = true"
            >查看拆票明细</q-btn
          >
        </div>
      </template>
    </div>
    <div
      class="bg-white q-mt-sm q-px-md q-py-sm"
      v-if="info.lottery_state == 4 || (info.button_qupiao && info.lottery_take_ticket != 1 && (
          info.lottery_state == 1 ||
          info.lottery_state == 2 ||
          info.lottery_state == 3 ||
          info.lottery_state == 7))"
    >
      <div class="row justify-between items-center">上传图片
        <q-btn v-if="info.button_qupiao && info.lottery_take_ticket != 1 && (
          info.lottery_state == 1 ||
          info.lottery_state == 2 ||
          info.lottery_state == 3 ||
          info.lottery_state == 7)"
          unelevated
          dense
          :disable="!materials.length || store.user.enable_work == 0"
          color="primary"
          class="q-px-sm"
          @click="modifyTickets"
          >重新上传票据</q-btn>
      </div>
      <div
        class="row q-col-gutter-sm wrap q-pt-sm text-grey items-center justify-start"
      >
        <UploadFile
          :multiple="false"
          url="seller/material/upload"
          accept="image/*"
          field-name="lottery"
          flat
          square
          class="col-auto"
          @uploaded="uploaded"
        >
          <template #header-content>
            <div
              class="bordered row flex-center"
              style="width: 80px; height: 80px"
            >
              <q-icon size="32px" name="file_upload" />
            </div>
          </template>
        </UploadFile>
        <div v-for="(item, i) in materials" class="relative-position" :key="i">
          <q-img
            class="bordered col-auto"
            no-spinner
            width="80px"
            height="80px"
            :src="item.file_url"
          >
          </q-img>
          <q-btn
            class="absolute"
            style="top: 0; right: -5px"
            size="6px"
            icon="clear"
            round
            unelevated
            color="grey"
            @click="materials.splice(i, 1)"
          ></q-btn>
        </div>
      </div>
    </div>
    <q-list separator class="bg-white q-mt-sm q-mb-lg">
      <q-item
        v-if="info.customer"
        :to="{ path: '/customer/' + info.customer_id }"
      >
        <q-item-section>下单用户</q-item-section>
        <q-item-section side>
          <q-item-label caption
            >{{ info.customer.remark || info.customer.nickname || "匿名" }}
            <q-icon name="arrow_forward_ios" size="14px" />
          </q-item-label>
        </q-item-section>
      </q-item>
      <q-item v-if="info.receiver">
        <q-item-section>接单人</q-item-section>
        <q-item-section side>
          <q-item-label caption>{{ info.receiver.nickname }}</q-item-label>
        </q-item-section>
      </q-item>
      <!-- DELAY 暂时隐藏 -->
      <!-- <q-item>
        <q-item-section>派单店铺</q-item-section>
        <q-item-section side>
          <q-item-label caption>xxxx</q-item-label>
        </q-item-section>
      </q-item> -->
      <template v-if="info.type == 3">
        <q-item>
          <q-item-section
            >进度
            <template v-if="info.union_keep"> +保底 </template>
          </q-item-section>
          <q-item-section side>
            <q-item-label caption
              >{{ info.union_schedule }}%
              <template v-if="info.union_keep">
                +{{ (info.union_piece_keep * 100) / info.union_piece_total }}%
              </template>
            </q-item-label>
          </q-item-section>
        </q-item>
        <q-item>
          <q-item-section>中奖佣金</q-item-section>
          <q-item-section side>
            <q-item-label caption>{{ info.union_brokerage }}%</q-item-label>
          </q-item-section>
        </q-item>
        <q-item>
          <q-item-section>认购人数</q-item-section>
          <q-item-section side>
            <q-item-label caption
              >{{ info.union_user_num }}人，共{{
                info.union_user_money
              }}元</q-item-label
            >
          </q-item-section>
        </q-item>
      </template>

      <q-item v-if="info.draft_at">
        <q-item-section>出票时间</q-item-section>
        <q-item-section side>
          <q-item-label caption>{{ info.draft_at }}</q-item-label>
        </q-item-section>
      </q-item>
      <q-item v-if="info.revoke_at">
        <q-item-section>出票失败时间</q-item-section>
        <q-item-section side>
          <q-item-label caption>{{ info.revoke_at }}</q-item-label>
        </q-item-section>
      </q-item>
      <q-item>
        <q-item-section>方案截止时间</q-item-section>
        <q-item-section side>
          <q-item-label caption>{{ info.odds_close_time }}</q-item-label>
        </q-item-section>
      </q-item>
      <q-item>
        <q-item-section>方案投注时间</q-item-section>
        <q-item-section side>
          <q-item-label caption>{{ info.created_at }}</q-item-label>
        </q-item-section>
      </q-item>
      <q-item clickable @click="safeCopyToClipboard(info.order_sn)">
        <q-item-section>订单编号</q-item-section>
        <q-item-section side>
          <q-item-label caption
            >{{ info.order_sn }}
            <q-icon name="content_copy" size="14px" />
          </q-item-label>
        </q-item-section>
      </q-item>
      <q-item v-if="info.materials && info.materials.length">
        <q-item-section>
        <q-item-label caption>票据</q-item-label>
        <div class="q-pt-sm">
        <q-img
          v-for="(item, i) in info.materials"
          :key="i"
          :src="item.file_url"
          width="180px"
          @click="showImagePreview({images:[item.file_url],closeable: true,showIndex:false})"
        ></q-img>
        </div>
      </q-item-section>
      </q-item>
      <q-item v-if="info.button_chedan && info.lottery_state == 4" class="justify-center">
        <q-btn
          unelevated
          :disable="store.user.enable_work == 0"
          color="accent"
          class="q-px-lg"
          @click="confirmPost('revokeOrder', '撤单成功',{field:'revoke_message',message:'确认撤单么？',prompt: {model:'',type:'text'}})"
          >撤单</q-btn
        >
      </q-item>
      <q-item
        v-if="info.button_qupiao && (
          info.lottery_state == 1 ||
          info.lottery_state == 2 ||
          info.lottery_state == 3 ||
          info.lottery_state == 7)
        "
        class="justify-center"
      >
        <q-btn
          unelevated
          :disable="store.user.enable_work == 0 || info.lottery_take_ticket == 1"
          :color="info.lottery_take_ticket == 1?'grey':'accent'"
          class="q-px-lg"
          @click="confirmPost('takeOrderTicket', '取票成功',{message:'确认取票么？'})"
          >{{info.lottery_take_ticket == 1?'已取票':'取票'}}</q-btn
        >
      </q-item>
    </q-list>

    <template #footer>
      <q-footer class="row">
          <q-btn
            v-if="info.button_shuaidan && info.lottery_state == 5"
            :disable="store.user.enable_work == 0"
            unelevated square
            color="white" text-color="black"
            class="q-py-sm col"
            @click="confirmPost('throwCooperate', '甩单成功')"
            >

          <div class="safe-padding-bottom">甩单</div></q-btn
          >
          <q-btn
            v-if="info.button_jiedan && info.lottery_state == 5"
            :disable="store.user.enable_work == 0"
            unelevated square
            color="primary"
            class="q-py-sm col"
            @click="confirmPost('receiveOrder', '接单成功')"
            >

          <div class="safe-padding-bottom">接单</div></q-btn
          >
          <q-btn
            v-if="info.button_chupiao  && info.lottery_state == 4"
            :disable="store.user.enable_work == 0"
            unelevated square
            color="primary"
            class="q-py-sm col"
            @click="onClickDrawTickets"
            >

          <div class="safe-padding-bottom"><q-icon
              name="check_circle_outline"
              size="1.25em"
              class="q-mr-xs"
            />出票</div></q-btn
          >

          <q-btn
            v-else-if="info.button_paijiang  && info.lottery_state == 1"
            :disable="store.user.enable_send_prize == 0"
            unelevated square
            color="primary"
            class="q-py-sm col"
            @click="sendPrize"
            >
          <div class="safe-padding-bottom">派奖</div></q-btn
          >
      </q-footer>
    </template>
    <q-dialog v-model="showTickets" position="bottom"
      class="dialog-full-height">
      <q-card style="min-height: 75vh">
        <q-card-section>拆票明细</q-card-section>
        <TicketsList v-if="showTickets" :orderSn="info.order_sn" :lottery="info.lottery_type"></TicketsList>
        <div class="safe-padding-bottom"></div>
      </q-card>
    </q-dialog>
    <q-dialog v-model="confirmOdds" position="bottom" class="dialog-full-height">
      <q-card>
        <q-card-section class="row items-center q-pb-none">
          <div class="text-body1">请核对打票内容</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>
        <q-card-section>
          <q-markup-table separator="cell" flat bordered class="text-center bordered-table">
            <thead>
              <tr class="bg-grey-2">
                <th style="width:68px;">场次</th>
                <!-- <th>玩法</th> -->
                <th>赔率</th>
              </tr>
            </thead>
            <tbody>
              <template v-for="(selling,i) in info.sellings" :key="i">
                <tr>
                  <td>{{ selling.issue_num_week }}{{ selling.play_num_view||selling.play_num }}</td>
                  <!-- <td>{{ odd.play_name }}</td> -->
                  <td :style="j !== 0 ? 'border-left:1px solid rgba(0, 0, 0, 0.12);' : ''">
                    <div>{{ selling.vs_b }}<span class="text-grey q-mx-xs">{{ selling.vs_m }}</span>{{ selling.vs_a }}</div>
                    <template  v-for="(odd,j) in selling.play_items" :key="j">
                      <template v-for="(item,k) in odd.play_items" :key="k">
                        <div class="q-mt-xs">
                          <q-input type="number" v-model="item.value" clearable :label="odd.play_name+'：'+item.name" outlined dense class="col">
                            <!-- <template v-slot:append>
                              <q-icon name="edit" size="xs" color="grey" />
                            </template> -->
                          </q-input>
                        </div>
                      </template>
                    </template>
                  </td>
                </tr>
              </template>
            </tbody>
          </q-markup-table>
          <div class="safe-padding-bottom"></div>
        </q-card-section>
        <q-card-actions align="center">
          <q-btn v-close-popup unelevated color="primary" class="fit" label="核对确认" @click="drawTickets(info.sellings)" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </page-layout>
</template>
<script setup>
import { showImagePreview } from 'vant';
import { api } from "boot/axios";
import { useQuasar } from "quasar";
import { LOTTERY_STATE, ORDER_TYPE, TYPE_MODE, isNumberTottery, isVieTottery,OPTIMIZE_TYPE } from "src/utils/const";
import { ref, watch, reactive, computed } from "vue";
import { useRoute } from "vue-router";
import SellingsTable from "./components/SellingsTable.vue";
import UploadFile from "src/components/UploadFile.vue";
import TicketsList from "./components/TicketsList.vue";
import { useSelfStore } from "stores/self";
import { Rules,formatMoney } from "src/utils/tools";
import { safeCopyToClipboard } from "src/utils/tools.js"
const $q = useQuasar();
const props = defineProps(["isSelfBuyPlan"]);
const loading = ref(true);
const route = useRoute();
const info = ref({});
const store = useSelfStore();
function getOrderInfo() {
  api
    .getOrderInfo({
      order_sn: route.params.orderSn,
    })
    .then((res) => {
      info.value = res;
    })
    .finally(() => {
      loading.value = false;
    });
}
getOrderInfo();

function confirmPost(method, msg, dialogOptions,data) {
  if (dialogOptions) {
    return new Promise((resolve,reject)=>{
      $q.dialog({
      cancel: true,
      ...dialogOptions
      }).onOk((val) => {
        resolve(post(method,dialogOptions.field?{[dialogOptions.field]:val,...data}:data, msg));
      }).onCancel(()=>{
        reject('Cancelled')
      });
    })
  } else {
    return post(method,data, msg);
  }
}
function post(method,data, msg) {
  $q.loading.show()
  return api[method]({
    order_sn: info.value.order_sn,
      ...data
  })
    .then((res) => {
      $q.notify({ type: "positive", message: res.message || msg });
      getOrderInfo();
      // if(method =='receiveOrder'){
        // store.orders.draft_num++
      // }
    })
    .catch((e) => {
      $q.notify({ type: "negative", message: e.message });
    }).finally(()=>{
      $q.loading.hide()
    });
}
// 拆单详情
const enableTickets = computed(()=>{
  const lotteryType = info.value.lottery_type.type
  return !isNumberTottery(lotteryType) && ['bjdc','bjdc_sfgg','ctzq_sfc14','ctzq_sfc9','guan','guan_ya'].indexOf(lotteryType) == -1
  // lotteryType!='bjdc'
  // && lotteryType!='bjdc_sfgg'
  // && lotteryType!=='ctzq_sfc14'
  // && lotteryType!=='ctzq_sfc9'
  // && lotteryType !== 'guan'
})
const showTickets = ref(false);

// 出票
const materials = reactive([]);
const confirmOdds = ref(false);
// 上传票据成功回调
function uploaded(res) {
  res && res.data && materials.push(res.data);
}
function onClickDrawTickets(){
  if(!materials.length && !info.value.materials?.length){
    return $q.notify('请先上传票据！')
  }
  if(info.value.lottery_type.type == 'jczq' || info.value.lottery_type.type == 'jclq' /* || info.value.lottery_type.type== 'bjdc' || info.value.lottery_type.type=='bjdc_sfgg'*/){
    confirmOdds.value = true
  }else{
    drawTickets()
  }
}
function formatOddses(sellings){
  let oddses
//   {
//     "28": {
//         "rf_odds": {
//             "win": 1.76
//         },
//         "sf_odds": {
//             "loss": 1.37
//         },
//         "sfc_odds": {
//             "l1": 3.85
//         }
//     },
//     "29": {
//         "sf_odds": {
//             "loss": 3.82
//         }
//     }
//   }
  sellings.forEach((selling)=>{
    let oddObj
    selling.play_items.forEach((odd)=>{
      let obj
      odd.play_items.forEach((item)=>{
        if(item.value){
          obj = obj || {}
          obj[item.odds_name] = item.value
        }
      });
      if(obj){
        oddObj = oddObj || {}
        oddObj[odd.play_type] = obj
      }
    })
    if(oddObj){
      oddses = oddses || {}
      oddses[selling.id] = oddObj
    }
  })
  return oddses
}
function drawTickets(sellings){
  confirmPost('drawOrder', '出票成功',{message:'确认出票成功么？'},{
    oddses: sellings ? formatOddses(sellings) : void(0),
    material_ids: materials.map((item) => item.id)
  }).then(() =>{
    materials.splice(0, materials.length);
  })
}
// 派奖
function sendPrize(){
  $q.dialog({
    cancel: true,
    title:`派奖确认`,
    message:'请确认派奖金额',
    prompt: {
      model: formatMoney(info.value.lottery_should_send_prize),
      type: "number",
      isValid: Rules.required
    }
  }).onOk((val) => {
    $q.loading.show()
    api.sendPrize({order_sn:info.value.order_sn, prize : val }).then((res) => {
      $q.notify({ type: "positive", message: res.message || '派奖成功！' });
      getOrderInfo()
    })
    .catch((e) => {
      $q.notify({ type: "negative", message: e.message });
    }).finally(()=>{
      $q.loading.hide()
    });
  });
}

// 重新上传票据
function modifyTickets(){
  confirmPost('updateOrderTickets','上传成功',{message: '重新上传将覆盖之前的票据，确定重新上传么？'},{ material_ids: materials.map((item) => item.id) }).then(() =>{
    materials.splice(0, materials.length);
  })
}

</script>
