<template>
  <el-dialog
    width="700px"
    :title="title"
    :visible.sync="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="table"
              empty-text="无可用优惠券"
              :data="quans.fullReductionCoupon"
              @cell-click="fullReductionCouponClick"
            >
              <el-table-column type="index" label="">
                <template v-slot="scope">
                  <el-checkbox
                    @change="fullReductionCouponClick(scope.row)"
                    :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="120">
                <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="table1"
              @cell-click="productCouponClick"
              empty-text="无可用商品券"
              :data="quans.productCoupon"
              style="width: 100%"
            >
              <el-table-column>
                <template v-slot="scope">
                  <el-checkbox
                    @change="productCouponClick(scope.row)"
                    :value="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="120">
                <template v-slot="scope">
                  <div class="u-flex">
                    <div class="u-flex">
                      <el-image
                        :src="scope.row.productCover"
                        fit="cover"
                        style="width: 40px; height: 40px"
                        :preview-src-list="[scope.row.productCover]"
                      ></el-image>
                    </div>
                    <div class="u-p-l-10">
                      <div class="">{{ scope.row.productName }}</div>
                      <div class="">x{{ scope.row.num || "" }}</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.productCover"
                      fit="cover"
                      style="width: 40px; height: 40px"
                      :preview-src-list="[scope.row.productCover]"
                    ></el-image>
                  </div>
                  <div class="u-p-l-10">
                    <div class="">{{ scope.row.productName }}</div>
                    <div class="">x{{ scope.row.num || "" }}</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="mini" @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="medium" @click="close">取消</el-button>
          <el-button size="medium" type="primary" @click="confirm"
            >确定</el-button
          >
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { $activateByOrderId } from "@/api/table";
import {
  returnNewGoodsList,
  returnFullReductionCouponAllPrice,
  returnCouponAllPrice,
  returnProductCoupon,
  returnCanUseFullReductionCoupon,
  returnCoupCanUse,
  returnProductCouponAllPrice,
  returnGoodsPayPriceMap,
  returnProductCoupAllPrice,
} from "../quan_util.js";
let $originFullReductionCoupon = [];
//可以抵扣的商品列表
let canDikouGoodsArr = [];
//商品数量从0到n每一个对应的价格
let $goodsPayPriceMap = {};
export default {
  props: {
    title: {
      type: String,
      default: "选择优惠券",
    },
    goodsArr: {
      type: Array,
      default: [],
    },
    vipUser: {
      type: Object,
      default: () => {
        return {
          isVip: false,
        };
      },
    },
  },
  data() {
    return {
      orderPrice: 0,
      fullReductionCouponSel: {
        id: "",
      },
      quansSelArr: [],
      quans: {
        fullReductionCoupon: [],
        productCoupon: [],
      },
      currentRow: null,
      multipleSelection: null,
      fullReductionCouponSelId: "",
      activeName: "youhui",
      form: {},
      show: false,
      isSetProductCoup: false,
    };
  },
  watch: {
    activeName(newval) {
      if (newval == "youhui") {
        this.filterFullReductionCoupon();
      }
    },
  },
  computed: {
    goodsDiscount() {
      const coupArr = this.quansSelArr.filter((v) => v.type == 2);
      return returnProductCouponAllPrice(
        coupArr,
        canDikouGoodsArr,
        this.vipUser
      );
    },
    fullReductionCouponDiscount() {
      const coupArr = this.quansSelArr.filter((v) => v.type == 1);
      return returnFullReductionCouponAllPrice(coupArr);
    },
    AllCouponPrice() {
      return returnCouponAllPrice(
        this.quansSelArr,
        canDikouGoodsArr,
        this.vipUser
      );
    },
    payPrice() {
      const pay = this.orderPrice - this.AllCouponPrice;
      return (pay < 0 ? 0 : pay).toFixed(2);
    },
  },
  methods: {
    returnProDiscount(row) {
      console.log(row);
      //相同商品抵扣券数组
      const arr = this.quans.productCoupon.filter((v) => v.proId == row.proId);
      const index = arr.findIndex((v) => v.id == row.id);
      if (index != -1) {
        return returnProductCoupAllPrice(
          $goodsPayPriceMap[row.proId],
          index,
          row.num
        ).toFixed(2);
      } else {
        return 0;
      }
    },
    goodsCoupSelectableHandle(row, index) {
      console.log(row, index);
      return true;
    },
    delQuan(row) {
      const index = this.quansSelArr.findIndex((item) => item.id == row.id);
      if (row.type == 2 && index != -1) {
        this.quansSelArr.splice(index, 1);
        const proIndex=this.quans.productCoupon.findIndex((v) => v.id == row.id);
        this.quans.productCoupon[proIndex].checked = false;
      }
      if (row.type == 1 && index != -1) {
        this.fullReductionCouponSel = { id: "" };
        this.quansSelArr.splice(0, 1);
      }
    },
    reset() {
      this.quansSelArr = [];
      this.fullReductionCouponSel = { id: "" };
      this.$refs.table1.clearSelection();
    },
    filterFullReductionCoupon() {
      this.quans.fullReductionCoupon = returnCanUseFullReductionCoupon(
        $originFullReductionCoupon,
        this.payPrice,
        this.fullReductionCouponSel
      );
    },
    fullReductionCouponClick(row) {
      if (row.id == this.fullReductionCouponSel.id) {
        this.fullReductionCouponSel = { id: "" };
        this.quansSelArr.splice(0, 1);
        return;
      }
      const dikouQuan = this.quansSelArr[0];
      this.fullReductionCouponSel = row;
      if (dikouQuan && dikouQuan.type == 1) {
        this.$set(this.quansSelArr, 0, row);
      } else {
        this.quansSelArr.unshift(row);
      }
      if (!this.fullReductionCouponSel.id) {
        return;
      }
    },
    productCouponClick(item) {
      if (!item.use) {
        return;
      }
      const hasSelNum = this.quansSelArr
        .filter((v) => v.type == 2 && v.proId == item.proId)
        .reduce((a, b) => {
          return a + b.num;
        }, 0);
      const maxSelNum = $goodsPayPriceMap[item.proId].length;
      const coupMaxUseNum = Math.min(item.num, maxSelNum - hasSelNum);
      const canUseNum = Math.min(maxSelNum, coupMaxUseNum);

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

        let coupArr = [...goodsQuan, { ...item, num: canUseNum }];
        const payPrice =
          this.orderPrice -
          returnCouponAllPrice(coupArr, canDikouGoodsArr, this.vipUser);
        console.log(payPrice);
        if (payPrice <= 0) {
          return this.$confirm(
            "选择该商品券后支付金额将为0，继续选择将取消选择的满减券",
            "提示",
            {
              confirmButtonText: "继续选择",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              this.fullReductionCouponSel = {
                id: "",
              };
              this.quansSelArr.splice(0, 1);
            })
            .catch(() => {});
        }
        if (this.fullReductionCouponSel.fullAmount > payPrice) {
          this.$confirm(
            "选择该商品券后将不满足选择抵扣券的最低满减需求，继续选择将取消选择的满减券",
            "提示",
            {
              confirmButtonText: "继续选择",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              this.fullReductionCouponSel = {
                id: "",
              };
            })
            .catch(() => {});
        }
      }
      item.checked = !item.checked;
      if (!item.checked) {
        console.log(index);
        const index = this.quansSelArr.findIndex((v) => v.id == item.id);
        this.quansSelArr.splice(index, 1);
      } else {
        this.quansSelArr.push({ ...item, num: canUseNum });
      }
      const CheckedArr = this.quans.productCoupon.filter((v) => v.checked);
      if (CheckedArr.length <= 0) {
        return this.quans.productCoupon.map((v) => {
          v.use = true;
        });
      }
      const noCheckedArr = this.quans.productCoupon.filter((v) => !v.checked);
      noCheckedArr.map((v) => {
        v.use = returnCoupCanUse(canDikouGoodsArr, v, CheckedArr);
      });
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    tabClick() {},
    init() {},

    changeKey(key, val) {
      this[key] = val;
    },

    confirm() {
      this.$emit("confirm", [...this.quansSelArr], $goodsPayPriceMap);
      this.close();
    },
    async open(data, propSelCoup) {
      console.log(data);
      this.orderPrice = data.orderPrice;
      this.quansSelArr = [...propSelCoup];
      $goodsPayPriceMap = returnGoodsPayPriceMap(this.goodsArr || []);
      if (data.memberId) {
        let quansRes = await $activateByOrderId({
          orderId: data.id,
          memberId: data.memberId,
        });
        quansRes.fullReductionCoupon = quansRes.fullReductionCoupon.filter(
          (v) =>this.orderPrice<=0?false:(v.use && this.orderPrice * 1 >= v.fullAmount * 1)  
        );
        const selFullReductionCoupon = this.quansSelArr.find(
          (v) => v.type == 1
        );
        this.fullReductionCouponSel = selFullReductionCoupon
          ? selFullReductionCoupon
          : { id: "" };
        this.quans.fullReductionCoupon = quansRes.fullReductionCoupon;
        canDikouGoodsArr = returnNewGoodsList(this.goodsArr || []);
        $originFullReductionCoupon = quansRes.fullReductionCoupon;
        this.quans.productCoupon = quansRes.productCoupon
          .map((v) => {
            const calcCoup = returnProductCoupon(
              v,
              canDikouGoodsArr,
              this.vipUser
            );
            return {
              ...calcCoup,
              checked: this.quansSelArr.find((selCoup) => selCoup.id == v.id)
                ? true
                : false,
                use:this.orderPrice<=0?false:calcCoup.use
            };
          })
          .filter((v) => v.use);
        // this.quans = quans;
      }

      this.show = true;
      this.init();
    },
    close() {
      this.show = false;
    },
  },
  mounted() {
    this.number = `${this.value}`;
  },
};
</script>
      
    <style  lang="scss" scoped>
.line-th {
  text-decoration: line-through;
}
.codeImg {
  width: 160px;
  border: 1px solid rgb(220, 223, 230);
  height: 160px;
}
::v-deep .el-input .el-input__inner::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

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