<template>
  <el-dialog width="700px" :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.fullReductionCoupon"
              @cell-click="fullReductionCouponClick"
            >
              <el-table-column type="index" label="">
                <template v-slot="scope">
                  <el-checkbox
                    @change="fullReductionCouponClick(scope.row)"
                    :model-value="scope.row.id == fullReductionCouponSel.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">
                  {{ scope.row.type == 1 ? "优惠券" : "商品券" }}
                </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-tab-pane label="商品券(多选)" name="goods">
            <el-table
              ref="refTable1"
              empty-text="无可用商品券"
              :data="quans.productCoupon"
              style="width: 100%"
            >
              <el-table-column width="80">
                <template v-slot="scope">
                  <el-checkbox
                    @change="productCouponClick($event, scope.row)"
                    v-model="scope.row.checked"
                  ></el-checkbox>
                </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">
                    <div class="u-flex">
                      <el-image
                        :src="scope.row.productImg"
                        fit="cover"
                        style="width: 40px; height: 40px"
                        :preview-src-list="[scope.row.productImg]"
                      ></el-image>
                    </div>
                    <div class="u-p-l-10">
                      <div class="">{{ scope.row.productName }}</div>
                      <div class="">x{{ scope.row.num || 1 }}</div>
                    </div>
                  </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 label="券类型">
                <template v-slot="scope">
                  {{ scope.row.type == 1 ? "优惠券" : "商品券" }}
                </template>
              </el-table-column> -->
              <el-table-column prop="useRestrictions" label="描述"></el-table-column>
              <!-- <el-table-column prop="useRestrictions" label="是否可用">
                <template v-slot="scope">
                  {{ scope.row.use ? "可以" : "不可用" }}
                </template>
              </el-table-column> -->
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <div v-if="quansSelArr.length > 0">
          <div class="font-bold u-m-b-10">已选优惠券</div>
          <el-table empty-text="未选择优惠券" :data="quansSelArr">
            <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">
                {{ scope.row.type == 1 ? "优惠券" : "商品券" }}
              </template>
            </el-table-column>
            <el-table-column label="商品信息" width="120">
              <template v-slot="scope">
                <div class="u-flex" v-if="scope.row.type == 2">
                  <div class="u-flex">
                    <el-image
                      :src="scope.row.productImg"
                      fit="cover"
                      style="width: 40px; height: 40px"
                    ></el-image>
                  </div>
                  <div class="u-p-l-10">
                    <div class="">{{ scope.row.productName }}</div>
                    <div class="">x{{ scope.row.num || 1 }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="discountAmount" label="抵扣">
              <template v-slot="scope">
                <span class="color-red" v-if="scope.row.type == 1">
                  ￥{{ scope.row.discountAmount }}
                </span>
                <span class="color-red" v-if="scope.row.type == 2">
                  ￥{{ returnProDiscount(scope.row, scope.row.index) }}
                </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 { ElMessageBox } from "element-plus";
import * as quanUtil from "../quan_util.js";
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,
  fullReductionCouponSel: {
    id: "",
  },
  quansSelArr: [],
  quans: {
    fullReductionCoupon: [],
    productCoupon: [],
  },
  currentRow: null,
  multipleSelection: null,
  fullReductionCouponSelId: "",
  activeName: "youhui",
  form: {},
  show: false,
  isSetProductCoup: false,
});

const {
  discount,
  fullReductionCouponSel,
  quansSelArr,
  quans,
  currentRow,
  multipleSelection,
  activeName,
  form,
  show,
  isSetProductCoup,
} = toRefs(state);

const refTable = ref();
const refTable1 = ref();

let orderPrice = ref(0);
let $originFullReductionCoupon = [];
//可以抵扣的商品列表
let canDikouGoodsArr = [];
//商品数量从0到n每一个对应的价格
let $goodsPayPriceMap = {};
let goodsArr = [];

function open(money, orderInfo) {
  let arr = [];
  for (let i in orderInfo.detailMap) {
    arr.push(...orderInfo.detailMap[i]);
  }
  goodsArr = arr;
  $goodsPayPriceMap = quanUtil.returnGoodsPayPriceMap(goodsArr || []);
  canDikouGoodsArr = quanUtil.returnNewGoodsList(goodsArr);
  console.log(canDikouGoodsArr);
  getcoup();
  orderPrice.value = money;
  show.value = true;
}

async function getcoup() {
  const res = await couponApi.findCoupon({ shopUserId: props.user.id });
  quans.value.fullReductionCoupon = res.filter(
    (v) => v.type == 1 && orderPrice.value * 1 >= v.fullAmount * 1
  );
  quans.value.productCoupon = res
    .filter((v) => v.type == 2 && canDikouGoodsArr.find((goods) => v.proId == goods.productId))
    .map((v) => {
      const findGoods = goodsArr.find((goods) => goods.productId == v.proId);
      return {
        ...v,
        productImg: findGoods ? findGoods.productImg : "",
        productName: findGoods ? findGoods.productName : "",
      };
    });
}
function fullReductionCouponClick(row) {
  if (row.id == fullReductionCouponSel.value.id) {
    fullReductionCouponSel.value = { id: "" };
    quansSelArr.value.splice(0, 1);
    return;
  }
  const dikouQuan = quansSelArr.value[0];
  fullReductionCouponSel.value = row;
  if (dikouQuan && dikouQuan.type == 1) {
    quansSelArr.value[0] = row;
  } else {
    quansSelArr.value.unshift(row);
  }
  if (!fullReductionCouponSel.value.id) {
    return;
  }
}
const AllCouponPrice = computed(() => {
  return quanUtil.returnCouponAllPrice(quansSelArr.value, canDikouGoodsArr, props.user);
});

const payPrice = computed(() => {
  return (orderPrice.value - AllCouponPrice.value).toFixed(2);
});
function productCouponClick(checked, item) {
  console.log(checked);
  if (!item.use) {
    return;
  }
  const hasSelNum = quansSelArr.value
    .filter((v) => v.type == 2 && v.proId == item.proId)
    .reduce((a, b) => {
      return a + (b.num || 1);
    }, 0);
  console.log($goodsPayPriceMap[item.proId]);
  const maxSelNum = $goodsPayPriceMap[item.proId].length;
  const coupMaxUseNum = Math.min(item.num || 1, maxSelNum - hasSelNum);
  const canUseNum = Math.min(maxSelNum, coupMaxUseNum);
  console.log("maxSelNum", maxSelNum);
  console.log("coupMaxUseNum", coupMaxUseNum);
  console.log("canUseNum", canUseNum);
  if (checked && canUseNum <= 0) {
    ElMessage.error("购物车该商品券可使用最大数量为" + maxSelNum);
    setTimeout(() => {
      item.checked = !checked;
    }, 100);
    return;
  }

  if (fullReductionCouponSel.value.id && !item.checked) {
    const goodsQuan = quans.value.productCoupon.filter((v) => v.checked);
    const fullReductionCoupon = fullReductionCouponSel.value.id
      ? [fullReductionCouponSel.value]
      : [];

    let coupArr = [...goodsQuan, { ...item, num: canUseNum }];
    const payPrice =
      orderPrice.value - quanUtil.returnCouponAllPrice(coupArr, canDikouGoodsArr, props.user);
    console.log(payPrice);
    if (payPrice <= 0) {
      return ElMessageBox.confirm(
        "选择该商品券后支付金额将为0，继续选择将取消选择的满减券",
        "提示",
        {
          confirmButtonText: "继续选择",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          fullReductionCouponSel.value = {
            id: "",
          };
          quansSelArr.value.splice(0, 1);
        })
        .catch(() => {});
    }
    if (fullReductionCouponSel.value.fullAmount > payPrice) {
      ElMessageBox.confirm(
        "选择该商品券后将不满足选择抵扣券的最低满减需求，继续选择将取消选择的满减券",
        "提示",
        {
          confirmButtonText: "继续选择",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          fullReductionCouponSel.value = {
            id: "",
          };
        })
        .catch(() => {
          item.checked = false;
          const index = quansSelArr.value.findIndex((v) => v.id == item.id);
          quansSelArr.value.splice(index, 1);
        });
    }
  }
  item.checked = checked;
  if (!item.checked) {
    const index = quansSelArr.value.findIndex((v) => v.id == item.id);
    quansSelArr.value.splice(index, 1);
  } else {
    quansSelArr.value.push({ ...item, num: canUseNum });
  }
  const CheckedArr = quans.value.productCoupon.filter((v) => v.checked);
  if (CheckedArr.length <= 0) {
    return quans.value.productCoupon.map((v) => {
      v.use = true;
    });
  }
  const noCheckedArr = quans.value.productCoupon.filter((v) => !v.checked);
  noCheckedArr.map((v) => {
    v.use = quanUtil.returnCoupCanUse(canDikouGoodsArr, v, CheckedArr);
  });
}
//返回商品券抵扣金额
function returnProDiscount(row) {
  //相同商品抵扣券数组
  const arr = quansSelArr.value.filter((v) => v.type == 2 && v.proId == row.proId);
  const index = arr.findIndex((v) => v.id == row.id);
  const item = goodsArr.find((v) => v.productId == row.proId);
  if (index != -1) {
    const n = quanUtil.returnProductCoupAllPrice(
      $goodsPayPriceMap[row.proId],
      index,
      row.num,
      props.user.id && props.user.isVip
    );
    return n.toFixed(2);
  } else {
    return 0;
  }
}
//删除选中的优惠券
function delQuan(row) {
  const index = quansSelArr.value.findIndex((item) => item.id == row.id);
  if (row.type == 2 && index != -1) {
    quansSelArr.value.splice(index, 1);
    const proIndex = quans.value.productCoupon.findIndex((v) => v.id == row.id);
    quans.value.productCoupon[proIndex].checked = false;
  }
  if (row.type == 1 && index != -1) {
    fullReductionCouponSel.value = { id: "" };
    quansSelArr.value.splice(0, 1);
  }
}
function close() {
  show.value = false;
}
const emits = defineEmits(["confirm"]);
function reset() {
  quansSelArr.value = [];
  fullReductionCouponSel.value = { id: "" };
  quans.value.productCoupon = [];
}
function confirm() {
  emits("confirm", [...quansSelArr.value], $goodsPayPriceMap, goodsArr);
  close();
}
defineExpose({
  close,
  open,
});
</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>