<template>
  <el-card shadow="never" class="!border-none">
    <el-page-header content="查看优惠券" @back="$router.back()" />
  </el-card>
  <el-card class="!border-none" shadow="never">
    <el-form ref="formRef" class="mb-[-16px]" :model="formData" :inline="true">
      <el-form-item label="优惠券名称" prop="name">
        <el-input
          class="w-[280px]"
          v-model="formData.couponName"
          clearable
          placeholder="请输入优惠券名称"
        />
      </el-form-item>
      <el-form-item label="发放状态" prop="status">
        <el-select class="w-[280px]" v-model="formData.status" clearable>
          <el-option label="全部" value="" />
          <el-option
            v-for="option in optionMap.statusOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getLists">查询</el-button>
        <el-button @click="resetParams">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card shadow="never" class="mt-4 !border-none">
    <el-button
      type="primary"
      @click="handleDelete({}, 'multiple')"
      :disabled="isDisabled"
    >
      批量删除
    </el-button>
    <div class="mt-3">
      <el-table
        :data="pager.lists"
        ref="couponTable"
        row-key="id"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          :reserve-selection="true"
        ></el-table-column>
        <el-table-column
          prop="id"
          label="ID号"
          min-width="80"
        ></el-table-column>
        <el-table-column prop="name" label="优惠券名称" min-width="200">
          <template #default="{ row }">{{ row.couponDetailVo.name }}</template>
        </el-table-column>
        <el-table-column prop="name" label="面值" min-width="120">
          <template #default="{ row }">{{ row.couponDetailVo.money }}</template>
        </el-table-column>
        <el-table-column
          prop="dispatchStartTime"
          label="发放时间"
          min-width="260"
        >
          <template #default="{ row }">
            {{ parseTime(row.couponDetailVo, "send") }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="使用时间" min-width="260">
          <template #default="{ row }">
            {{ parseTime(row.couponDetailVo, "use") }}
          </template>
        </el-table-column>
        <el-table-column
          prop="allCouponCount"
          label="总领取数量"
          min-width="120"
        />
        <el-table-column
          prop="useCouponCount"
          label="使用数量"
          min-width="120"
        />
        <el-table-column prop="orderStatus" label="发放状态" min-width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="2"
              :before-change="() => handleStatusChange(row, getLists, 'inner')"
              :disabled="disabledStatus(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="148" fixed="right">
          <template #default="{ row }">
            <el-link
              class="ml-4"
              type="primary"
              :underline="false"
              @click="handleDelete(row, 'single', 'inner', getLists)"
            >
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="flex justify-end mt-4">
      <pagination v-model="pager" @change="getLists" />
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { apiOrderLists } from "@/api/order/lists";
import {
  DispatchEnum,
  StatusEnum,
  channelMap,
  dispatchStatusMap,
  getTypeMap,
} from "@/enums/modeEnum";
import { usePaging } from "@/hooks/usePaging";
import feedback from "@/utils/feedback";
import pagination from "@/components/pagination/index.vue";
import { useCreateModal } from "@/hooks/useCreateModal";
import type { ChannelEnum } from "@/enums/modeEnum";
import { useCommon } from "@/hooks/useCommon";
import type { ElTable } from "element-plus";
import { apiDistributorCoupon } from "@/api/distributor/lists";
import { optionMap } from "@/config/status";
import { delCoupon, delCouponByDistributor } from "@/api/application/coupon";
import { time } from "echarts/core";
import { parseCouponTime } from "@/utils/util";
import { DispatchStatusEnum } from "@/enums/modeEnum";

const route = useRoute();
const id = route.query.id;
// const selectedIds = ref<number[]>([])
// const couponTable = ref<InstanceType<typeof ElTable>>()
const formData = reactive({
  appointId: id,
  status: "",
  couponName: "",
});

const tableData = [
  {
    id: 1,
    name: "xxx",
    dispatchStartTime: 1693789200,
    dispatchEndTime: 1693792800,
    orderStatus: 0,
    getType: 1,
  },
  {
    name: "xxx",
    dispatchStartTime: 1693789200,
    dispatchEndTime: 1693792800,
    orderStatus: 0,
    getType: 3,
    channel: 1,
  },
  {
    name: "xxx",
    dispatchStartTime: 1693789200,
    dispatchEndTime: 1693792800,
    orderStatus: 0,
    getType: 3,
    channel: 2,
  },
];
const { pager, getLists, resetPage, resetParams } = usePaging({
  fetchFun: apiDistributorCoupon,
  params: formData,
});

onMounted(getLists);

// const isDisabled = computed(() => !selectedIds.value.length)

// /**多选操作 */
// const handleSelectionChange = (val: any[]) => {
//     selectedIds.value = val.map(item => item.id) as number[]
// }
// /**删除 */
// const handleDelete = async (row: any, type: string, field: string) => {
//     let couponName = ''
//     if(field === 'inner') {
//         const { couponDetailVo: { name } } = row
//         couponName = name
//     }else {
//         const { name } = row
//         couponName = name
//     }
//     try {
//         if (type === 'single') couponTable.value?.toggleRowSelection(row, true)
//         const text = type === 'multiple' ? '勾选的优惠券' : `优惠券【${couponName}】`
//         await feedback.confirm(`此操作不可逆，确定删除${text}？`)
//         await delCouponByDistributor({ ids: selectedIds.value })
//         feedback.msgSuccess('删除成功')
//         getLists()
//     } catch (error) { } finally {
//         clearSelection()
//     }
// }
// function clearSelection() {
//     couponTable.value?.clearSelection()
// }

/**切换发放状态 */
const {
  handleStatusChange,
  couponTable,
  isDisabled,
  handleDelete,
  handleSelectionChange,
} = useCommon();

// 发放时间：18:00-19:00， 根据当前时间判断是否可以滑动
// 未到发放时间停用且无法滑动
// 过了发放时间停用且无法滑动
// 发放期间
const now = new Date().getTime();
const disabledStatus = computed(function () {
  return function (row) {
    const { sendTimeStart, sendTimeEnd, status } = row.couponDetailVo;
    if (Object.keys(row).length) {
      const flag =
        now > Date.parse(sendTimeStart) && now < Date.parse(sendTimeEnd);
      return !flag || status == DispatchStatusEnum.STOP ? true : false;
    }
  };
});
const parseTime = computed(() => {
  return (row: any, field: string) => {
    const { sendTimeStart, sendTimeEnd, useTimeStart, useTimeEnd } = row;
    const fieldsMap: Record<string, string[]> = {
      send: [sendTimeStart, sendTimeEnd],
      use: [useTimeStart, useTimeEnd],
    };
    const [timeStart, timeEnd] = fieldsMap[field];
    if (!timeStart || !timeEnd) {
      return "--";
    }
    return `${parseCouponTime(timeStart)}至${parseCouponTime(timeEnd)}`;
  };
});
</script>

<style lang="scss" scope></style>
