<template>
  <div class="goodsOrder">
    <m-header :backUrl="backUrl" />
    <van-tabs color="#01C1B5" title-active-color="#000" @change="onTabChange" title-inactive-color="#808080" v-model="activeTab">
      <van-tab title="待支付" name="ING">
        <search @onSearch="onSearch" placeholder="请输入学生姓名或手机号" style="margin-bottom: 0.15rem" />
        <van-list v-model="loading" v-if="dataShow" key="ing" :finished="finished" :immediate-check="false" finished-text=" " @load="getGoodsList()">
          <van-cell-group class="order-section" :border="false" v-for="(list, index) in dataList" :key="index" @click="onGoodDetail(list)">
            <van-cell title-class="order-title" value-class="order-status">
              <template #title>学生姓名：{{ list.userName }}</template>
              <template>待支付</template>
            </van-cell>
            <van-cell v-for="(item, i) in list.goodsJson" :border="i == list.goodsJson.length - 1 ? true : false" :key="i" :class="[i != list.goodsJson.length - 1 ? 'input-bottom' : null, 'input-cell']" class="input-cell" :center="true">
              <template slot="icon">
                <van-image :src="item.image" class="logo">
                  <template v-slot:loading>
                    <van-loading type="spinner" size="20" />
                  </template>
                </van-image>
              </template>
              <template slot="title">
                {{ item.goodsName }}
                <p class="money">￥{{ item.goodsPrice | moneyFormat }}</p>
              </template>
              <template #default> x {{ item.goodsNum }} </template>
            </van-cell>
            <van-cell title-class="order-money" title-style="flex: auto 1" style="align-items: center" class="van-hairline--top">
              <template #title>
                订单金额：<span>¥{{ list.totalAmount | moneyFormat }}</span>
              </template>
              <template>
                <van-button size="small" round class="van-small__btn" @click.stop="onRePay(list)" type="default">继续支付</van-button>
              </template>
            </van-cell>
          </van-cell-group>
        </van-list>
        <m-empty v-else msg="暂无订单" />
      </van-tab>
      <van-tab title="已支付" name="SUCCESS">
        <search @onSearch="onSearch2" placeholder="请输入学生姓名或手机号" style="margin-bottom: 0.15rem" />
        <van-list v-model="loading2" v-if="dataShow2" key="success" :immediate-check="false" :finished="finished2" finished-text=" " @load="getGoodsList2()">
          <van-cell-group class="order-section" :border="false" v-for="(list, index) in dataList2" :key="index" @click="onGoodDetail(list)">
            <van-cell title-class="order-title" value-class="order-status success">
              <template #title>学生姓名：{{ list.userName }} <span style="padding-left: 0.1rem" v-if="list.authorUser != operationId">学员自建</span></template>
              <template>支付成功</template>
            </van-cell>
            <van-cell v-for="(item, i) in list.goodsJson" :border="i == list.goodsJson.length - 1 ? true : false" :key="i" :class="[i != list.goodsJson.length - 1 ? 'input-bottom' : null, 'input-cell']" :center="true">
              <template slot="icon">
                <van-image :src="item.image" class="logo">
                  <template v-slot:loading>
                    <van-loading type="spinner" size="20" />
                  </template>
                </van-image>
              </template>
              <template slot="title">
                {{ item.goodsName }}
                <p class="money">￥{{ item.goodsPrice | moneyFormat }}</p>
              </template>
              <template #default> x {{ item.goodsNum }} </template>
            </van-cell>
            <van-cell title-class="order-money" class="van-hairline--top order-payment" title=" ">
              <template #title>
                订单金额：<span>¥{{ list.totalAmount | moneyFormat }}</span>
              </template>
              <template>
                <div>
                  <div class="order-money-get" v-if="list.receiveStatus == 'NO_RECEIVE'">未确认</div>
                  <div v-if="list.receiveStatus == 'AUTO_RECEIVE'">自动确认收货</div>
                  <div v-if="list.receiveStatus == 'MANUAL_RECEIVE'">手动确认收货</div>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
        </van-list>
        <m-empty v-else msg="暂无订单" />
      </van-tab>
    </van-tabs>

    <m-payment :closeStatus="isStatus" :amount="payMoney" :payment="payment" @onChangeStatus="onChangeStatus" />
  </div>
</template>

<script>
/* eslint-disable */
import { queryStudentGoodsOrders, addGoodsSellOrder } from "./api";
import MHeader from "@/components/header";
import MEmpty from "@/components/MEmpty";
import MPayment from "@/components/MPayment";
import Search from "@/components/Search";
import setLoading from "@/common/loading";
export default {
  name: "goodsOrder",
  components: {
    MHeader,
    MEmpty,
    Search,
    MPayment,
  },
  data() {
    let query = this.$route.query;
    let operationId = localStorage.getItem("operationId");
    return {
      operationId: operationId,
      activeTab: query.activeTab ? query.activeTab : "ING",
      isStatus: false,
      payment: {}, // 支付对象
      payMoney: 0,
      dataList: [],
      dataShow: true,
      loading: false,
      finished: false,
      params: {
        search: null,
        status: "ING",
        page: 1,
        rows: 10,
      },
      dataList2: [],
      dataShow2: true,
      loading2: false,
      finished2: false,
      params2: {
        search: null,
        status: "SUCCESS",
        page: 1,
        rows: 10,
      },
      backUrl: {
        status: true,
        path: "/serviceStudent",
      },
    };
  },
  async mounted() {
    // 判断是否在app里面
    localStorage.removeItem("orderGoodsDetail");
    await this.onTabChange();
  },
  methods: {
    onTabChange() {
      if (this.activeTab == "ING") {
        this.getGoodsList();
      } else if (this.activeTab == "SUCCESS") {
        this.getGoodsList2();
      }
    },
    onGoodDetail(item) {
      localStorage.setItem("orderGoodsDetail", JSON.stringify(item));
      this.$router.push({
        path: "/goodsOrderDetail",
        query: {
          activeTab: this.activeTab,
        },
      });
    },
    onSearch(value) {
      this.params.search = value;
      this.params.page = 1;
      this.dataList = [];
      this.dataShow = true;
      this.loading = true;
      this.finished = false;
      this.getGoodsList();
    },
    async getGoodsList() {
      let params = this.params;
      try {
        await queryStudentGoodsOrders(params).then((res) => {
          let result = res.data;
          this.loading = false;
          if (res.code == 200) {
            let rows = result.rows;
            rows.forEach((item) => {
              item.goodsJson = item.goodsJson ? JSON.parse(item.goodsJson) : [];
            });
            this.dataList.push(...rows);
            if (params.page >= Math.ceil(result.total / params.rows)) {
              this.finished = true;
            }
            this.params.page++;
          } else {
            this.finished = true;
          }
          if (this.dataList.length <= 0) {
            this.dataShow = false;
          }
        });
      } catch {
        //
      }
    },
    onSearch2(value) {
      this.params2.search = value;
      this.params2.page = 1;
      this.dataList2 = [];
      this.dataShow2 = true;
      this.loading2 = true;
      this.finished2 = false;
      this.getGoodsList2();
    },
    async getGoodsList2() {
      let params = this.params2;
      try {
        await queryStudentGoodsOrders(params).then((res) => {
          let result = res.data;
          this.loading2 = false;
          if (res.code == 200) {
            let rows = result.rows;
            rows.forEach((item) => {
              item.goodsJson = item.goodsJson ? JSON.parse(item.goodsJson) : [];
            });
            this.dataList2.push(...rows);
            if (params.page >= Math.ceil(result.total / params.rows)) {
              this.finished2 = true;
            }
            this.params2.page++;
          } else {
            this.finished2 = true;
          }
          if (this.dataList2.length <= 0) {
            this.dataShow2 = false;
          }
        });
      } catch {
        //
      }
    },
    async onChangeStatus(val) {
      this.isStatus = val;
      this.dataList = [];
      this.dataShow = true;
      this.loading = true;
      this.finished = false;
      this.params = {
        status: "ING",
        page: 1,
        rows: 10,
      };
      this.getGoodsList();
    },
    onRePay(item) {
      // 是否继续支付
      this.$dialog
        .confirm({
          message: "是否继续支付该订单？",
          confirmButtonColor: "#269a93",
          cancelButtonText: "取消",
          confirmButtonText: "继续支付",
        })
        .then(() => {
          this.buy(item);
        })
        .catch(() => {
          this.$dialog.close();
        });
    },
    async buy(item) {
      let goodsList = this.goodsList;
      setLoading(true);
      await addGoodsSellOrder({
        userId: item.userId,
        goodsSellDtos: item.goodsJson,
        isRepeatPay: true,
        marketAmount: item.marketAmount,
        orderNo: item.orderNo,
        id: item.id,
      })
        .then((res) => {
          setLoading(false);
          let result = res.data;
          if (result.code == 200) {
            this.result = result.data;
            this.onSubmit();
          } else if (result.code == 201) {
            this.$toast(result.msg);
            this.$router.push({
              path: "/paymentResult",
              query: {
                type: "on",
                isBack: "off",
              },
            });
          } else {
            this.$toast(result.msg);
          }
        })
        .catch(() => {
          setLoading(false);
        });
    },
    onSubmit() {
      // submit 提交
      let result = this.result;
      if (result.type == "YQPAY") {
        let f = result.payMap;
        document.querySelector("#onSubmit").action = f.host;
        document.querySelector("#apiContent").value = f.apiContent;
        document.querySelector("#merNo").value = f.merNo;
        document.querySelector("#notifyUrl").value = f.notifyUrl;
        document.querySelector("#sign").value = f.sign;
        document.querySelector("#signType").value = f.signType;
        document.querySelector("#timestamp").value = f.timestamp;
        document.querySelector("#version").value = f.version;
        document.querySelector("#onSubmit").submit();
      } else if (result.type == "UNIONPAY") {
        localStorage.setItem("payInfo", JSON.stringify(result));
        this.$router.push({
          path: "/alipay",
          query: {
            balance: result.totalPrice,
          },
        });
      } else if (result.type == "ADAPAY" || result.type == "YEEPAY") {
        this.payment = result;
        this.payMoney = result.payMap.amount;
        // 开始支付窗口
        this.isStatus = true;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.goodsOrder {
  min-height: 100vh;
  overflow: hidden;
}

.order-section {
  margin: 0 0.12rem 0.16rem;
  border-radius: 0.08rem;
  overflow: hidden;
}
/deep/.van-tabs--line .van-tabs__wrap {
  height: 0.44rem;
}

.order-title {
  color: #808080;
  font-size: 0.14rem;
  flex: auto 1;
}

.order-status {
  font-size: 0.14rem;
  color: #f5222d;

  &.success {
    color: #01c1b5;
  }
}

.van-small__btn {
  font-size: 0.14rem;
  background-color: #f85043;
  border-color: #f85043;
  color: #fff;
  height: 0.3rem;
  padding: 0 0.08rem;
  line-height: 0.28rem;
}

.order-money {
  color: #000;
  font-size: 0.16rem;

  span {
    color: #ff3535;
  }
}
.order-payment {
  // margin-top: .15rem;
}

.input-cell {
  padding: 0.15rem 0.16rem;
  &.input-bottom {
    padding-bottom: 0;
  }
  .logo {
    width: 1rem;
    height: 1rem;
    margin-right: 0.15rem;
    border-radius: 0.05rem;
  }

  .money {
    color: #ff3535;
    font-weight: 600;
    font-size: 0.18rem;
  }

  /deep/.van-cell__title {
    font-size: 0.16rem;
    color: #000000;
    flex-basis: 47%;
  }

  /deep/.van-cell__value {
    height: 0.2rem;
  }
}
</style>
