<template>
  <div class="settlement">
    <Myheader></Myheader>
	<div class="rc-top"></div>
    <div class="rc_contline"></div>
    <div class="rc-main">
      <div class="address-list">
        <div
          class="mypersonal"
          v-for="(item, index) in useraddress"
          :key="index"
          :class="item.isDefault ? 'active' : ''"
          @click="selectAddress(item)"
        >
          <div class="arrow_ph" v-if="item.isDefault" @click="popGetList()">
            <i class="el-icon-arrow-right"></i>
          </div>
          <div class="edit" @click="editAddress(item)">
            <i class="el-icon-edit"></i>编辑
          </div>
          <div class="my-delivery">
            <span>{{ item.recipient }}</span>
            <i>{{ item.recipientPhone }}</i>
          </div>
          <div class="per-delivery">
            <span>{{ item.address }}</span>
          </div>
        </div>
        <div class="mypersonal add" :class="useraddress.length>0?'':'show'">
          <div
            class="my-delivery"
            @click="addAddress"
            style="justify-content: center"
          >
            <i class="el-icon-plus"></i>
            <span>添加收货地址</span>
          </div>
        </div>
      </div>
    </div>
    <div class="rc_contline"></div>
    <div class="rc-main" v-for="(item, index) in goldmedal" :key="index">
      <div class="rc-usermain">
        <div class="rc-image">
          <img :src="item.productImg" alt="" />
        </div>
        <div class="rc-right">
          <div class="rc-usercenter">
            <h3>{{ item.productName }}</h3>
            <p>规格:{{ item.specifications }}</p>
          </div>
          <div class="rc-userbottom">
            <p>￥{{ item.productPrice }}</p>
            <p>X{{ item.buyCount }}</p>
            <p class="price">￥{{ item.productPrice * item.buyCount }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="rc_contline"></div>
    <div class="rc-main">
      <div class="rc-merchandise">
        <ul>
          <li>
            <span>配送方式:</span>
            <i>{{ shopprice.price }}</i>
          </li>
		  
          <li>
            <span> 活动促销:</span>
            <i class="ts-right-arr ts-right-arr--two" @click="userget()">{{ curCoupon.couponName }}</i>
          </li>
	
          <li>
            <span>商品总价:</span>
            <i class="red">{{ sumPrice }}</i>
          </li>
          <li>
            <span>配送费用:</span>
            <i class="red">{{ shopprice.payment }}</i>
          </li>
        </ul>
      </div>
    </div>

    <div class="rc_contline"></div>
    <div class="rc-main">
      <div class="rc-foot">
        <div class="rc-foo">
          <div>
				<div class="discountInfo" v-if="discountAmount">
					<i>优惠金额:</i>
					<em>{{ discountAmount }}</em>
				</div>
            <i>合计金额:</i>
            <em>{{ finalAmount }}</em>
          </div>
          <div style="font-weight: bold">
            <span @click="preJiesuan()">提交订单</span>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogAdd"
      class="diallog_width"
      width="'100%"
      :title="dialogAddTitle"
    >
      <div class="tc dl_cont" v-if="dialogAdd">
        <myAddress
          @isClose="dialogCtrl"
          :editAddressData="editAddressData"
        ></myAddress>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogPopList"
      class="diallog_width"
      width="'100%"
      title="选择收货地址"
    >
      <div class="tc dl_cont" style="padding-bottom: 50px; position: relative">
        <div class="pop_list">
          <el-row
            class="mypersonal"
            v-for="(item, index) in useraddress"
            :key="index"
            :class="item.isDefault ? 'active' : ''"
          >
            <el-col :span="4"
              ><input
                type="checkbox"
                v-model="item.checked"
                @click="selectPopAddress(item)"
            /></el-col>
            <el-col :span="16" class="tl">
              <div>
                <p class="inline">{{ item.recipient }}</p>
                <p class="inline">{{ item.recipientPhone }}</p>
              </div>
              <p>{{ item.address }}</p>
            </el-col>
            <el-col :span="4">
              <i @click="editAddress(item)" class="el-icon-edit"></i>
            </el-col>
          </el-row>
          <div class="popnewaddr">
            <span class="btn" @click="addAddress">新增收货地址</span>
          </div>
        </div>
      </div>
    </el-dialog>
	<el-dialog :visible.sync="dialogInfo1"  class="pop_coupon" :close-on-click-modal="false">
		<div class="ts-no-data" v-if="drawlist.length<=0">您还没有优惠券，可在商品的详情页面中领取</div>
	  <div class="rs-dis">
	    <div
	      class="rc-discount"
	      v-for="(item, index) in drawlist"
	      :key="index"
	    >
			<img :src="userimage" alt="" />
			<div class="rc-contair">
			  <div class="rc-left" :style='usercolor'>
				<div>
					<i v-if="(item.couponTypeId!='4' && item.couponAmount>0)">
						￥
					</i>
					<span>
						{{ item.couponAmount?item.couponAmount:(parseInt((1-item.discount)*10)+'折') }}
					</span>
				</div>
				<strong>{{ item.couponName }}</strong>
			  </div>
			  <div class="rc-right">
				<i  :style='usercolor'>
				  {{ item.couponName }}
				</i>
				<div class="rc-userfont" :style="(item.validTo?'visibility:visible':'visibility:hidden')">
					<strong>有效期</strong>
				  <span>{{item.validFrom}}至</span>
				  <em>{{item.validTo}}</em>
				</div>
				<div class="rc-footer">
				  <span @click="pickCoupon(item)">立即使用</span>
				</div>
			  </div>
			</div>
	    </div>
	  </div>
	</el-dialog>
  </div>
</template>

<script>
import Myheader from "~/components/header.vue";
import { userin, memberAddress, generateOrderWX, getdraw } from "../../ajax/getData";
import util from "@/ajax/util";
import tabs from "@/components/tabs.vue";
import myAddress from "~/components/address.vue";
import { mapMutations } from "vuex";
import itemMixin from "../../../smart-admin-web/src/components/main/components/side-menu/item-mixin";
export default {
  middleware: "metaTitle",
  meta: { title: "订单结算" },
  data() {
    return {
	  util,
	  crumbs:[
		  {
		  	path:'/productdetails/productlist/',
		  },
		  {
			path:'/personal/settlement'
		  }
	  ],
	  usercolor:{color:'#e1001a'},
	  userimage: require("../../assets/image/unused.png"),
	  curCoupon:{couponName:'未选择可用优惠券'},
	  drawlist:[],
	  dialogInfo1:false,
      goldmedal: [],
      dialogAddTitle: "",
      addressstype: null,
      orderstatus: "",
      userisdelivery: "待收货",
      userdelivery: "派送中",
      isshow: true,
      leftico: require("../../assets/image/rc-left.png"),
      orderNumber: "",
      dialogAdd: false,
      dialogPopList: false,
      editAddressData: {},
      curAddress: {},
      saveType: "",
      useraddress: [
        // {
        //   state: "李某某",
        //   tel: "15124117917",
        //   address: "广东省 广州市 天河区 天河客运站118号",
        //   isdefault: true,
        // },
        // {
        //   state: "李某某",
        //   tel: "15124117917",
        //   address: "广东省 广州市 天河区 天河客运站118号",
        //   isdefault: false,
        // },
      ],
      shopprice: {
        price: "标准快递",
        distribution: "限时折扣全场商品8折",
        promotion: "￥167.00",
        payment: "￥0.00 ",
      },
	  discountAmount:0,
	  finalAmount:0,
	  discountedProductCode:undefined,
    };
  },
  computed: {
	sumPrice() {
		return this.goldmedal.reduce((pre, cur) => {
			return pre + cur.buyCount * cur.productPrice;
			}, 0);
	},
    // 折扣计算
  },
  methods: {
	...mapMutations(["checkIsLogin"]),
	discountedSumPrice() {
		if(this.curCoupon.productCodes)
			this.finalAmount = this.qualifiedProductDiscount();
		else
			this.finalAmount = this.wholeOrderDiscount();
		this.finalAmount = parseFloat(this.finalAmount).toFixed(2);
		this.discountAmount = parseFloat(this.discountAmount).toFixed(2);
	},
	wholeOrderDiscount(){
		this.discountedItemIndex = 0;
		let checkResult = true;
		if(this.curCoupon.minPrice && this.curCoupon.minPrice > this.sumPrice) {
			checkResult = false;
		}
		if(this.curCoupon.minQuantity && this.curCoupon.minQuantity > 0) {
			let totalItemNum = 0;
			let tmpShoppingCartList = this.arrSort(this.goldmedal);
			for(let itemInCart of tmpShoppingCartList) {
				totalItemNum += itemInCart.buyCount;
			}
			if(this.curCoupon.minQuantity > totalItemNum)
				checkResult = false;
		}
		if(this.curCoupon.couponAmount && this.curCoupon.couponAmount > this.sumPrice) {
			checkResult = false;
		}
		if(checkResult) {
			this.discountedProductCode = this.goldmedal[0].productCode
			if(this.curCoupon.couponAmount && this.curCoupon.couponAmount>0) {
				this.discountAmount = this.curCoupon.couponAmount;
				return this.sumPrice - this.curCoupon.couponAmount;
			} else if(this.curCoupon.discount && this.curCoupon.discount>0) {
				this.discountAmount = this.sumPrice*this.curCoupon.discount;
				return this.sumPrice * ( 1 - this.curCoupon.discount );
			}
		} else {
			this.discountAmount = 0;
			this.curCoupon = {couponName:'未能使用该优惠券'};
			return this.sumPrice;
		}
	},
	qualifiedProductDiscount(){
		this.discountedItemIndex = 0;
		let total = 0;
		let totalItemNum = 0;
		let couponUsed = false;
		let tmpShoppingCartList = this.arrSort(this.goldmedal);
		let qualifiedProductAmount = 0;
		let skipQualifiedProductAmountCalculating = false;
		let checkResult = true;
		for(let itemInCart of tmpShoppingCartList) {
			if(this.curCoupon.productCodes.indexOf(itemInCart.productCode)>-1) {
				qualifiedProductAmount += (itemInCart.productPrice * itemInCart.buyCount);
				totalItemNum += itemInCart.buyCount;
			}
		}
		if(this.curCoupon.minPrice && this.curCoupon.minPrice > qualifiedProductAmount) {
			checkResult = false;
		}
		if(this.curCoupon.minQuantity && this.curCoupon.minQuantity > totalItemNum) {
			checkResult = false;
		}
		if(this.curCoupon.couponAmount && this.curCoupon.couponAmount > qualifiedProductAmount) {
			checkResult = false;
		}
		
		for(let itemInCart of tmpShoppingCartList) {
			if(this.curCoupon.productCodes && this.curCoupon.productCodes.indexOf(itemInCart.productCode)>-1 && !couponUsed && checkResult) {
				//Into coupon discount calculation
				switch(this.curCoupon.couponTypeId) {
					case 1: //Amount deduct
						/*
						if(this.curCoupon.couponAmount && this.curCoupon.couponAmount <= (itemInCart.productPrice * itemInCart.buyCount)) {							
							total = total + (itemInCart.productPrice * itemInCart.buyCount - this.curCoupon.couponAmount);
							this.discountAmount = this.curCoupon.couponAmount;
							this.discountedProductCode = itemInCart.productCode;
							couponUsed=true;
						} else if(this.curCoupon.couponAmount && this.curCoupon.couponAmount > (itemInCart.productPrice * itemInCart.buyCount)) {
							total = total + itemInCart.productPrice * itemInCart.buyCount;
							this.discountAmount = 0;
							this.curCoupon = {couponName:'未能使用该优惠券'};
						}
						break;
						*/
					case 2: //Amount deduct with minPrice restriction
					case 6:
						if(this.curCoupon.couponAmount && this.curCoupon.couponAmount <= qualifiedProductAmount && this.curCoupon.productCodes.indexOf(itemInCart.productCode)>-1) {
							total = total + qualifiedProductAmount - this.curCoupon.couponAmount;
							this.discountAmount = this.curCoupon.couponAmount;
							this.discountedProductCode = itemInCart.productCode;
							skipQualifiedProductAmountCalculating = true;
							couponUsed=true;
						} else if(this.curCoupon.couponAmount && this.curCoupon.couponAmount > qualifiedProductAmount) {
							total = total + itemInCart.productPrice * itemInCart.buyCount;
							this.discountAmount = 0;
							this.curCoupon = {couponName:'未能使用该优惠券'};
						}
						break;
					case 3: //Limited product % discount
					case 4: //% discount
						if(this.curCoupon.discount && this.curCoupon.productCodes.indexOf(itemInCart.productCode)>-1) {
							total = total + (itemInCart.productPrice * itemInCart.buyCount) * ( 1 - this.curCoupon.discount );
							this.discountAmount = (itemInCart.productPrice * itemInCart.buyCount) * this.curCoupon.discount;
							this.discountedProductCode = itemInCart.productCode;
							couponUsed=true;
							skipQualifiedProductAmountCalculating = true;
						} else if(this.curCoupon.couponAmount && this.curCoupon.couponAmount > qualifiedProductAmount) {
							total = total + itemInCart.productPrice * itemInCart.buyCount;
							this.discountAmount = 0;
							this.curCoupon = {couponName:'未能使用该优惠券'};
						}
						break;
					default:
						total += itemInCart.productPrice * itemInCart.buyCount;
						break;
				}
				//Into coupon discount calculation end
			} else {
				if(skipQualifiedProductAmountCalculating && this.curCoupon.productCodes.indexOf(itemInCart.productCode)>-1) {
					
				} else {
					total += itemInCart.productPrice * itemInCart.buyCount;
				}
			}
		}
		if(!couponUsed) {
			this.discountAmount = 0;
			this.curCoupon = {couponName:'未能使用该优惠券'};
			total = this.sumPrice;
		}
		return total;
	},
	arrSort(arr) {
		let userarr=[]
		let a=[];
		for(let i in arr){
			arr[i].total=arr[i].productPrice*arr[i].buyCount;
			if(arr[i].total){
				userarr.push(arr[i]);
			}
		}
		return userarr.sort((n1,n2)=>{
			return n2.total-n1.total;
		});
	},
    async getAddressList() {
      let memberId = JSON.parse(localStorage.getItem("userInfo")).data.id;
      let { data } = await memberAddress("getAll", { memberId: memberId });
      data.forEach((item) => {
        item.address =
          item.provinceName +
          item.cityName +
          item.districtName +
          item.detailAddress;
      });
      this.useraddress = data;
    },
	userget(){
		let user = this.$store.state.userInfo;
		if (user) {
		  //this.userdraw(user.data.mobile);
		  this.dialogInfo1 = true;
		} else {
			this.$router.push({
				path: "/userlogin/login",
			});
		}
	},
	//获取用户领取的优惠券
	async userdraw(mobile) {
		let curDate = new Date();
		let productCodes = [];
		for(let itemInCart of this.goldmedal) {
			productCodes.push(itemInCart.productCode);
		}
		let paramsToAPI = {
			mobile : mobile,
			useStartDate : curDate.getFullYear()+'-'+(curDate.getMonth()+1)+'-'+curDate.getDate(),
			status:0
		};
		if(productCodes)
			paramsToAPI.productCodes = productCodes.join(',');
		let data = await getdraw(paramsToAPI);
		let _self = this;
		let curTime = new Date().getTime();
		let valDateFromTime=0;
		let valDateToTime=0;
		let dateChecked=true;
		let avaliableCouponNum = 0;
	  if (data) {
		this.drawlist=[];
		/*
		for(let itemInCart of this.goldmedal) {
			let tmpIndex=0;
			for(let myCoupon of data.data) {
				valDateFromTime=0;
				valDateToTime=0;
				dateChecked=true;
				if(myCoupon.fValidFrom) {
					//Fix ios date issue
					myCoupon.fValidFrom = myCoupon.fValidFrom.replace(/-/g, '/');
					valDateFromTime = new Date(myCoupon.fValidFrom).getTime();
				}
				if(myCoupon.fValidTo) {
					//Fix ios date issue
					myCoupon.fValidTo = myCoupon.fValidTo.replace(/-/g, '/');
					valDateToTime = new Date(myCoupon.fValidTo).getTime();
				}
				
				if(valDateFromTime && curTime < valDateFromTime) {
					dateChecked=false;
				}
				if(valDateToTime && curTime > valDateToTime) {
					dateChecked=false;
				}
				
				if(myCoupon.minQuantity && myCoupon.minQuantity>itemInCart.buyCount) {
					dateChecked=false;
				}
				if(myCoupon.minPrice && myCoupon.minPrice>this.sumPrice) {
					dateChecked=false;
				}
				if(myCoupon.couponAmount && myCoupon.couponAmount>this.sumPrice) {
					dateChecked=false;
				}
				if(myCoupon.udf2!='H5') {
					dateChecked=false;
				}
				
				if(dateChecked && myCoupon.activityId != 10 && myCoupon.status == 0 && (!myCoupon.productCodes || myCoupon.productCodes.indexOf(itemInCart.productCode)>-1)) {
				//if(dateChecked) {
					//data.data.splice(tmpIndex,1);
					data.data[tmpIndex]={};
					_self.drawlist.push(myCoupon);
					avaliableCouponNum++;
				}
				tmpIndex++;
			}
		}
		*/
	   
	   avaliableCouponNum = data.length;
	   this.drawlist = data.data;
	   
		if(avaliableCouponNum > 0) {
			this.curCoupon.couponName = '有 '+avaliableCouponNum+' 张优惠券可以使用';
		}
	  }
	},
	pickCoupon(item){
		this.curCoupon = item;
		this.dialogInfo1 = false;
		this.discountedSumPrice();
	},
    editAddress(item) {
      this.dialogAddTitle = "修改收货地址";
      this.editAddressData = {
        memberId: item.memberId,
        name: item.recipient,
        tel: item.recipientPhone,
        detailAddress: item.detailAddress,
        id: item.id,
        cityId: item.cityId,
        districtId: item.districtId,
        provinceId: item.provinceId,
        provinceName: item.provinceName,
        cityName: item.cityName,
        districtName: item.districtName,
        saveType: "edit",
      };
      this.dialogAdd = true;
    },
    addAddress() {
      this.dialogAddTitle = "新增收货地址";
      this.editAddressData = {};
      this.dialogAdd = true;
    },
    selectAddress(cur) {
      this.useraddress.forEach((item) => {
        if (item.id == cur.id) {
          item.isDefault = true;
          item.checked = true;
        } else {
          item.checked = false;
          item.isDefault = false;
        }
      });
    },
    selectPopAddress(cur) {
      this.useraddress.forEach((item) => {
        if (item.id == cur.id) {
          item.isDefault = true;
          item.checked = true;
        } else {
          item.checked = false;
          item.isDefault = false;
        }
      });
    },
    popGetList() {
      this.dialogPopList = true;
    },
    dialogCtrl(parm) {
      this.dialogAdd = parm;
      this.getAddressList();
    },
	preJiesuan(){
		let checkResult=true;
		if(this.useraddress.length<=0) {
			this.$message({
			  type: "error",
			  message: '请先添加收件信息',
			});
			checkResult=false;
		}
		
		if(checkResult)
			this.jiesuan();
	},
    async jiesuan() {
      let orderAddress = this.useraddress.filter((item) => item.isDefault);
	  let userInfo = this.$store.state.userInfo;
	  if(!userInfo) {
		  this.$router.push({
		    path: "/userlogin/login",
		    query: {
		      
		    },
		  });
		  return;
	  }
      let postData = [];
	  let tmpCounter=0;
      this.goldmedal.forEach((item) => {
		let basePoint = (item.basePoint?item.basePoint:0);
        let oneProduct = {
			basePoint:basePoint,
			productName: item.productName,
			buyCount: item.buyCount,
			productCode: item.productCode,
			payAmount: item.productPrice,
			memberId: userInfo.data.id,
			phoneNumber: userInfo.data.mobile,
			// couponId: "NGQ2022P12",
			// couponTypeId: "4",
			// couponName: "内购券",
			// couponAmount: "0.3175",
			// couponCode: "0007792402",
			orderAddress: {
				addressPhoneNumber: orderAddress[0].recipientPhone,
				addressUserName: orderAddress[0].recipient,
				addressProvinceName: orderAddress[0].provinceName,
				addressCityName: orderAddress[0].cityName,
				addressCountyName: orderAddress[0].districtName,
				addressDetailInfo: orderAddress[0].detailAddress,
			},
        };
		if(this.curCoupon.couponId && item.productCode == this.discountedProductCode) {
			oneProduct.couponId = this.curCoupon.couponId;
			oneProduct.couponTypeId = this.curCoupon.couponTypeId;
			oneProduct.couponName = this.curCoupon.couponName;
			oneProduct.couponCode = this.curCoupon.couponCode;
			oneProduct.couponAmount = (this.curCoupon.couponAmount?this.curCoupon.couponAmount:this.curCoupon.discount);
		}
        postData.push(oneProduct);
		tmpCounter++;
      });
      // let postData = [
      //   {
      //     productName: this.goldmedal.productName,
      //     buyCount: "2",
      //     productId: "20030200",
      //     payAmount: "147.00",
      //     memberId: "844350",
      //     phoneNumber: "18112621098",
      //     couponId: "NGQ2022P12",
      //     couponTypeId: "4",
      //     couponName: "内购券",
      //     couponAmount: "0.3175",
      //     couponCode: "0007792402",
      //     orderAddress: {
      //       addressPhoneNumber:orderAddress[0].recipientPhone,
      //       addressUserName:orderAddress[0].recipient,
      //       addressProvinceName: orderAddress[0].provinceName,
      //       addressCityName:orderAddress[0].cityName,
      //       addressCountyName: orderAddress[0].districtName,
      //       addressDetailInfo: orderAddress[0].detailAddress,
      //     },
      //   },
      //   // {
      //   //   productName: "幼猫全价粮",
      //   //   buyCount: "2",
      //   //   productId: "20030200",
      //   //   payAmount: "147.00",
      //   //   memberId: "844350",
      //   //   phoneNumber: "18112621098",
      //   //   couponId: "NGQ2022P12",
      //   //   couponTypeId: "4",
      //   //   couponName: "内购券",
      //   //   couponAmount: "0.3175",
      //   //   couponCode: "0007792402",
      //   //   orderAddress: {
      //   //     addressPhoneNumber: "13602898745",
      //   //     addressUserName: "张三",
      //   //     addressProvinceName: "江苏省",
      //   //     addressCityName: "无锡市",
      //   //     addressCountyName: "江阴市",
      //   //     addressDetailInfo: "东苑一村",
      //   //   },
      //   // },
      // ];
	  let payType = this.util.pickPaytype();
      let res = await generateOrderWX(postData,payType);
      if (res.success) {
        let userPayData = {
          orderId: res.data.orderNumber,
          userprice: parseFloat(res.data.orderAmount).toFixed(2),
          userinformation:
            postData[0].orderAddress.addressUserName +
            " " +
            postData[0].orderAddress.addressPhoneNumber,
          // wxPay: "weixin://wxpay/bizpayurl?pr=4RJbokxzz",
          // wxPay: "weixin://wxpay/bizpayurl?pr=4RJbokxzz",
          wxPay: (res.msg?res.msg:''),
        };
        this.$router.push({
          path: "/personal/userpay",
          query: {
            userPayData: JSON.stringify(userPayData),
          },
        });
      } else {
        this.$message({
          type: "warning",
          message: res.msg,
        });
      }
    },
    async canceldanhao(orderNumber) {
      let data = await userin(orderNumber);
    }
  },
  mounted() {
    this.goldmedal = JSON.parse(this.$route.query.list);
    this.getAddressList();
	this.checkIsLogin();
	let user = this.$store.state.userInfo;
	let memberId = '';
	if(user)
		memberId = user.data.id;
	this.finalAmount = this.sumPrice;
	this.goldmedal.forEach((item) => {
		_hmt.push([
		    "_trackCustomEvent",
		    "placing_order",
		    {
				"member_id": memberId,
				"product_id": item.productCode,
				"product_name": item.productName,
				"product_quantity" : item.buyCount,
				"product_amount" : item.buyCount*item.productPrice,
		    }
		])
	});
	
	if(user) {
		this.userdraw(user.data.mobile);
	}
    // this.addressstype = this.$route.query.stype;
    // this.orderNumber = this.$route.query.orderNumber;
    // this.canceldanhao(this.orderNumber);
    // console.log(this.$refs.rccolor);
    // this.$refs.rccolor.style.background = "gray";
  },
  components: {
    Myheader,
    tabs,
    myAddress,
  },
};
</script>

<style lang="less" scoped>
//@import url("../../assets/css/global.less");
@import "./settlement.less";
// @import url("../../assets/css/settlement.less");
</style>