<template>
  <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.name"
          clearable
          placeholder="请输入优惠券名称"
        />
      </el-form-item>
      <el-form-item label="优惠券类型" prop="useGoodsType">
        <el-select class="w-[280px]" v-model="formData.useGoodsType" clearable>
          <el-option label="全部" value="" />
          <el-option
            v-for="option in optionMap.goodsOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="使用时间">
        <daterange-picker
          class="w-[385px]"
          type="datetimerange"
          format="YYYY-MM-DD HH:mm:ss"
          v-model:startTime="formData.useTimeStart"
          v-model:endTime="formData.useTimeEnd"
        />
      </el-form-item>
      <el-form-item label="发放方式" prop="getType">
        <el-select class="w-[280px]" v-model="formData.getType" clearable>
          <el-option label="全部" value="" />
          <el-option
            v-for="option in optionMap.getTypeOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </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="$router.push('edit')"
      >添加优惠券</el-button
    >
    <el-button
      type="primary"
      @click="handleDelete({}, 'multiple', 'wrapper', getLists)"
      :disabled="isDisabled"
    >
      批量删除
    </el-button>
    <div class="mt-3">
      <el-table
        ref="couponTable"
        :data="pager.lists"
        style="width: 100%"
        row-key="id"
        @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"
        ></el-table-column>
        <el-table-column prop="useGoodsType" label="优惠券类型" min-width="120">
          <template #default="{ row }">
            <span>{{ parseuseGoodsType(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="money" label="面值" min-width="100" />
        <el-table-column prop="sendTimeStart" label="发放时间" min-width="260">
          <template #default="{ row }">
            <span>{{ parseSendTime(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="useTimeStart" label="使用时间" min-width="260">
          <template #default="{ row }">
            <span>{{ parseUseTime(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sumNum" label="总领取数量" min-width="120" />
        <el-table-column prop="useNum" label="使用数量" min-width="120" />
        <el-table-column prop="getType" label="发放方式" min-width="120">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="handleGetTypeByUserReceive(row)"
              :disabled="disabledText(row)"
            >
              {{ parseGetType(row) }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="发放状态" min-width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="2"
              :before-change="
                () => handleStatusChange(row, getLists, 'wrapper')
              "
              :disabled="disabledStatus(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="148" fixed="right">
          <template #default="{ row }">
            <div class="flex">
              <router-link
                class="mr-2"
                :to="{
                  path: 'detail',
                  query: {
                    id: row.id,
                    channel: row.channelType,
                  },
                }"
              >
                <el-link type="primary" :underline="false">详情</el-link>
              </router-link>
              <el-link
                class="ml-4"
                type="primary"
                :underline="false"
                @click="handleDelete(row, 'single', 'wrapper', getLists)"
              >
                删除
              </el-link>
            </div>
          </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 selectuser from "./components/selectuser.vue";
import { usePaging } from "@/hooks/usePaging";
import { useCreateModal } from "@/hooks/useCreateModal";
import { useCommon } from "@/hooks/useCommon";
import {
  DispatchEnum,
  UseGoodsEnum,
  ChannelEnum,
  channelMap,
  getTypeMap,
  useGoodsTypeMap,
} from "@/enums/modeEnum";
import { GetcouponLists } from "@/api/application/coupon";
import { optionMap } from "@/config/status";
import { parseCouponTime } from "@/utils/util";

const formData = reactive({
  name: "", //优惠券名称
  useGoodsType: "", //优惠券类型
  useTimeStart: "", //优惠券使用开始时间
  useTimeEnd: "", //优惠券使用结束时间
  getType: "", //发放方式
  status: "", //发放状态
});

const { pager, getLists, resetPage, resetParams } = usePaging({
  fetchFun: GetcouponLists,
  params: formData,
});
onMounted(getLists);

const commandComponent = useCreateModal(selectuser);
/**发放方式 */
const handleGetTypeByUserReceive = (row: any) => {
  const {
    getType,
    channelType,
    id,
    name,
  }: {
    getType: DispatchEnum;
    channelType: ChannelEnum;
    id: number;
    name: string;
  } = row;
  const text = getTypeMap[getType];
  const title =
    getType === DispatchEnum.CHANNEL_DISPATCH
      ? `${text}-${channelMap[channelType]}`
      : `${text}记录`;
  commandComponent({
    title: title,
    getType,
    channelType,
    id,
    name,
  });
};
/**切换发放状态 */
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, channelType } = row;
    if (Object.keys(row).length) {
      return now < Date.parse(sendTimeStart) ||
        now > Date.parse(sendTimeEnd) ||
        channelType === ChannelEnum.USER
        ? true
        : false;
    }
  };
});
const parseGetType = computed(() => {
  return (row: any) => {
    const {
      getType,
      channelType,
    }: { getType: DispatchEnum; channelType: ChannelEnum } = row;
    return getType === DispatchEnum.CHANNEL_DISPATCH
      ? `指定${channelMap[channelType]}`
      : getTypeMap[getType];
  };
});
const parseuseGoodsType = computed(() => {
  return (row: any) => {
    const { useGoodsType }: { useGoodsType: UseGoodsEnum } = row;
    return useGoodsTypeMap[useGoodsType];
  };
});
const parseUseTime = computed(() => {
  return (row: any) => {
    const { useTimeStart, useTimeEnd } = row;
    return `${parseCouponTime(useTimeStart)} 至 ${parseCouponTime(useTimeEnd)}`;
  };
});

const parseSendTime = computed(() => {
  return (row: any) => {
    const { sendTimeStart, sendTimeEnd, channelType, getType, createTime } =
      row;
    if (
      getType === DispatchEnum.CHANNEL_DISPATCH &&
      channelType === ChannelEnum.USER
    ) {
      //渠道派发-指定用户
      return createTime;
    }
    return `${parseCouponTime(sendTimeStart)} 至 ${parseCouponTime(
      sendTimeEnd
    )}`;
  };
});

const disabledText = computed(() => {
  return (row: any) => {
    const { getType } = row;
    return getType === DispatchEnum.SYSTEM_GIVE;
  };
});
</script>

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