<template>
  <div class="index wrapper_1200">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>购物车</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="submit_order_Box">
      <div class="select_address">
        <el-radio-group v-model="defaultAddress">
          <el-radio
            class="select_address_list"
            :label="item.id"
            v-for="(item, index) in addressList"
            :key="index"
          >
            <div class="select_address_txt">
              <div style="color: #222">
                <span>{{ item.name }}</span>
                <span>{{ item.mobile }}</span>
              </div>
              <div style="color: #999">{{ item.full_address }}{{ item.address }}</div>
            </div>
          </el-radio>
        </el-radio-group>

        <div>
          <el-button size="samll" @click="showAllAddressList" type="text"
            >显示全部地址</el-button
          >
        </div>
      </div>

      <div class="submit_order_table">
        <div class="table_title">待确认订单信息</div>
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          ref="multipleTable"
          :header-cell-style="{ background: '#fafafa' }"
        >
          <el-table-column prop="id" label="商品" width="300" align="center">
            <template slot-scope="scope">
              <div class="commodityBox">
                <img :src="imgUrl + scope.row.sku_image" alt />
                <div class="commoditytxt">
                  <p class="p1">{{ scope.row.goods_name }}</p>
                  <p class="p2" v-if="scope.row.commoditytag">
                    <span
                      :class="{
                        commodityTagBg: scope.row.commodityTagType === 1,
                      }"
                      >{{ scope.row.commoditytag }}</span
                    >
                  </p>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="commodityNum" label="数量" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.num }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="amount1" label="单价" align="center">
            <template slot-scope="scope">
              <span>￥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="amount2" label="小计" align="center">
            <template slot-scope="scope">
              <span>￥{{ Math.round(scope.row.num * scope.row.price * 100) / 100 }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="select_coupon">
        <el-form
          ref="paymentForm"
          label-position="left"
          :model="paymentForm"
          label-width="150px"
        >
<!--          <el-form-item label="是否使用预存款支付">-->
<!--            <el-switch v-model="paymentForm.is_balance"></el-switch>-->
<!--          </el-form-item>-->
          <el-form-item label="是否需要开发票">
            <el-switch
              v-model="paymentForm.is_invoice"
              @change="invoiceChange"
            ></el-switch>
          </el-form-item>
          <el-form-item label="给卖家留言" style="width: 50%">
            <el-input type="textarea" v-model="paymentForm.buyer_message"></el-input>
          </el-form-item>
        </el-form>
        <div class="coupon_title" v-if="availableNum">选择优惠券</div>
        <div class="coupon_title" v-else-if="!availableNum">暂无可使用优惠券</div>
        <div class="couponCardList">
          <div class="couponCard">
            <el-radio-group v-model="defaultCoupon">
              <el-radio
                v-model="defaultCoupon"
                class="select_coupon_list"
                :label="item"
                v-for="(item, index) in decrementList"
                :key="index"
                @click.native.prevent="radioChange(item)"
              >
                <div class="select_couponCard">
                  <div class="couponCard_l">
                    <div v-if="item.type == 'discount'">
                      <span style="font-weight: 500; font-size: 24px">
                        {{ item.discount }}
                      </span>
                      <span>折</span>
                    </div>
                    <div v-if="!(item.type == 'discount')">
                      <span>￥</span>
                      <span style="font-weight: 500; font-size: 24px">
                        {{ item.money }}
                      </span>
                    </div>
                    <div
                      style="
                        font-size: 12px;
                        width: 70px;
                        line-height: 20px;
                        height: 20px;
                      "
                    >
                      满{{ item.at_least }}可使用
                    </div>

                    <div class="couponCard_leftBg"></div>
                  </div>
                  <div class="couponCard_r">
                    <div class="couponCard_rt">
                      <div style="font-size: 18px; font-weight: 500">
                        {{ item.coupon_name }}
                      </div>
                    </div>
                    <div style="font-size: 12px">
                      有效期：{{
                        $dayjs(item.end_time * 1000).format("YYYY-MM-DD HH:mm:ss")
                      }}
                    </div>
                    <div class="couponCard_rightBg"></div>
                  </div>
                </div>
              </el-radio>
            </el-radio-group>
          </div>

          <div class="couponCardList_bottom">
            <div class="couponCardList_bottom_Box">
              <div class="couponCardList_bottom_r">商品金额</div>
              <div class="couponCardList_bottom_l">{{ amount }}</div>
            </div>
            <div class="couponCardList_bottom_Box" v-if="Pre_price">
              <div class="couponCardList_bottom_r">优惠券</div>
              <div class="couponCardList_bottom_l">-￥ {{ Pre_price }}</div>
            </div>
            <div class="couponCardList_bottom_Box" v-if="orderInfo.delivery_money">
              <div class="couponCardList_bottom_r">运费</div>
              <div class="couponCardList_bottom_l">
                ￥{{ Number(orderInfo.delivery_money) }}
              </div>
            </div>
            <div class="couponCardList_bottom_Box">
              <div class="couponCardList_bottom_r">需付款</div>
              <div class="couponCardList_bottom_l" style="color: #ff2020">
                ￥{{ Paid_in }}
              </div>
            </div>

            <div class="couponCardList_bottom_btn">
              <el-button type="primary" size="small" @click="paymentType(paymentForm)"
                >提交订单</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 提交订单 -->
    <el-dialog
      title="选择支付方式"
      :visible.sync="paymentDialog"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div>
        <el-radio-group
          v-model="defaultAddress"
          class="paymentDialogRadio"
          @change="paidChange"
        >
          <el-radio :label="false">待支付金额：￥{{ Paid_in }}</el-radio>
          <el-radio :label="true"
            >预存款支付（当前余额{{ userInfo.balance }}，本次抵扣{{ Paid_in }}）</el-radio
          >
        </el-radio-group>

        <el-form ref="form" :model="paymentForm" label-width="120px">
          <el-form-item label="还需支付">
            <el-input
              v-model="paymentForm.payment_money"
              size="small"
              :placeholder="Tobepaid ? Paid_in : Tobepaid"
              disabled
            ></el-input>
          </el-form-item>

          <el-form-item label="请选择支付方式" v-if="!paymentForm.is_balance">
            <el-radio-group
              v-model="paymentForm.payment_type"
              class="paymentTypeRadioList"
            >
              <el-radio
                v-for="(payItem, payIndex) in payTypeList"
                :label="payItem.payType"
                :key="payIndex"
              >
                <div class="paymentTypeRadio">
                  <img style="width: 20px; height: 20px" :src="payItem.payImg" alt />
                  <div class="paymentTypeRadio_txt">
                    <div style="color: #222">
                      <b>{{ payItem.payName }}</b>
                    </div>
                    <div style="color: #999; font-size: 12px">
                      {{ payItem.payRemarks }}
                    </div>
                  </div>
                </div>
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="orderCancel()">取 消</el-button>
        <el-button size="small" type="primary" @click="submitPay(paymentForm)"
          >确定支付</el-button
        >
      </span>
    </el-dialog>

    <!-- 扫码支付 -->
    <el-dialog
      :title="scanningObj.Title"
      :visible.sync="scanningCodeDialog"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div
        style="width: 186px; height: 186px; border: 1px solid #eee; margin: auto"
        @click="paySuccess()"
      >
        <img src alt />
      </div>
      <p style="text-align: center; line-height: 40px; height: 40px">
        {{ scanningObj.Remarks }}
      </p>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="payback()">返回</el-button>
      </span>
    </el-dialog>

    <!-- 扫码支付 -->
    <el-dialog
      :visible.sync="paySuccessDialog"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div style="width: 111px; height: 111px; margin: auto">
        <img src="~assets/images/paySuccess.png" alt />
      </div>
      <p style="text-align: center; line-height: 40px; height: 40px">
        <b>支付成功</b>
      </p>
      <span slot="footer" class="dialog-footer">
        <nuxt-link to="/">
          <el-button size="small">返回首页</el-button>
        </nuxt-link>
        <el-button size="small" type="primary">查看订单</el-button>
      </span>
    </el-dialog>

    <!-- 全部地址 -->
    <el-dialog
      width="25%"
      title="全部地址"
      :visible.sync="addressDialog"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="addressDialog"
    >
      <el-radio-group v-model="defaultAddress">
        <el-radio
          class="select_address_list"
          :label="item.id"
          v-for="(item, index) in allAddressList"
          :key="index"
        >
          <div class="select_address_txt">
            <div style="color: #222">
              <span>{{ item.name }}</span>
              <span>{{ item.mobile }}</span>
            </div>
            <div style="color: #999">{{ item.full_address }}{{ item.address }}</div>
          </div>
        </el-radio>
      </el-radio-group>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="changeAddress" type="primary">确认选择</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Setting from "~/setting";
import wxpay from "../../assets/images/wxpay.png";
import AlipayTag from "../../assets/images/AlipayTag.png";
export default {
  auth: false,
  data() {
    return {
      userInfo: JSON.parse(localStorage.getItem("userInfo")),
      imgUrl: Setting.uplodBaseURL,
      defaultAddress: false,
      defaultCoupon: {},
      addressList: [],
      allAddressList: [],
      addressDialog: false,
      tableData: [],
      decrementList: [],
      paymentDialog: false,
      paymentForm: {
        payment_money: "",
        payment_type: "",
        is_balance: false,
        is_invoice: false,
        buyer_message: "",
      },
      payTypeList: [
        // {
        //   payType: 1,
        //   payName: "微信",
        //   payImg: wxpay,
        //   payRemarks: "使用微信扫描二维码即可付款",
        // },
        {
          payType: 2,
          payName: "支付宝",
          payImg: AlipayTag,
          payRemarks: "使用支付宝扫描二维码即可付款",
        },
      ],

      // 扫码
      scanningCodeDialog: false,
      scanningObj: {
        Title: "",
        Img: "",
        Remarks: "",
      },
      // 扫码成功
      paySuccessDialog: false,
      // 优惠折扣
      is_ShowCoupon: false,
      availableNum: 0,
      isCoupon: false,
      amount: "",
      Paid_in: "",
      Pre_price: "", //优惠价格
      Fare_Price: "", //运费
      Tobepaid: "",
      radio2: "",

      cart_ids: [], //购物车id
      sku_ids: [], //商品sku_id
      // init购物车订单返回信息
      orderInfo: {},
      // 选择优惠券数据
      couponform: {},
      // 创建订单后返回订单编号
      orderNum: "",
    };
  },

  created() {
    this.getAddressList({ isALL: false });
    this.cart_ids = this.$route.query.cart_ids;
    this.sku_ids = this.$route.query.sku_ids;
    this.init();
  },
  methods: {
    init(couponform) {
      let obj = {
        couponform: JSON.stringify(couponform),
        cart_ids: this.cart_ids,
        store_id: JSON.parse(localStorage.getItem("drugstoreObj")).id,
      };
      this.$axios
        .post(`/ordercreate/payment`, obj)
        .then((res) => {
          this.orderInfo = res.data;
          // console.log(this.orderInfo, 11111);

          this.decrementList = res.data.shop_goods_list.coupon_list;
          this.tableData = res.data.shop_goods_list.goods_list;
          this.amount = res.data.goods_money;
          if (this.orderInfo.delivery_money) {
            this.Paid_in =
              Number(this.orderInfo.goods_money) + Number(this.orderInfo.delivery_money);
          } else {
            this.Paid_in = Number(this.orderInfo.goods_money);
          }
          this.getCalculate();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getCalculate() {
      let obj = {
        cart_ids: this.orderInfo.cart_ids,
        app_type: "pc",
        app_type_name: "PC",
        token: localStorage.getItem("token"),
        store_id: JSON.parse(localStorage.getItem("drugstoreObj")).id,
      };
      this.$axios.post(`/ordercreate/calculate`, obj).then((res) => {
        console.log(res);
      });
    },
    // 获取默认地址
    getAddressList(OBJ) {
      let obj = {
        member_id: this.userInfo.member_id,
      };
      this.$axios
        .post(`/memberaddress/page`, obj)
        .then((res) => {
          if (!OBJ.isALL) {
            this.addressList = [];
            res.data.list.forEach((item) => {
              if (item.is_default) {
                this.addressList.push(item);
              }
            });
          } else {
            this.allAddressList = [];
            this.allAddressList = res.data.list;
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    //地址
    showAllAddressList() {
      this.addressDialog = true;
      this.getAddressList({ isALL: true });
    },
    changeAddress() {
      this.$axios
        .post("/memberaddress/setdefault", {
          id: this.defaultAddress,
        })
        .then((res) => {
          this.$message.success(res.message);
          this.getAddressList({ isALL: false });
          this.addressDialog = false;
        });
    },

    // 是否直接支付还是余额抵扣
    paidChange(val) {
      if (!val) {
        this.Tobepaid = this.Paid_in;
        this.paymentForm.is_balance = false;
      } else if (val) {
        let num = Number(this.userInfo.balance) - Number(this.Paid_in);
        this.paymentForm.is_balance = true;
        if (num < Number(this.userInfo.balance)) {
          this.Tobepaid = 0;
        } else if (num > Number(this.userInfo.balance)) {
          this.Tobepaid = num - Number(this.userInfo.balance);
        }
      }
    },

    radioChange(val) {
      // 再次点击取消选择，并不使用优惠券
      if (this.defaultCoupon.coupon_type_id == val.coupon_type_id) {
        this.defaultCoupon = {};
        this.Paid_in =
          Number(this.orderInfo.goods_money) + Number(this.orderInfo.delivery_money);
        this.Pre_price = 0; //优惠金额
        // this.Paid_in = this.amount;
        // this.Pre_price = this.amount - this.Paid_in;
      }
      // 选中使用优惠券折价
      else {
        this.defaultCoupon = val;
        let obj = {
          coupon: JSON.stringify({ coupon_id: val.coupon_id }),
          cart_ids: this.cart_ids,
          store_id: JSON.parse(localStorage.getItem("drugstoreObj")).id,
        };
        this.$axios.post(`/ordercreate/calculate `, obj).then((res) => {
          this.amount = res.data.goods_money; //总金额
          this.Paid_in = res.data.pay_money; //还需支付
          this.Pre_price = res.data.coupon_money; //优惠金额
        });
      }
    },
    getCouponId() {
      let obj = {
        couponURL: true,
        id: this.defaultCoupon.coupon_type_id,
      };
      this.$axios.post(`coupon/api/coupon/couponById`, obj).then((res) => {});
    },
    // 提交订单按钮 创建订单
    paymentType(row) {
      let obj = {
        cart_ids: this.cart_ids.toString(),
        buyer_message: this.paymentForm.buyer_message,
        is_balance: this.paymentForm.is_balance ? 1 : 0,
        delivery: { delivery_type: "express", delivery_type_name: "快递发货" }, //配送规则
        coupon: this.defaultCoupon, //优惠券
        is_invoice: this.paymentForm.is_invoice ? 1 : 0, //是否需要开发票
        store_id: JSON.parse(localStorage.getItem("drugstoreObj")).id,
      };
      // this.$axios.post(`/ordercreate/create`, obj).then((res) => {
      //   this.orderNum = res.data;
      // });

      this.$axios
        .post(`/ordercreate/create`, obj)
        .then(res => {
          if(res.code != 0){
            this.$message.error(res.message);
          }
          this.orderNum = res.data;
        })
        .catch(err => {
          this.$message.error(err);
        });



      this.paymentDialog = true;
    },
    // 提交订单弹出框取消按钮
    orderCancel() {
      this.paymentForm = {
        payment_money: "",
        payment_type: "",
        is_balance: false,
      };

      this.paymentDialog = false;
      this.$router.push("/order");
    },
    // 支付方式确认支付按钮
    submitPay(row) {
      // 不使用余额支付才会弹出扫码支付
      if (!this.paymentForm.is_balance) {
        this.scanningCodeDialog = true;

        // 支付宝扫码：

        if (row.payment_type == 1) {
          this.scanningObj = {
            Title: "微信扫码付款",
            Remarks: "请使用微信“扫一扫”扫描二维码支付",
          };
        } else {
          this.scanningObj = {
            Title: "支付宝扫码付款",
            Remarks: "请使用支付宝“扫一扫”扫描二维码支付",
          };
          let obj = {
            out_trade_no: this.orderNum,
            payCode: "ALIPAY_NATIVE",
          };
        }
      }
      // 使用余额支付
      else {
        let _data = {
          out_trade_no: this.orderNum
        }
        //获取支付信息
        this.$axios.post(`/pay/info`, _data).then((res) => {
          if (res.code == 0){
            //找到支付信息-发起余额支付
            let _payData = {
              out_trade_no: res.data.out_trade_no,
              pay_type: 'BALANCE',//余额支付
              return_url: '',
              is_balance: 1
            }
            //请求支付接口-完成余额支付
            this.$axios.post(`/pay/pay`, _payData).then((res2) => {
              if (res2.code == 0){
                this.paymentDialog = false;
                this.$router.push("/order"); //支付成功跳转订单列表页面
              }else{
                this.$message.error(res.message);
              }
            })
          }else{
            //未找到支付信息
            this.$message.error(`未找到支付信息`);
          }
          // this.paymentDialog = false;
          // this.$router.push("/order"); //支付成功跳转订单列表页面
        });
      }
      //this.paymentDialog = false;
      //this.$router.push("/order"); //支付成功跳转订单列表页面
    },
    // 扫码返回按钮
    payback() {
      this.paymentDialog = true;
      this.scanningCodeDialog = false;
    },

    // 扫码成功
    paySuccess() {
      this.paySuccessDialog = true;
    },
    // switch控制是否开发票弹出框
    invoiceChange(e) {
      console.log(e);
    },
  },
};
</script>
<style lang="scss" scoped>
.index {
  .crumbs {
    margin: 20px 0;
  }
  .submit_order_Box {
    width: 1200px;
    min-height: 920px;
    background: #ffffff;
    border-radius: 4px;
    margin-bottom: 20px;
    .select_address {
      display: flex;
      justify-content: space-between;
      padding: 30px;
      /deep/.el-radio-group {
        display: flex;
        .select_address_list {
          width: 280px;
          height: 60px;
          line-height: 60px;
          margin-right: 50px;
          display: flex;
          .el-radio__input {
            .el-radio__inner {
              margin-top: 23px;
            }
          }
          .select_address_txt {
            width: 320px;
            div {
              line-height: 30px;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
        }
      }
    }

    .submit_order_table {
      padding: 0 30px;
      .table_title {
        width: 150px;
        height: 25px;
        font-size: 18px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 600;
        color: #222222;
        line-height: 25px;
        margin: 20px 0;
      }
      .commodityBox {
        display: flex;
        img {
          width: 60px;
          height: 60px;
        }
        .commoditytxt {
          p {
            line-height: 30px;
            text-align: left;
            margin-left: 10px;
          }

          .p1 {
            font-weight: 600;
          }
          .p2 {
            font-size: 12px;

            span {
              background: #ff7d02;
              border-radius: 2px;
              width: 36px;
              padding: 3px 4px;
              color: #ffffff;
            }
            .commodityTagBg {
              background: #ff1449;
            }
          }
        }
      }
    }

    .select_coupon {
      padding: 0 30px;
      .el-form {
        margin-top: 20px;
        .el-form-item {
          margin-bottom: 0px;
        }
      }

      .coupon_title {
        width: 150px;
        height: 25px;
        font-size: 18px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 600;
        color: #222222;
        line-height: 25px;
        margin-top: 20px;
      }
      .couponCardList {
        padding-bottom: 20px;
        .couponCard {
          display: flex;
          /deep/.el-radio-group {
            display: flex;
            flex-wrap: wrap;
            .select_coupon_list {
              width: 380px;
              margin-right: 50px;
              margin-top: 20px;
              display: flex;
              .select_couponCard {
                width: 340px;
                height: 90px;
                background: linear-gradient(
                  146deg,
                  #ffe2bb 0%,
                  #ffeedc 35%,
                  #fcd8ab 100%
                );
                border: 1px solid rgba(255, 229, 195, 0.3);
                display: flex;
                justify-content: space-between;
                padding: 20px;
                margin-right: 60px;
                border-radius: 10px;
                color: rgba(240, 132, 51, 0.78);
                .couponCard_l {
                  width: 90px;
                  padding-right: 30px;
                  border-right: 1px dashed rgba(230, 201, 165, 0.8);
                  position: relative;
                  .couponCard_leftBg {
                    position: absolute;
                    top: 16px;
                    left: -30px;
                    width: 16px;
                    height: 16px;
                    background: #fff;
                    border-radius: 50%;
                  }
                }
                .couponCard_r {
                  width: 250px;
                  margin-left: 15px;
                  position: relative;
                  .couponCard_rt {
                    display: flex;
                    justify-content: space-between;
                    margin-bottom: 10px;
                    .couponCard_rt_btn {
                      background: linear-gradient(133deg, #fb6677 0%, #f33b50 100%);
                      border-radius: 14px;
                      color: #fff;
                      font-size: 12px;
                      line-height: 24px;
                      padding: 0px 20px;
                    }
                  }
                  .couponCard_rightBg {
                    position: absolute;
                    top: 16px;
                    right: -30px;
                    width: 16px;
                    height: 16px;
                    background: #fff;
                    border-radius: 50%;
                  }
                }
              }
              .el-radio__input {
                .el-radio__inner {
                  margin-top: 39px;
                }
              }
            }
          }
        }
        .couponCardList_bottom {
          margin-top: 20px;
          position: relative;
          .couponCardList_bottom_Box {
            display: flex;
            margin-top: 20px;
            .couponCardList_bottom_r {
              width: 150px;
              height: 20px;
              font-size: 14px;
              font-family: PingFangSC-Medium, PingFang SC;
              font-weight: 500;
              color: #585858;
              line-height: 20px;
            }
            .couponCardList_bottom_l {
              width: 100px;
              height: 20px;
              font-size: 14px;
              font-family: PingFangSC-Medium, PingFang SC;
              font-weight: 600;
              color: #222222;
              line-height: 20px;
            }
          }
          .couponCardList_bottom_btn {
            position: absolute;
            bottom: 0;
            right: 20px;
          }
        }
      }
    }
  }
  /deep/ .el-dialog__wrapper {
    .el-dialog {
      .el-dialog__body {
        .paymentDialogRadio {
          .el-radio {
            margin-bottom: 15px;
          }
        }
        .paymentTypeRadioList {
          margin-top: 15px;
          .el-radio {
            display: flex;
            .paymentTypeRadio {
              display: flex;
              .paymentTypeRadio_txt {
                div {
                  margin-bottom: 15px;
                  padding-left: 15px;
                }
              }
            }
          }
        }
      }
    }
  }
  .addressDialog {
    /deep/ .el-dialog {
      .el-dialog__body {
        .el-radio-group {
          .select_address_list {
            display: flex;
            width: 280px;
            height: 60px;

            margin-right: 50px;
          }
        }
      }
    }
  }
}
</style>
