<template>
  <div :class="{ list: dataShow && !loading }">
    <template v-if="dataShow">
      <van-list
        v-model="loading"
        v-if="dataShow"
        key="data"
        :finished="finished"
        :immediate-check="false"
        finished-text="- 没有更多优惠券 -"
        @load="FetchList"
      >
        <van-checkbox-group
          v-model="checkCouponList"
          @change="changeAll"
          checked-color="#ff6464"
        >
          <coupon-item
            v-for="item in dataList"
            :key="item.code"
            :detail="item"
            :isDisabled="item.disabled"
            :isEdit="isEdit"
          />
        </van-checkbox-group>
      </van-list>
    </template>
    <m-empty v-if="!dataShow" key="teacher" msg="暂无优惠券" />
  </div>
</template>
<script>
const couponType = [
  "OTHER",
  "MUSICAL",
  "ACCESSORIES",
  "MAINTENANCE",
  "TEACHING",
  "PRACTICE",
  "SINGLE",
  "MIX",
  "VIP",
  "MEMBER",
  "FULLCOUPON",
];
import MEmpty from "@/components/MEmpty";
import item from "./item";
import { sysCouponCode } from "./api";
import { isDuringDate } from "@/helpers/utils";
export default {
  props: ["status", "isEdit", "allMoney", "all", "buyList", "useSystem"],
  components: {
    MEmpty,
    "coupon-item": item,
  },
  data() {
    return {
      couponType,
      loading: false,
      finished: false,
      dataShow: true,
      dataList: [],
      params: {
        page: 1,
        useSystem: this.useSystem || "",
        usageStatus: this.status,
        rows: this.all ? 9999 : 10,
      },
      checkCouponList: [],
      faceValue: 0,
    };
  },
  mounted() {
    this.FetchList();
    // console.log('调用123')
    // console.log(isDuringDate('2021-11-01 00:00:00','2022-10-31 23:59:59'))
  },
  methods: {
    async FetchList(page) {
      if (page) {
        this.dataList = [];
        this.params.page = page;
      }
      try {
        this.loading = true;
        this.params.userId = this.$route.query.studentId;
        let res = await sysCouponCode(this.params);
        let result = res.data;
        if (this.dataList.length > 0 && result.pageNo == 1) {
          return;
        }
        this.dataList = this.dataList.concat(result.rows);
        if (this.params.page >= result.totalPage) {
          this.finished = true;
        }
        this.params.page++;
        // 判断是否有数据
        if (this.dataList.length <= 0) {
          this.dataShow = false;
        } else {
          this.dataShow = true;
        }

        // this.$emit("setDot", this.dataList.length > 0);
        // eslint-disable-next-line no-empty
      } catch (error) {
        this.dataShow = false;
        this.finished = true;
      }
      this.loading = false;
      this.$nextTick(() => {
        this.setTitle(this.allMoney);
      });
      this.$nextTick(() => {
        this.setTitle(this.allMoney);
      });
    },
    changeAll(val) {
      // console.log(val, 'changeAll')
      this.setListDisabled(val);
    },
    setListDisabled(list) {
      // 算优惠券了 list 已选中的优惠券
      // dataList 所有的优惠券
      let shopObj = {}; // 每种类型的商品对应的价格

      let fullAmountList = {};
      let faceValueList = {};
      let shopType = []; // 所以类型的商品
      this.buyList.forEach((item) => {
        if (shopObj[item.couponType] || shopType.includes(item.couponType)) {
          shopObj[item.couponType] += Number(item.price);
        } else {
          shopObj[item.couponType] = Number(item.price);
          fullAmountList[item.couponType] = 0;
          faceValueList[item.couponType] = 0;
          shopType.push(item.couponType);
        }
      });
      let nowMoneyList = { ...shopObj };
      // shopType.push("FULLCOUPON");
      // typeDetail

      this.nowMoney = 0; // 满的钱
      this.faceValue = 0; // 面值 减的钱
      this.payMoney = this.allMoney * 1; // 减的总金额
      // 过滤一遍优惠券
      /**
       *      if (shopType.indexOf(copon.typeDetail) == -1) {
          copon.disabled = true;
        }
       *
       */
      this.dataList.forEach((item) => {
        if (list.indexOf(item.couponCodeId) != -1) {
          // 这里是选过的卷 加到相对应的值里去
          if (item.typeDetail != "FULLCOUPON") {
            fullAmountList[item.typeDetail] += item.fullAmount;
            faceValueList[item.typeDetail] += item.faceValue;
            nowMoneyList[item.typeDetail] =
              shopObj[item.typeDetail] - faceValueList[item.typeDetail];
            // shopObj[item.typeDetail] -= item.faceValue;
          } else {
            // 全类卷
            // 1.获取当前商品减优惠券的价格总值 allmoney
            // 2.获取当前 单个商品减优惠卷的价格 shopObj[i]
            // 3.算出 单个价值总价格的百分比
            // 4.将面值和见面金额分摊到每个商品上去
            let temAllMoney = 0;
            for (let i in shopType) {
              // i 为所有的type
              temAllMoney += shopObj[shopType[i]];
            }

            // 1.总价格拿到 temAllMoney
            for (let i in shopType) {
              // i 为所有的type
              let sclac = Number(shopObj[shopType[i]] / temAllMoney);
              faceValueList[shopType[i]] = Number(
                faceValueList[shopType[i]] + sclac * Number(item.faceValue)
              );
              nowMoneyList[shopType[i]] = Number(
                shopObj[shopType[i]] - faceValueList[shopType[i]]
              );
              fullAmountList[shopType[i]] = Number(
                fullAmountList[shopType[i]] + sclac * Number(item.fullAmount)
              );
            }
            // console.log(temAllMoney,{...shopObj})
          }

          // this.nowMoney += item.fullAmount;
          // this.payMoney -= item.faceValue;
          // this.faceValue += item.faceValue;
        }
      });
      // console.log("nowMoneyList:", nowMoneyList);
      // console.log("faceValueList:", faceValueList);
      // console.log("shopObj:", shopObj);
      // console.log("fullAmountList:", fullAmountList);
      // 选了一张
      // this.dataList.forEach((item) => {
      //   if (list.indexOf(item.couponCodeId) != -1) {
      //     this.nowMoney += item.fullAmount;
      //     // this.payMoney -= item.faceValue;
      //     this.faceValue += item.faceValue;
      //   }
      // });
      let allNowMoney = 0;
      let allShopMoney = 0;
      let allfaceValue = 0;
      let allFullMoney = 0;
      let flag = false;
      for (let i in shopType) {
        allNowMoney += nowMoneyList[shopType[i]];
        allShopMoney += shopObj[shopType[i]];
        allfaceValue += faceValueList[shopType[i]];
        allFullMoney += fullAmountList[shopType[i]];
      }

      console.log(
        "allNowMoney:",
        allNowMoney,
        "allShopMoney:",
        allShopMoney,
        "allfaceValue:",
        allfaceValue,
        "allFullMoney",
        allFullMoney
      );
      this.faceValue = allfaceValue;
      this.dataList.forEach((item) => {
        if (
          item.typeDetail != "FULLCOUPON" &&
          shopObj[item.typeDetail] &&
          item.fullAmount <=
            shopObj[item.typeDetail] - fullAmountList[item.typeDetail] &&
          isDuringDate(item.useStartDate, item.useDeadlineDate)
        ) {
          item.disabled = false;
          flag = true;
        } else if (
          item.typeDetail == "FULLCOUPON" &&
          isDuringDate(item.useStartDate, item.useDeadlineDate) &&
          item.fullAmount <= allShopMoney - allFullMoney
        ) {
          item.disabled = false;
          flag = true;
        } else {
          item.disabled = true;
        }
      });
      // 已经选了得 继续保持可以选
      this.dataList.forEach((item) => {
        if (list.indexOf(item.couponCodeId) != -1) {
          flag = true;
          item.disabled = false;
        }
      });
      this.dataList.sort((obj1, obj2) => {
        return obj1.disabled - obj2.disabled;
      });
      this.$forceUpdate();
      return flag;
    },
    setTitle(val) {
      let flag = false;
      if (this.isEdit) {
        flag = this.setListDisabled([]);
        console.log("调用list,setTitle");
      } else {
        this.dataList = this.dataList.map((item) => {
          item.disabled = true;
          return item;
        });
      }
      if (flag) {
        this.$emit("resetTitle", "有可用优惠券");
      } else {
        this.$emit("resetTitle", "暂无优惠券可用");
      }
    },
  },
  watch: {
    allMoney(val) {
      // console.log(val, 'allMoney', this.nowMoney, 'nowMoney', this.checkCouponList)
      this.setTitle([]);
    },
  },
};
</script>

<style lang="less" scoped>
.list {
  // background-color: #fff;
  width: 3.51rem;
  margin: auto;
  border-radius: 0.1rem;
  padding-top: 0.01rem;
}
/deep/.van-checkbox__icon .van-icon {
  border-color: #ffa4a4 !important;
}
</style>
