<template>
  <view class="content clearfix">
    <view class="notice send_info" v-html="sendInfo || ''"></view>
    <view class="content1">
      <view v-for="(item, key) in datas" :key="key" class="content1-list">
        <view class="twoleft">
          <checkbox-group @change="selectAll(item)">
            <label class="align-center flex-row">
              <checkbox
                :checked="item.check"
                color="orange"
                style="transform: scale(0.7)"
              />
              <span class="content-title">{{ item.shop_name }}</span>
            </label>
          </checkbox-group>

          <view v-for="(ele, i) in item.relations" :key="i">
            <checkbox-group @change="selected(item, ele)">
              <label class="item-list">
                <checkbox
                  :checked="ele.check"
                  color="orange"
                  style="transform: scale(0.7)"
                />
                <view class="content1-list_img">
                  <image mode :src="ele.img"></image>
                </view>
                <view class="commodity-box">
                  <view class="content1-list_text1">{{ ele.name }}</view>
                  <!-- <view class="content1-list_text2">{{ele.send_info}}</view> -->
                  <view
                    v-if="ele.attribute.length"
                    class="content1-list_text3"
                    >{{ ele.attribute[0] }}</view
                  >
                  <view class="content1-list_text4">
                    <view class="content1-list_right" @tap.stop="reduce(ele)">
                      <image
                        mode
                        src="@/assets/icon_v1/del.png"
                        style="width: 24rpx; height: 24rpx"
                      ></image>
                    </view>
                    <input
                      v-model="ele.num"
                      class="content1-list_input"
                      :disabled="ele.status == 2 ? true : false"
                      type="number"
                      @blur="starBlur(ele)"
                    />
                    <view class="content1-list_left" @tap.stop="add(ele)">
                      <image
                        mode
                        src="@/assets/icon_v1/add.png"
                        style="width: 24rpx; height: 24rpx"
                      ></image>
                    </view>
                  </view>
                </view>
              </label>
            </checkbox-group>
          </view>
        </view>
        <!-- <view class="del">
					<uni-icons class="del" color="orange" type="trash" size="18" @tap="del(item,index)"></uni-icons>
				</view> -->
      </view>
    </view>
    <view class="foot">
      <view
        class="button"
        :style="'opacity:' + (isCheck ? '' : '0.6') + ';'"
        @tap="confirmRetrieve"
        >卖二手</view
      >
      <view
        class="button button-border"
        :style="'opacity:' + (canSend ? '' : '0.6') + ';'"
        @tap="confirmSend"
        >发货</view
      >
    </view>
    <uni-popup
      ref="popup"
      style="z-index: 99 !important"
      type="bottom"
      @click="noTouch"
    >
      <view class="goods">
        <view class="goods-title">发货确认</view>
        <view class="notice" style="float: left">
          <view class="notice-img">
            <image mode src="@/assets/icon_v1/Notice1@2x.png"></image>
          </view>
          <view class="notice-text">{{ "" + notice + "" }}</view>
        </view>
        <view v-if="address" class="goods-address">
          <view class="goods-address_name">{{
            "" + address.name + " " + address.phone + ""
          }}</view>
          <view class="goods-address_text1" @tap="chooseAddress">
            修改地址
          </view>
          <view class="goods-address_text">{{
            "" + address.city + address.address + ""
          }}</view>
        </view>
        <view v-if="!address" class="goods-remarks1">
          <view class="goods-remarks-text1" style="width: 408rpx"
            >请填写收货地址</view
          >
          <view class="goods-address_text1" @tap="chooseAddress">去填写</view>
        </view>
        <view class="goods-remarks2">
          <view class="goods-remarks-text">发货备注</view>
          <textarea
            v-model="remarks"
            auto-height="true"
            placeholder="请填写备注信息"
            maxlength="50"
            style="
              display: block;
              margin-left: 20rpx;
              color: #999;
              width: 700rpx;
            "
            type="text"
          />
        </view>
        <view class="goods-payment">
          <template v-if="!freeShipping">
            <view class="goods-payment_img">
              <image mode src="@/assets/icon_v1/hair@2x.png"></image>
            </view>
            <view class="goods-payment_text"
              >需要支付运费<text style="color: red">8</text> 元</view
            >
            <view class="button-border" @tap="cancel">取消</view>
            <view
              v-if="numAll > 0"
              class="button"
              :style="address ? '' : 'opacity:0.6'"
              @tap="payment"
            >
              <view class="_b">支付运费</view>
            </view>
          </template>
          <template v-else>
            <view class="button-border" @tap="cancel">取消</view
            ><view
              class="button"
              :style="address ? '' : 'opacity:0.6'"
              @tap="payment"
              >确定</view
            >
          </template>
        </view>
        <view
          v-if="protects == true"
          style="
            width: 750rpx;
            height: 42rpx;
            background-color: #ffffff;
            float: left;
          "
        ></view>
      </view>
    </uni-popup>
    <uni-popup ref="popup_place_false" type="center">
      <view class="popup-recovery">
        <view class="popup-overtime_img">
          <image mode src="@/assets/icon_v1/success@2x.png"></image>
        </view>
        <view class="popup-overtime_text">申请成功</view>
        <view class="popup-overtime_text1">仓库小哥已经收到你的请求，</view>
        <view class="popup-overtime_text1">会尽快帮你发货的</view>
        <view class="popup-overtime-btns">
          <view class="button button-border" @tap="home">回首页</view>
          <view class="button" @tap="orderInfo">查看发货单</view>
        </view>
      </view>
    </uni-popup>
    <uni-popup ref="retrieve_confirm" type="bottom">
      <view class="pop confirm_retrieve">
        <view class="p_head">卖二手</view>
        <view class="p_body">
          <view class="align-center flex-col">
            <view class="hx_used" style="margin-top: 30rpx">
              <text>用户</text>
              <image class="img-s" mode :src="retrieve['avatar']"></image>
              <text style="line-height: 50rpx"
                >{{ retrieve["nickname"] }} 想要求购以上商品，共计{{
                  retrievePrice
                }}元，可在我的 - 消费记录里查看回血明细。</text
              >
            </view>
          </view>
        </view>
        <view class="p_foot between">
          <view class="button button-border" @tap="confirmRetrieveCancel"
            >取消</view
          >
          <view class="button" @tap="submitRetrieve">卖出</view>
        </view>
      </view>
    </uni-popup>

    <uni-popup ref="retrieve_done" type="bottom">
      <view class="pop confirm_retrieve">
        <view class="p_head">卖二手</view>
        <view class="p_body">
          <view class="align-center flex-col">
            <view class="hx_used" style="margin-top: 30rpx">
              您本次获得 <text style="color: red">{{ retrievePrice }}</text> 元
            </view>
            <view class="hx_used"> 目前账户余额 {{ balance }} 元 </view>
          </view>
        </view>
        <view class="p_foot center">
          <view class="button" @tap="submitRetrieveDone">完成</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import api from "@/lib/api/api";
export default {
  name: "PageOrderUnsend",
  data() {
    return {
      num: 0,
      address: "",
      remarks: "",
      mask: !1,
      datas: [],
      protects: "",
      disabled: !1,
      notice: "请确保当面核对包裹信息",
      isCheck: false,
      canSend: false,
      sendList: [],
      numAll: 0,
      sendInfo: "",
      userInfo: {},
      retrievePrice: 0, // 回血用
      retrieve: {},
      balance: 0, // 回血用
      freeShipping: false,
    };
  },
  onShow() {
    const e = getCurrentPages();
    this.address = e[e.length - 1].data.address;
    //
    const uinfoStr = uni.getStorageSync("userinfo");
    if (uinfoStr) {
      this.userInfo = JSON.parse(uinfoStr);
    } else {
      this.userInfo = {};
      uni.showToast({
        title: "请先登录",
        icon: "none",
      });
      return;
    }
  },
  onLoad() {
    const uinfoStr = uni.getStorageSync("userinfo");
    if (uinfoStr) {
      this.userInfo = JSON.parse(uinfoStr);
      this.loadData();
    }
    //
  },
  methods: {
    // 页面刷新
    refresh() {
      this.init(); // 初始化值
      this.loadData();
    },
    //
    init() {
      this.num = 0;
      this.address = "";
      this.remarks = "";
      this.mask = !1;
      this.datas = [];
      this.protects = "";
      this.disabled = !1;
      this.notice = "请确保当面核对包裹信息";
      this.isCheck = false;
      this.canSend = false;
      this.sendList = [];
      this.numAll = 0;
      this.sendInfo = "";
      this.retrievePrice = 0; // 回血用
      this.retrieve = {}; // 回血用
      this.balance = 0; // 回血用
    },
    loadData() {
      api
        .unSendList(this.userInfo.session)
        .then((data) => {
          if (data.data) {
            this.datas = data.data;
            this.sendInfo = data.send_info;
            this.datas.filter((item) => {
              //设置店铺选中状态
              this.$set(item, "check", false);
              item.relations.filter((ele) => {
                //设置单个商品选中状态
                this.$set(ele, "check", false);
                this.$set(ele, "num1", ele.num);
              });
              //设置是否可以选中
              if (item.relations.every((val) => val.status === 2)) {
                this.$set(item, "status", 2);
              }
            });
          }
        })
        .catch(() => {
          uni.showToast({
            icon: "none",
            title: "服务器错误，请稍后重试",
            duration: 2e3,
          });
          return;
        });
    },
    //全选
    selectAll(item) {
      item.check = !item.check;
      item.relations.forEach((el) => (el.check = item.check));

      //发货按钮状态
      const btnStatus = [];
      const notSent = [];
      this.datas.forEach((val) => {
        val.relations.forEach((el) => {
          if (el.check) {
            btnStatus.push(el);
            if (el.status === 2) {
              notSent.push(el);
            }
          }
        });
      });
      if (btnStatus.length > 0) {
        this.isCheck = true;
        this.canSend = notSent.length === 0;
      } else {
        this.isCheck = false;
        this.canSend = false;
      }
      //
      // this.sendList = []
      // for(let i = 0; i<this.datas.length; i++){
      // 	for(let j =0; j<this.datas[i].relations.length; j++){
      // 		if(this.datas[i].relations[j].check){
      // 			this.sendList.push({
      // 				"sku_id": ""+this.datas[i].relations[j].id,
      // 				"num": ""+this.datas[i].relations[j].num
      // 			})
      // 		}
      // 	}
      // }
    },
    // 单个商品前的勾选
    selected(item, ele) {
      ele.check = !ele.check; //设置单个商品的选中状态
      //是否全部选中该店铺下的所有商品>>>单个商品都为true，店铺也应为true
      item.check = item.relations.every((val) => val.check == true);

      //发货按钮状态
      const btnStatus = [];
      const notSent = [];
      this.datas.forEach((val) => {
        val.relations.forEach((el) => {
          if (el.check) {
            btnStatus.push(el);
            if (el.status === 2) {
              notSent.push(el);
            }
          }
        });
      });
      if (btnStatus.length > 0) {
        this.isCheck = true;
        this.canSend = notSent.length === 0;
      } else {
        this.isCheck = false;
        this.canSend = false;
      }
      //
      // this.sendList = []
      // for(let i = 0; i<this.datas.length; i++){
      // 	for(let j =0; j<this.datas[i].relations.length; j++){
      // 		if(this.datas[i].relations[j].check){
      // 			this.sendList.push({
      // 				"sku_id": ""+this.datas[i].relations[j].id,
      // 				"num": ""+this.datas[i].relations[j].num
      // 			})
      // 		}
      // 	}
      // }
    },
    add(t) {
      t.num = +t.num || 0;
      if (t.num < t.num1) {
        t.num++;
      } else {
        uni.showToast({
          icon: "none",
          title: "已到达最大值",
          duration: 2e3,
        });
      }
    },
    reduce(t) {
      t.num = +t.num || 0;
      if (t.num > 1) {
        t.num--;
      }
    },
    starBlur(t) {
      t.num = +t.num || 0;
      if (t.num < 1 || 0 === t.num || "" === t.num) {
        t.num = t.num1;
      }
      if (t.num > t.num1) {
        t.num = t.num1;
      }
    },
    cancel() {
      this.disabled = false;
      this.$refs.popup.close();
    },
    async confirmSend() {
      this.sendList = [];
      for (let i = 0; i < this.datas.length; i++) {
        for (let j = 0; j < this.datas[i].relations.length; j++) {
          if (this.datas[i].relations[j].check) {
            this.sendList.push({
              sku_id: "" + this.datas[i].relations[j].id,
              num: "" + this.datas[i].relations[j].num,
            });
          }
        }
      }
      if (this.sendList.length == 0) {
        uni.showToast({
          icon: "none",
          title: "请选择要发货的商品",
          duration: 2e3,
        });
        return;
      }

      if (!this.canSend) {
        uni.showToast({
          icon: "none",
          title: "选择商品中存在不可发货商品",
          duration: 2e3,
        });
        return;
      }

      const res = await api
        .checkIsFreeShipping({
          session: this.userInfo.session,
          skus: this.sendList,
        })
        .catch((e) => {
          return {
            errno: 404,
            errmsg: e.message || "请求失败，请重试",
          };
        });

      if (res.errno === 10000) {
        this.freeShipping = res?.free_shipping === 1;

        this.disabled = true;
        this.numAll = 0;
        this.sendList.forEach((item) => {
          this.numAll = Number(this.numAll) + Number(item.num);
        });
        this.$refs.popup.open();
      } else {
        uni.showToast({
          icon: "none",
          title: res.errmsg || "请求失败，请重试",
          duration: 2e3,
        });
      }
    },
    confirmRetrieveCancel() {
      this.$refs.retrieve_confirm.close();
    },
    submitRetrieveDone() {
      this.refresh();
      this.$refs.retrieve_done.close();
    },
    confirmRetrieve() {
      // 寄存柜，预回血操作
      this.sendList = [];
      for (let i = 0; i < this.datas.length; i++) {
        for (let j = 0; j < this.datas[i].relations.length; j++) {
          if (this.datas[i].relations[j].check) {
            this.sendList.push({
              sku_id: "" + this.datas[i].relations[j].id,
              num: "" + this.datas[i].relations[j].num,
            });
          }
        }
      }
      if (this.sendList.length == 0) {
        uni.showToast({
          icon: "none",
          title: "请选择要回血的商品",
          duration: 2e3,
        });
        return;
      } else {
        api
          .preSkuRetrieve({
            session: this.userInfo.session,
            skus: this.sendList,
          })
          .then((data) => {
            if (data.errno != 10000) {
              uni.showToast({
                title: data.errmsg,
                icon: "error",
                mask: true,
                duration: 2e3,
              });
              return;
            }
            this.retrievePrice = data.data.retrieve_price;
            this.retrieve = data.data.retrive;
            this.$refs.retrieve_confirm.open();
          })
          .catch(() => {
            uni.showToast({
              icon: "none",
              title: "回收失败，请稍后重试",
              duration: 2e3,
            });
          });
        return;
      }
    },
    submitRetrieve() {
      this.$refs.retrieve_confirm.close();
      // 寄存柜回收
      if (this.sendList.length < 1) {
        uni.showToast({
          icon: "none",
          title: "请选择需要回血的商品",
          duration: 2e3,
        });
        return;
      }
      //
      api
        .finalSkuRetrieve({
          session: this.userInfo.session,
          skus: this.sendList,
        })
        .then((data) => {
          if (data.errno != 10000) {
            uni.showToast({
              title: data.errmsg,
              icon: "error",
              mask: true,
              duration: 2e3,
            });
            return;
          }
          this.retrievePrice = data.data.retrieve_price;
          this.balance = data.data.balance;
          this.$refs.retrieve_done.open();
        })
        .catch(() => {
          uni.showToast({
            icon: "none",
            title: "回收失败，请稍后重试",
            duration: 2e3,
          });
        });
      return;
    },
    chooseAddress() {
      uni.navigateTo({
        url: "../address/address?action=choose",
      });
    },
    showRes() {
      this.$refs.popup.close();
      this.$refs.popup_place_false.open();
      this.refresh();
    },
    payment() {
      if (!this.address || this.address.id < 1) {
        uni.showToast({
          icon: "none",
          title: "请选择收获地址",
          duration: 2e3,
        });
        return;
      }
      if (this.sendList.length < 1) {
        uni.showToast({
          icon: "none",
          title: "你还没有需要发货的商品",
          duration: 2e3,
        });
        this.$refs.popup.close();
        return;
      }

      api
        .sendOrder({
          session: this.userInfo.session,
          beizhu: this.remarks,
          skus: this.sendList,
          address_id: "" + this.address.id,
        })
        .then((data) => {
          if (data.data.paySign == undefined) {
            this.showRes();
          } else {
            // 微信支付运费
            uni.showToast({
              title: "支付中",
              icon: "loading",
              mask: true,
              duration: 10e3,
            });
            uni.hideToast();
            uni.requestPayment({
              provider: "wxpay",
              timeStamp: data.data.timeStamp,
              nonceStr: data.data.nonceStr,
              package: data.data.package,
              signType: data.data.signType,
              paySign: data.data.paySign,
              success(res) {
                if (res.errMsg === "requestPayment:ok") {
                  this.getPrepaySucceedOrder(data.data.id);
                }
              },
              fail(err) {
                if (err.errMsg === "requestPayment:fail cancel") {
                  this.getPrepayStatusOrder("3", data.data.id);
                } else {
                  this.getPrepayStatusOrder("2", data.data.id);
                }
              },
            });
          }
        })
        .catch(() => {
          uni.showToast({
            icon: "none",
            title: "发货失败，请稍后重试",
            duration: 2e3,
          });
        });
    },
    getPrepayStatusOrder(type, id) {
      const params = {
        session: this.userInfo.session,
        id: "" + id,
        type: "" + type,
      };
      api
        .getPrepayStatusOrder(params)
        .then(() => {
          uni.showToast({
            title: type == "3" ? "取消支付" : "支付失败",
            icon: "error",
            mask: true,
            duration: 2e3,
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    getPrepaySucceedOrder(id) {
      let timer;
      api
        .getPrepaySucceedOrder({
          session: this.userInfo.session,
          id: "" + id,
          times: "" + this.testInt++,
        })
        .then((data) => {
          if (data.errno == 90000) {
            if (this.queryPayIng) {
              this.queryPayIng = false;
              uni.showLoading({
                title: "加载中",
                mask: true,
              });
            }
            timer = setTimeout(() => {
              this.getPrepaySucceedOrder(id);
            }, 1000);
          } else if (data.errno == 10000) {
            this.queryPayIng = true;
            uni.hideLoading();
            uni.showToast({
              title: "支付成功",
              icon: "success",
              mask: true,
              duration: 2e3,
            });
            if (data.data.status == 1) {
              this.showRes();
            }
            clearTimeout(timer); //清理定时任务
          } else {
            this.queryPayIng = true;
            uni.hideLoading();
            uni.showToast({
              title: "订单查询失败",
              icon: "error",
              mask: true,
              duration: 2e3,
            });
            clearTimeout(timer); //清理定时任务
          }
        })
        .catch(() => {
          this.queryPayIng = true;
          uni.hideLoading();
          clearTimeout(timer); //清理定时任务
        });
    },
    home() {
      uni.switchTab({
        url: "../index/index",
      });
    },
    orderInfo() {
      this.$refs.popup_place_false.close();
      uni.redirectTo({
        url: "./sended",
      });
    },
  },
};
</script>

<style lang="scss">
@import "./unsend.scss";
</style>
