<template>
  <BasePage>
    <div class="tradelist">
      <div class="tabs">
        <van-tabs class="area" v-model:active="TradeArea" color="#f00" title-active-color="#222"
          title-inactive-color="#999" line-width="0" line-height=".667vw" @change="changeMall">
          <van-tab v-for="i in mallList" :title="i.label" :name="i.value"></van-tab>
        </van-tabs>

        <van-tabs class="states" v-model:active="activeTab" color="#ca2904" title-active-color="#ca2904"
          title-inactive-color="#000" line-width="4vw" line-height=".667vw" @change="onTabChange">
          <van-tab title="全部" name=""></van-tab>
          <van-tab v-for="i in tradeStates" :title="i.label" :name="String(i.value)"></van-tab>
        </van-tabs>
      </div>
      <van-search v-model="_searchParams.ordernum" left-icon=" " shape="round" placeholder="输入订单号搜索" @search="onSearch"
        @clear="onClear">
        <template #right-icon>
          <van-icon name="/img/sort-search.png" @click="onSearch"></van-icon>
        </template>
      </van-search>

      <BaseList ref="baseList" url="/v1/client/FOrdersClient" :params="searchParams" :parseData="parseData"
        style="padding: 3.33vw;" @refresh="onRefresh">
        <template #default="{ item }">
          <div class="list">
            <!-- 买单订单 -->
            <template v-if="item.shopname">
              <div class="merchant_info">
                <img class="icon" :src="$file(item.shopimg)" alt="">
                <div class="inf">
                  <span>{{ item.shopname }}</span>
                  <div>
                    <p>￥{{ item.ordermoney?.toFixed(2) }}</p>
                    <span class="dr" v-if="item.discountratio">{{ item.discountratio }}%让利</span>
                  </div>
                </div>
              </div>
              <div class="price">
                实付：<span>￥<b>{{ item.realmoney?.toFixed(2) }}</b></span>
              </div>
              <div class="detail_box">
                <div>
                  <span>订单编号:</span>
                  <span class="r">{{ item.ordernum }}<img src="/img/copy_b.png"
                      @click="$copyText(item.ordernum); $showSuccessToast('复制成功')" alt=""></span>
                </div>
                <div>
                  <span>下单时间:</span>
                  <span class="r">{{ $formatGMT(item.addtime, 'yyyy-MM-dd HH:mm:ss') }}</span>
                </div>
              </div>
              <div class="state_box">
                <b :class="'b' + item.state">{{ item.statename }}</b>
                <div class="btn_box">
                  <button @click="$navigate(`MerchantTradeDetail?id=${item.ordernum}&type=user`)">查看详情</button>
                </div>
              </div>
            </template>
            <!-- 商城/礼包订单 -->
            <template v-else>
              <div class="order_box">
                <span>订单编号:{{ item.ordernum }}</span>
                <img src="/img/copy_b.png" @click="$copyText(item.ordernum); $showSuccessToast('复制成功')" alt="">
              </div>
              <div class="goods_box">
                <img :src="$file(item.proimg)" alt="">
                <div class="goods_info">
                  <div class="tit">{{ item.proname }}</div>
                  <div class="spec">
                    <span>{{ item.proskuname }}</span>
                    <p>x{{ item.buynums }}</p>
                  </div>
                  <div class="concession">
                    <span>¥{{ item.proskusaleprice?.toFixed(2) }}</span>
                    <p v-if="item.discountratio">{{ item.discountratio }}%让利</p>
                  </div>
                </div>
              </div>
              <div class="price">
                实付：<span>￥<b>{{ item.realmoney?.toFixed(2) }}</b></span>
              </div>
              <div class="state_box">
                <b :class="'b' + item.state">{{ item.statename }}</b>
                <div class="btn_box">
                  <button v-if="item.state === 0" @click="cancelTrade(item)">取消订单</button>
                  <button @click="$navigate(`TradeDetail?ordernum=${item.ordernum}`)">查看详情</button>
                  <button v-if="item.state === 3" @click="confirmReceipt(item)">确认收货</button>
                  <button v-if="item.state === 0" @click="$navigate(`Pay?ordernum=${item.ordernum}`)">立即支付</button>
                </div>
              </div>
            </template>
          </div>
        </template>
      </BaseList>
    </div>
  </BasePage>
</template>

<script>
export default {
  name: 'TradeList',
  data() {
    return {
      activeTab: '',
      TradeArea: 0,
      _initialized: false,
      _searchParams: {
        ordernum: '',
        state: '',
      },
      tradeStates: [
      ],
      mallList: [
      ],
    }
  },
  mounted() {
    Promise.all([
      this.$get('/v1/client/FOrdersClient/orderstate'),
      this.$get('/v1/client/EProsClient/mallstate')
    ]).then(([stateRes, areaRes]) => {
      this.tradeStates = stateRes.data;
      this.mallList = [{ value: 0, label: '全部订单' }, ...(areaRes.data || [])];
      // 先标记跳过，等 watch 触发完再刷新
      if (this.$refs.baseList) {
        this.$refs.baseList._skipWatch = true
      }
      const areaFromRoute = this.$route.query.TradeArea;
      if (areaFromRoute !== undefined && areaFromRoute !== '') {
        this.TradeArea = Number(areaFromRoute) || 0;
      } else {
        this.TradeArea = 0;
      }
      const stateFromRoute = this.$route.query.state;
      if (stateFromRoute !== undefined && stateFromRoute !== '') {
        this.activeTab = String(stateFromRoute);
        this._searchParams.state = stateFromRoute;
      }
      this.$nextTick(() => {
        if (this.$refs.baseList) {
          this.$refs.baseList._skipWatch = false
          this.$refs.baseList.refresh()
        }
      })
    }).catch((err) => {
      this.$showFailToast(err.message || '加载失败');
    });
  },
  computed: {
    parseData() {
      return res => res.data.items;
    },
    parseData2() {
      return res => res.data.items;
    },
    searchParams() {
      const params = {
        ordernum: this._searchParams.ordernum,
        state: this._searchParams.state,
      };
      if (this.TradeArea !== 0) {
        params.mallstate = this.TradeArea;
      }
      return params;
    }
  },
  watch: {
    // TradeArea(val) {
    //   this._searchParams.state = '';
    //   this.activeTab = '';
    // },
    '$route.query.state': {
      handler(newVal) {
        if (newVal !== undefined && newVal !== '') {
          this.activeTab = String(newVal);
          // this.getTradeStates();
        } else {
          this.activeTab = '';
        }
      }
    },
    '$route.query.TradeArea': {
      handler(newVal) {
        if (newVal !== undefined && newVal !== '') {
          this.TradeArea = Number(newVal) || 0;
        } else {
          this.TradeArea = 0;
        }
      }
    },
  },
  methods: {
    back() {
      this.$router.push('/My')
    },
    onTabChange(name) {
      this._searchParams.state = name;
      this.$refs.baseList?.refresh();
    },
    changeMall(name) {
      if (this.TradeArea !== name) {
        this.TradeArea = Number(name) || 0;
      }
    },
    onSearch() {
      this.$refs.baseList?.refresh();
    },
    onClear() {
      this._searchParams.ordernum = '';
      this.$refs.baseList?.refresh();
    },
    getTradeAreas() {
      this.$get('/v1/client/EProsClient/mallstate').then(res => {
        this.mallList = [{ value: 0, label: '全部订单' }, ...(res.data || [])];
      }).catch((err) => {
        this.$showFailToast(err.message || '获取订单类型失败');
      });
    },
    getTradeStates() {
      this.$get('/v1/client/FOrdersClient/orderstate').then(res => {
        this.tradeStates = res.data;
      }).catch((err) => {
        this.$showFailToast(err.message || '获取订单状态失败');
      });
    },
    onRefresh() {
    },
    confirmReceipt(item) {
      this.$showConfirmDialog({
        title: "是否确认收货",
      }).then(() => {
        this.$put(`/v1/client/FOrdersClient/${item.ordernum}/receipt`).then(() => {
          this.$showSuccessToast('确认收货成功');
          this.$refs.baseList?.refresh();
        }).catch(err => {
          this.$showFailToast(err.message || '操作失败');
        });
      }).catch(() => { });
    },
    cancelTrade(item) {
      this.$showConfirmDialog({
        title: "是否确认取消订单",
      }).then(() => {
        this.$put(`/v1/client/FOrdersClient/${item.ordernum}/cancel`).then(() => {
          this.$showSuccessToast('取消订单成功');
          this.$refs.baseList?.refresh();
        }).catch(err => {
          this.$showFailToast(err.message || '取消失败');
        });
      }).catch(() => { });
    },
  }
}
</script>
