<template>
  <div>
    <el-dialog title="账单详情" v-model="dialogVisible" width="70%">
      <div>
        <el-table :data="[detail]" style="width: 100%" border>
          <el-table-column prop="startTime" label="账单周期">
            <template #default="{ row }">
              <div class="flex">
                <div>{{ row.startTime?.split(" ")[0] }}</div>
                <div class="mx-2">至</div>
                <div>{{ row.endTime?.split(" ")[0] }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="archiveId" label="账单所属第三方名称">
            <template #default="{ row }">
              <div class="flex">
                <div>{{ row.agency?.nickname }}【{{ row.agency?.id }}】</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="agencyReceiveBalance"
            label="累计支付到第三方总金额"
            :formatter="v => (v.agencyReceiveBalance / 100).toFixed(2)"
          />
          <el-table-column
            prop="toMechanismBalance"
            label="结算后平台应收收款金额"
            :formatter="v => (v.toMechanismBalance / 100).toFixed(2)"
          />
          <el-table-column
            prop="mechanismReceiveBalance"
            label="累计支付到平台总金额"
            :formatter="v => (v.mechanismReceiveBalance / 100).toFixed(2)"
          />
          <el-table-column
            prop="toAgencyBalance"
            label="结算后第三方应收款金额"
            :formatter="v => (v.toAgencyBalance / 100).toFixed(2)"
          />
          <el-table-column prop="serviceName" label="结算状态">
            <template #default="{ row }">
              <div :class="settlementStatusList[row.status - 1]?.color">
                {{ settlementStatusList[row.status - 1]?.label }}
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" class="my-3" v-if="detail.status == 2" @click="handleSettle">设为已结算</el-button>
        <el-divider />
        <div>
          <div class="flex justify-between">
            <div class="flex">
              <div>{{ detail.startTime?.split(" ")[0] }}</div>
              <div class="mx-2">至</div>
              <div class="mr-3">{{ detail.endTime?.split(" ")[0] }}</div>
              订单详情（系统只显示这期间内支付已完成订单）
            </div>
            <el-button v-if="state.recordList.length" :icon="Document" type="primary" link @click="handleExport"
              >导出详情</el-button
            >
          </div>

          <el-table :data="state.recordList" style="width: 100%" border class="my-4">
            <el-table-column prop="sn" label="订单信息">
              <template #default="{ row }">
                <div>
                  <span>{{ row.order.sn }}</span>
                  <el-tag>【会员卡订单】</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="promotionSite" label="订单来源信息">
              <template #default="{ row }">
                <div>
                  <div>{{ row?.order?.promotionSite?.name }}</div>
                  <div style="color: #a8abb2">[ {{ row.order?.promotionSite?.sn }} ]</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="promotionGoods"
              :formatter="v => v.order.promotionGoods?.memberCardName"
              label="订单商品名称"
            />
            <el-table-column prop="promotionGoods" label="实付金额">
              <template #default="{ row }">
                <div>
                  {{ row.order.balance / 100 }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" :formatter="v => v.order.promotionGoods?.memberCardName" label="订单状态">
              <template #default="{ row }">
                <div :class="statusList[row.order.status - 1]?.color">
                  {{ statusList[row.order.status - 1]?.label }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="支付时间" />
            <el-table-column prop="payType" label="支付方式" :formatter="() => '微信支付'" />
            <el-table-column prop="paymentType" label="支付款流向">
              <template #default="{ row }">
                <div>
                  {{ row.order.paymentType === 1 ? "平台" : row?.order.agency?.nickname }}
                </div>
                <div style="color: #a8abb2">
                  [ 商户号: {{ row.order.mchId }} ]
                  <br />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="toAgencyBalance"
              label="应收款方"
              :formatter="v => (v.type == 2 ? '平台' : v?.order.agency?.nickname)"
            />
            <el-table-column prop="toMechanismBalance" label="应收结算金额" :formatter="v => (v.balance / 100).toFixed(2)" />
          </el-table>
          <el-pagination
            class="mt-4 justify-end"
            background
            layout="prev, pager, next"
            :total="state.total"
            :page-size="state.query.pageSize"
            @current-change="changePage"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { handleDownloadFile } from "@/utils";
import { ref, computed, defineProps, defineEmits, reactive } from "vue";
import { statusList, settlementStatusList } from "../constant.ts";
import { ElMessage } from "element-plus";
import { Document, ElMessageBox } from "@element-plus/icons-vue";
import request from "@/api";

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  }
});
const emits = defineEmits(["update:show", "success"]);
const detail = ref({});
const state = reactive({
  query: {
    page: 1,
    pageSize: 10
  },

  total: 0,
  recordList: []
});
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});
const handleSettle = () => {
  ElMessageBox.confirm("确定该笔账单已经进行了实际的资金结算吗？确定后该状态不可撤回", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    request.post(`archivesService/agency/orderBill/settle?id=${detail.value.id}`).then(resp => {
      ElMessage.success(resp.message);
      emits("success");
      initData(detail.value.id);
    });
  });
};
const initData = id => {
  request.get(`archivesService/agency/orderBill/detail?id=${id}`).then(resp => {
    detail.value = resp.data.detail;
  });
  getOrderBillRecord(id);
};
const getOrderBillRecord = id => {
  request
    .get("archivesService/agency/orderBill/record/paginate", {
      ...state.query,
      billId: id
    })
    .then(resp => {
      state.recordList = resp.data.list;
      state.total = resp.data.total;
    });
};
const handleExport = () => {
  request
    .post(
      `archivesService/agency/orderBill/export`,
      {
        id: detail.value.id
      },
      {
        responseType: "blob"
      }
    )
    .then(resp => {
      const fileName = `${detail.value.startTime?.split(" ")[0]} 至 ${
        detail.value.endTime?.split(" ")[0]
      } 订单详情（系统只显示这期间内支付已完成订单）`;

      handleDownloadFile(resp, fileName);
    });
};
const changePage = page => {
  state.query.page = page;
  getOrderBillRecord(detail.value.id);
};
defineExpose({
  initData
});
</script>
