<template>
  <el-dialog width="1000px" :title="title" v-model="show" top="20px" @close="reset">
    <div class="u-p-15">
      <div class="">
        <el-tabs v-model="activeName" @tab-click="tabClick">
          <el-tab-pane label="优惠券(单选)" name="youhui">
            <el-table ref="refTable" empty-text="无可用优惠券" :data="quans.coupon" max-height="40vh">
              <el-table-column type="index" label="">
                <template v-slot="scope">
                  <el-checkbox @change="couponClick($event, scope.row)"
                    :model-value="scope.row.id == couponSel.id"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="name" label="券名称"></el-table-column>
              <el-table-column label="券类型" width="80">
                <template v-slot="scope">
                  {{ couponUtils.returnCoupType(scope.row) }}
                </template>
              </el-table-column>
              <el-table-column prop="discountAmount" label="抵扣" align="center">
                <template v-slot="scope">
                  <span class="color-red">￥{{ scope.row.discountAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="discountAmount" label="最大抵扣金额" align="center">
                <template v-slot="scope">
                  <span class="color-red">
                    {{
                      !scope.row.maxDiscountAmount ? "无上限" : "￥" + scope.row.maxDiscountAmount
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="discountAmount" label="限制" width="180">
                <template v-slot="scope">
                  <div class="u-flex">
                    <span>支付满</span>
                    <span class="color-red no-wrap">
                      {{ scope.row.fullAmount }}
                    </span>
                    <span>元可用</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="useRestrictions" label="描述"></el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="商品券(单选)" name="goods">
            <el-table ref="refTable1" empty-text="无可用商品券" :data="quans.productCoupon" style="width: 100%"
              max-height="40vh">
              <el-table-column width="80">
                <template v-slot="scope">
                  <el-checkbox @change="productCouponClick($event, scope.row)"
                    :model-value="goodsCouponSel.id == scope.row.id"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column prop="id" width="100" label="ID">
                <template v-slot="scope">
                  {{ scope.row.id }}
                </template>
              </el-table-column>

              <el-table-column type="index" width="50" label="#"></el-table-column>
              <el-table-column prop="name" label="券名称"></el-table-column>

              <el-table-column label="商品信息" width="220">
                <template v-slot="scope">
                  <div class="u-flex">
                    {{ scope.row.foods }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="discountAmount" label="抵扣">
                <template v-slot="scope">
                  <span class="color-red">￥{{ scope.row.discountAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="discountAmount" label="限制" width="180">
                <template v-slot="scope">
                  <div class="u-flex">
                    <span>支付满</span>
                    <span class="color-red no-wrap">
                      {{ scope.row.fullAmount }}
                    </span>
                    <span>元可用</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="useRestrictions" label="描述"></el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <div class="u-m-t-10" v-if="noUseCoupon.length > 0">
          <div class="font-bold u-m-b-10">不可用优惠券</div>
          <el-table empty-text="无" :data="noUseCoupon" max-height="30vh">
            <el-table-column type="index" width="50" label="#"></el-table-column>
            <el-table-column prop="name" label="券名称"></el-table-column>
            <el-table-column label="券类型" width="80">
              <template v-slot="scope">
                {{ couponUtils.returnCoupType(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column label="商品信息" width="120">
              <template v-slot="scope">
                <div class="u-flex">
                  {{ scope.row.foods }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="discountAmount" label="抵扣">
              <template v-slot="scope">
                <span class="color-red">￥{{ scope.row.discountAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="useRestrictions" label="描述"></el-table-column>
            <el-table-column label="不可用原因">
              <template v-slot="scope">
                <span class="color-red">{{ scope.row.canuseResult.reason }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="u-m-t-10" v-if="quansSelArr.length > 0">
          <div class="font-bold u-m-b-10">已选优惠券</div>
          <el-table empty-text="无" :data="quansSelArr" max-height="20vh">
            <el-table-column type="index" width="50" label="#"></el-table-column>
            <el-table-column prop="name" label="券名称"></el-table-column>
            <el-table-column label="券类型" width="80">
              <template v-slot="scope">
                {{ couponUtils.returnCoupType(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column label="商品信息" width="120">
              <template v-slot="scope">
                <div class="u-flex">
                  {{ scope.row.foods }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="discountAmount" label="抵扣">
              <template v-slot="scope">
                <span class="color-red">￥{{ scope.row.discountAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="useRestrictions" label="描述"></el-table-column>
            <el-table-column prop="useRestrictions" label="">
              <template v-slot="scope">
                <el-button type="danger" size="small" @click="delQuan(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="u-flex u-row-between u-m-t-20">
          <div class="u-flex">
            <span>抵扣金额:</span>
            <span class="color-red">￥{{ AllCouponPrice }}</span>
          </div>
          <div class="u-flex u-relative">
            <span>支付金额:</span>
            <span class="color-red">￥{{ payPrice }}</span>
            <div class="u-absolute u-flex line-th color-999" style="right: 0; bottom: 100%"
              v-if="orderPrice * 1 != payPrice * 1">
              <span class="">￥{{ orderPrice }}</span>
            </div>
          </div>
        </div>
        <div class="u-flex u-row-center u-m-t-50">
          <el-button size="large" @click="close">取消</el-button>
          <el-button size="large" type="primary" @click="confirm">确定</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import couponApi from "@/api/account/coupon";
import { BigNumber } from "bignumber.js";
import { couponUtils } from "ysk-utils";
import { ElMessageBox } from "element-plus";
import { useUserStoreHook } from "@/store/modules/user";
import { useCartsStore } from '@/store/modules/carts'

const cartStore = useCartsStore()

const shopUser = useUserStoreHook();

const props = defineProps({
  title: {
    type: String,
    default: "选择优惠券",
  },
  goodsArr: {
    type: Array,
    default: [],
  },
  user: {
    type: Object,
    default: () => {
      return {
        isVip: false,
      };
    },
  },
});
function tabClick() { }

const state = reactive({
  discount: 1,
  couponSel: {
    id: "",
  },
  goodsCouponSel: {
    id: "",
  },
  quans: {
    coupon: [],
    productCoupon: [],
  },
  currentRow: null,
  multipleSelection: null,
  couponSelId: "",
  activeName: "youhui",
  form: {},
  show: false,
  isSetProductCoup: false,
});

const {
  discount,
  couponSel,
  goodsCouponSel,
  quans,
  currentRow,
  multipleSelection,
  activeName,
  form,
  show,
  isSetProductCoup,
} = toRefs(state);
const quansSelArr = computed(() => {
  return [goodsCouponSel.value, couponSel.value].filter((v) => v.id);
});
const refTable = ref();
const refTable1 = ref();

let orderPrice = ref(0);
//可以抵扣的商品列表
let canDikouGoodsArr = [];
let goodsArr = [];
//不可用优惠券列表
const noUseCoupon = ref([]);

function open(money, orderInfo) {
  let arr = [];
  for (let i in orderInfo.detailMap) {
    arr.push(...orderInfo.detailMap[i]);
  }
  goodsArr = arr;
  canDikouGoodsArr = couponUtils.returnCanDikouGoods(arr, props.user, cartStore.shopInfo);
  console.log("canDikouGoodsArr", canDikouGoodsArr);
  getcoup();
  orderPrice.value = money;
  show.value = true;
}

let couponList = [];
async function getcoup() {

  console.log(cartStore.limitDiscountRes);


  const res = await couponApi.findCoupon({ shopUserId: props.user.id });
  couponList = res || [];
  let canUseGoodsCoupon = [];
  let canUseDiscountCoupon = [];

  let noUseGoodsCoupon = [];
  let noUseDiscountCoupon = [];
  console.log("orderPrice", orderPrice.value);
  for (let i = 0; i < couponList.length; i++) {
    const coupon = couponList[i];
    const selCoupon =
      activeName.value == "goods"
        ? quansSelArr.value.filter((v) => v.type != 2)
        : quansSelArr.value.filter((v) => v.type == 2);
    const canuseResult = couponUtils.returnCouponCanUse({
      canDikouGoodsArr,
      coupon,
      goodsOrderPrice: orderPrice.value,
      user: props.user,
      selCoupon,
      shopInfo: shopUser.userInfo,
      limitTimeDiscount: cartStore.limitDiscountRes
    });
    const { canUse, reason } = canuseResult;
    if (coupon.type == 2) {
      if (canUse || goodsCouponSel.value.id == coupon.id) {
        canUseGoodsCoupon.push(coupon);
      } else {
        noUseGoodsCoupon.push({
          ...coupon,
          canuseResult,
        });
      }
    } else {
      if (canUse || couponSel.value.id == coupon.id) {
        canUseDiscountCoupon.push(coupon);
      } else {
        noUseDiscountCoupon.push({
          ...coupon,
          canuseResult,
        });
      }
    }
  }

  //商品券
  canUseGoodsCoupon = canUseGoodsCoupon.map((v) => {
    const discount = couponUtils.returnCouponDiscount(
      canDikouGoodsArr,
      v,
      props.user,
      orderPrice.value,
      quansSelArr.value.filter((v) => v.type != 2),
      shopUser.userInfo,
      cartStore.limitDiscountRes
    );
    return {
      ...v,
      discount,
      discountAmount: discount ? discount.discountPrice : v.discountAmount,
    };
  });
  //非商品券
  canUseDiscountCoupon = canUseDiscountCoupon.map((v) => {
    const discount = couponUtils.returnCouponDiscount(
      canDikouGoodsArr,
      v,
      props.user,
      orderPrice.value,
      quansSelArr.value.filter((v) => v.type == 2),
      shopUser.userInfo,
      cartStore.limitDiscountRes
    );
    return {
      ...v,
      discount,
      discountAmount: discount ? discount.discountPrice : v.discountAmount,
    };
  });

  quans.value.productCoupon = canUseGoodsCoupon;
  quans.value.coupon = canUseDiscountCoupon;
  if (activeName.value == "goods") {
    noUseCoupon.value = [...noUseGoodsCoupon];
  } else {
    noUseCoupon.value = [...noUseDiscountCoupon];
  }
}

function couponClick(checked, row) {
  couponSel.value = checked ? row : { id: "" };
  updateSelCoupon();
}
const AllCouponPrice = computed(() => {
  return quansSelArr.value.reduce((pre, cur) => pre + cur.discountAmount, 0);
});

const payPrice = computed(() => {
  return (orderPrice.value - AllCouponPrice.value).toFixed(2);
});
function productCouponClick(checked, item) {
  goodsCouponSel.value = checked ? item : { id: "" };
  updateSelCoupon();
}

//删除选中的优惠券
function delQuan(row) {
  if (row.type == 2) {
    goodsCouponSel.value = { id: "" };
    return;
  }
  couponSel.value = { id: "" };
}
function close() {
  show.value = false;
}
const emits = defineEmits(["confirm"]);
function reset() {
  couponSel.value = { id: "" };
  goodsCouponSel.value = { id: "" };
}
function confirm() {
  emits("confirm", [...quansSelArr.value], goodsArr);
  close();
}
defineExpose({
  close,
  open,
});

watch(
  () => activeName.value,
  () => {
    getcoup();
  }
);
function updateSelCoupon() {
  const newval = quansSelArr.value;
  if (newval.length >= 2) {
    let goodsCoupon = newval.filter((v) => v.type == 2);
    let otherCoupon = newval.filter((v) => v.type != 2);
    goodsCoupon = goodsCoupon.map((v) => {
      const discount = couponUtils.returnCouponDiscount(
        canDikouGoodsArr,
        v,
        props.user,
        orderPrice.value,
        [],
        shopUser.userInfo,
        cartStore.limitDiscountRes
      );
      return {
        ...v,
        discount,
        discountAmount: discount ? discount.discountPrice : v.discountAmount,
      };
    });
    otherCoupon = otherCoupon.map((v) => {
      const canuseResult = couponUtils.returnCouponCanUse({
        canDikouGoodsArr,
        coupon: v,
        orderPrice: orderPrice.value,
        user: props.user,
        selCoupon: goodsCoupon,
        shopInfo: shopUser.userInfo,
        limitTimeDiscount: cartStore.limitDiscountRes
      });

      const discount = couponUtils.returnCouponDiscount(
        canDikouGoodsArr,
        v,
        props.user,
        orderPrice.value,
        goodsCoupon,
        shopUser.userInfo,
        cartStore.limitDiscountRes
      );
      return {
        ...v,
        canuseResult,
        discount,
        discountAmount: discount ? discount.discountPrice : v.discountAmount,
      };
    });
    if (!otherCoupon[0].canuseResult.canUse) {
      couponSel.value = { id: "" };
      ElMessageBox.confirm(
        `选择该券后优惠券${otherCoupon[0].name}不可用，不可用原因：${otherCoupon[0].canuseResult.reason}`,
        "提示",
        {
          type: "warning",
          showCancelButton: true,
          cancelButtonText: "取消当前券的选择",
          confirmButtonText: "剔除不可用的优惠券",
        }
      )
        .then(() => {
          couponSel.value = { id: "" };
          goodsCouponSel.value = goodsCoupon[0];
        })
        .catch(() => {
          goodsCouponSel.value = { id: "" };
          couponSel.value = otherCoupon[0];
        });
      return;
    }
    goodsCouponSel.value = goodsCoupon[0];
    couponSel.value = otherCoupon[0];
  }
}

watch(
  () => quansSelArr.value,
  (newval) => {
    console.log("quansSelArr", newval);

    getcoup();
  }
);
</script>

<style lang="scss" scoped>
.line-th {
  text-decoration: line-through;
}

.codeImg {
  width: 160px;
  border: 1px solid rgb(220, 223, 230);
  height: 160px;
}

:deep(.el-input .el-input__inner::-webkit-inner-spin-button) {
  -webkit-appearance: none;
  margin: 0;
}

:deep(.el-input .el-input__inner::-webkit-outer-spin-button) {
  -webkit-appearance: none;
  margin: 0;
}
</style>