<template>
  <view class="container">
    <view class="header-wrap">
      <view class="u-flex" style="justify-content: flex-end"> </view>
      <view class="search-wrap">
        <view class="input-wrap" @click="showStatus = true">
          <view class="icon right">
            <u-icon name="arrow-down" size="12"></u-icon>
          </view>
          <input
            v-model="querForm.statusName"
            class="ipt right"
            type="text"
            placeholder="全部"
            placeholder-style="font-size: 28rpx"
            disabled
          />
        </view>
        <view class="input-wrap" @click="showTimeArea = true">
          <view class="icon right">
            <u-icon name="arrow-down" size="12"></u-icon>
          </view>
          <input
            v-model="querForm.timeArea"
            class="ipt right"
            type="text"
            placeholder="选择日期范围"
            placeholder-style="font-size: 28rpx"
            disabled
          />
        </view>
        <view class="input-wrap" @click="show = true">
          <view class="icon right">
            <u-icon name="arrow-down" size="12"></u-icon>
          </view>
          <input
            v-model="querForm.shopName"
            class="ipt right"
            type="text"
            placeholder="全部店铺"
            placeholder-style="font-size: 28rpx"
            disabled
          />
        </view>
      </view>
    </view>
    <view>
      <!-- <view
        class="u-p-t-16 u-p-b-20 u-flex u-p-l-28 u-p-r-28"
        style="align-items: baseline; justify-content: flex-end"
      >
        <text class="color-666 font-12"> 总计：</text>
        <text class="font-16 color-333 font-700" >
          {{ totalIncome }}</text
        >
      </view> -->

      <view class="list u-m-t-32">
        <view v-for="(item, index) in state.records" :key="index" class="item">
          <view class="u-flex justify-between">
            <view>
              <text class="color-666">来源：</text>
              <text class="color-333 font-700">{{ item.shopName }}</text>
            </view>
            <view>
              <text class="color-666" v-if="item.status == 'pending'"
                >待入账</text
              >
              <text class="color-666" v-if="item.status == 'success'"
                >已入账</text
              >
              <text class="color-666" v-if="item.status == 'refund'"
                >已退款</text
              >
            </view>
          </view>
          <view class="u-flex justify-between u-m-t-16">
            <view>
              <text class="color-666">订单：</text>
              <text class="color-333 font-700">{{ item.orderNo }}</text>
            </view>
            <view class="money">
              <text class="money reduce" v-if="item.status == 'refund'"
                >-{{ item.rewardAmount }}</text
              >

              <text class="money" v-else>+{{ item.rewardAmount }}</text>
              <text class="tag" v-if="item.status == 'refund'">订单退款</text>
              <text class="tag" v-else-if="item.level == 1"
                >(订单一级分成)</text
              >
              <text class="tag" v-else-if="item.level == 2"
                >(订单二级分成)</text
              >
            </view>
          </view>
          <view class="u-flex justify-between u-m-t-16">
            <view>
              <text class="color-666">时间：</text>
              <text class="color-333 font-700">{{ item.createTime }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <u-loadmore :status="isEnd ? 'nomore' : 'loading'"></u-loadmore>
    <u-popup :show="show" round="20" closeable @close="show = false">
      <view class="shoplist-popup">
        <view class="title">
          <text class="t">店铺列表</text>
        </view>
        <scroll-view
          class="popup-list"
          direction="vertical"
		  :scroll-y="true"
          @scrollend="scrollBottom"
        >
          <view
            class="item"
            v-for="item in shopList"
            :key="item.shopId"
            @click="selectShopHandle(item)"
          >
            <text class="t">{{ item.shopName }}</text>
            <text class="intro">地址：{{ item.shopAddress }}</text>
          </view>
          <u-loadmore status="nomore"></u-loadmore>
        </scroll-view>
      </view>
    </u-popup>

    <up-action-sheet
      cancelText="取消"
      :actions="statusList"
      title="选择状态"
      :show="showStatus"
      closeOnClickAction
      @close="showStatus = false"
      @select="selectStatusHandle"
      round="16"
    ></up-action-sheet>

    <dateAreaSel
      :show="showTimeArea"
      :minYear="2022"
      @close="showTimeArea = false"
      @confirm="confirmTimeArea"
    ></dateAreaSel>
  </view>
</template>

<script setup>
import dayjs from "dayjs";
import dateAreaSel from "@/components/date-range-picker/date-range-picker.vue";
import { ref, reactive, onMounted, computed, watch } from "vue";
import * as distributionApi from "@/common/api/market/distribution.js";

import {
  onLoad,
  onReady,
  onShow,
  onPageScroll,
  onReachBottom,
} from "@dcloudio/uni-app";
import {
  APIcouponfindByUserId,
  APIfindCoupon,
  getCouponShops,
} from "@/common/api/member.js";

const show = ref(false);
const showTimeArea = ref(false);

const querForm = ref({
  shopId: "",
  shopName: "",
  statusActiveIndex: 0,
  status: "",
  statusName: "",
  startTime: "",
  timeArea: "",
  endTime: "",
  page: 1,
});

function confirmTimeArea(e) {
  querForm.value.date = e;
  querForm.value.startTime = e[0];
  querForm.value.endTime = e[1];
  querForm.value.timeArea = e[0] + "-" + e[1];
}

// 状态
const statusList = ref([
  {
    value: "pending",
    name: "待入账",
    color: "#333",
    fontSize: "16",
  },
  {
    value: "success",
    name: "已入账",
    color: "#333",
    fontSize: "16",
  },
  {
    value: "refund",
    name: "已退款",
    color: "#333",
    fontSize: "16",
  },
]);
const returnStatusName = () => {
  let name = "";
  statusList.value.forEach((item) => {
    if (item.value == querForm.value.status) {
      name = item.name;
    }
  });
  return name;
};
function selectStatusHandle(e) {
  console.log(e);
  querForm.value.status = e.value;
  querForm.value.statusName = returnStatusName();
}

onReachBottom(() => {
  console.log("到底了");
  if (!isEnd.value) {
    console.log("没有跟多了");
    querForm.value.page++;
    getIncomeDetailsAjax();
  }
});

const showStatus = ref(false);

// 店铺列表滚动到底部了
function scrollBottom() {
  console.log("店铺列表滚动到底部了");
}

// 选择店铺
function selectShopHandle(item) {
  querForm.value.shopId = item.shopId;
  querForm.value.shopName = item.shopName;
  show.value = false;
}
// 获取当前店铺会员信息
const shopList = ref([]);
async function getCouponShopsAjax() {
  try {
    const res = await distributionApi.activates({ page: 1, size: 999 });
    shopList.value = res.records || [];
  } catch (error) {
    console.log(error);
  }
}

// 获取收益明细
const state = reactive({
  records: [],
  totalRow: 0,
});
const isEnd = ref(false);
async function getIncomeDetailsAjax() {
  try {
    const ajaxQuery = {
      shopId: querForm.value.shopId,
      startTime: querForm.value.startTime
        ? `${querForm.value.startTime} 00:00:00`
        : "",
      endTime: querForm.value.endTime
        ? `${querForm.value.endTime} 23:59:59`
        : "",
      status: querForm.value.status,
      page: querForm.value.page,
    };
    console.log("ajaxQuery,", ajaxQuery);
    const res = await distributionApi.getIncomeDetails(ajaxQuery);
    if (res) {
      if (querForm.value.page == 1) {
        Object.assign(state, res);
      } else {
        state.totalPage = res.totalPage * 1;
        state.records.push(...(res.records || []));
      }
      isEnd.value = querForm.value.page >= res.totalPage * 1;
    }
  } catch (error) {
    console.log(error);
  }
}

const centerUserInfo = ref({});
async function centerUser() {
  const res = await distributionApi.centerUser();
  centerUserInfo.value = res;
}
onShow(() => {});


onLoad(async (opt) => {
  await getCouponShopsAjax();

  console.log(opt);
  if (opt.name) {
    const findItem = statusList.value.find((item) => item.name == opt.name);
    if (findItem) {
      querForm.value.status = findItem.value;
      querForm.value.statusName = findItem.name;
    }
  }
  if (opt.shopId) {
    querForm.value.shopId = opt.shopId;
    const findItem = shopList.value.find((item) => item.shopId == opt.shopId);
    querForm.value.shopName = findItem.shopName || "";
  }
  centerUser();
  getIncomeDetailsAjax();
});

const totalIncome=computed(()=>{
	if(!querForm.value.shopId){
		return centerUserInfo.value?(centerUserInfo.value.totalIncome||0):0;
	}
	const findItem = shopList.value.find((item) => item.shopId ==  querForm.value.shopId );
	if(findItem){
		return findItem.income||0
	}
	return 0
})

watch(
  () => querForm.value.status,
  (newVal, oldVal) => {
    querForm.value.page = 1;
    isEnd.value = false;
    getIncomeDetailsAjax();
  }
);
watch(
  () => querForm.value.shopId,
  (newVal, oldVal) => {
    querForm.value.page = 1;
    isEnd.value = false;
    getIncomeDetailsAjax();
  }
);
watch(
  () => querForm.value.startTime,
  (newVal, oldVal) => {
    querForm.value.page = 1;
    isEnd.value = false;
    getIncomeDetailsAjax();
  }
);
watch(
  () => querForm.value.endTime,
  (newVal, oldVal) => {
    querForm.value.page = 1;
    isEnd.value = false;
    getIncomeDetailsAjax();
  }
);
</script>

<style>
page {
  background-color: #f7f7f7;
}
</style>
<style scoped lang="scss">
.container {
  padding: 130rpx 0 28upx;
}
.list {
  font-size: 28rpx;
  .item {
    background-color: #fff;
    padding: 32rpx 28rpx 32rpx 36rpx;
    margin-bottom: 16rpx;
    .money {
      line-height: 44rpx;
      color: #fe7e00;
      font-size: 48rpx;
      font-weight: 700;
      position: relative;
      &.reduce {
        color: #ff1c1c;
      }
      .tag {
        position: absolute;
        font-weight: 400;
        right: 0;
        top: 100%;
        font-size: 28rpx;
        white-space: nowrap;
        color: #999;
        transform: translateY(10rpx);
      }
    }
  }
}
.header-wrap {
  width: 100%;
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 99;
  padding: 28upx;
  .search-wrap {
    display: flex;
    gap: 20upx;
    .input-wrap {
      height: 70upx;
      border: 1px solid #ececec;
      border-radius: 8upx;
      position: relative;
      box-sizing: border-box;
      &:nth-child(1) {
        width: 170rpx;
      }
      &:nth-child(2) {
        flex: 1;
      }
      &:nth-child(3) {
        width: 226rpx;
      }
      .icon {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        &.left {
          left: 14upx;
        }
        &.right {
          right: 14upx;
        }
      }
      .ipt {
        width: 100%;
        height: 100%;
        font-size: 28rpx;
        &.left {
          padding-left: 68upx;
        }
        &.right {
          padding: 0 56upx 0 24upx;
        }
      }
    }
  }
  .status-wrap {
    display: flex;
    padding-top: 28upx;
    position: relative;
    .icon-wrap {
      height: 12upx;
      position: absolute;
      bottom: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease-in-out;
      .active-icon {
        width: 24upx;
        height: 12upx;
        z-index: 9;
      }
    }
    .item {
      flex: 1;
      height: 80upx;
      display: flex;
      align-items: center;
      justify-content: center;
      .t {
        font-size: 32upx;
        color: #666666;
        transition: all 0.3s ease-in-out 0.1s;
      }
      &.active {
        .t {
          color: #e3ad7f;
        }
      }
    }
  }
}
.list-wrap {
  padding-top: 28upx;
  .item {
    border-radius: 18upx;
    background-color: #fff;
    padding: 28upx;
    &:not(:first-child) {
      margin-top: 28upx;
    }
    .top {
      display: flex;
      align-items: center;
      padding-bottom: 28upx;
      .icon {
        $size: 140upx;
        width: $size;
        height: $size;
        margin-right: 28upx;
      }
      .info {
        flex: 1;
        display: flex;
        justify-content: center;
        flex-direction: column;
        gap: 8upx;
        padding-left: 28upx;
        position: relative;
        &::after {
          $height: 100upx;
          content: "";
          height: $height;
          border-left: 1upx solid #f7f7f7;
          position: absolute;
          top: 50%;
          margin-top: $height * 0.5 * -1;
          left: 0;
        }
        .view {
          flex: 1;
          &.name {
            font-size: 32upx;
            color: #333;
          }
          &.time {
            .t {
              font-size: 24upx;
              color: #999;
            }
          }
        }
      }
      .btn {
        width: 120upx;
        height: 48upx;
        border-radius: 48upx;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #333;
        .t {
          font-size: 24upx;
          color: #fff;
        }
        &.disabled {
          background-color: #f8f8f8;
          .t {
            color: #999999;
          }
        }
      }
    }
    .btm {
      display: flex;
      align-items: center;
      padding: 28upx 0 14upx;
      border-top: 1upx solid #f7f7f7;
      .left {
        flex: 1;
        height: 40upx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 24upx;
        color: #999;
      }
      .right {
        flex: 1;
        display: flex;
        align-items: center;
        padding-left: 28upx;
        justify-content: flex-end;
        .t {
          font-size: 24upx;
          color: #333;
        }
      }
    }
  }
}
.shoplist-popup {
  padding: 0 28upx 28upx;
  .title {
    padding: 28upx 0;
    display: flex;
    align-items: center;
    justify-content: center;
    .t {
      font-size: 32upx;
      font-weight: bold;
      color: #333;
    }
  }
  .popup-list {
    max-height: 50vh;
    .item {
      padding: 28upx;
      border-radius: 12upx;
      background-color: #f7f7f7;
      margin-bottom: 28upx;
      display: flex;
      flex-direction: column;
      padding: 28upx;
      .t {
        font-size: 28upx;
        font-weight: bold;
        color: #333;
        /* 必须设置宽度 */
        width: 600upx; /* 或具体像素值 */

        /* 关键属性 */
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1; /* 显示2行 */
        overflow: hidden;

        /* 文本溢出省略号 */
        text-overflow: ellipsis;

        /* 可选：防止行高度，确保计算准确 */
        line-height: 1.5;
        word-break: break-all; /* 允许在单词内换行 */
        word-wrap: break-word; /* 允许长单词或URL换行 */
      }
      .intro {
        font-size: 28upx;
        color: #999;
        /* 必须设置宽度 */
        width: 600upx; /* 或具体像素值 */

        /* 关键属性 */
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2; /* 显示2行 */
        overflow: hidden;

        /* 文本溢出省略号 */
        text-overflow: ellipsis;

        /* 可选：防止行高度，确保计算准确 */
        line-height: 1.5;
        word-break: break-all; /* 允许在单词内换行 */
        word-wrap: break-word; /* 允许长单词或URL换行 */
      }
    }
    .ul {
      .li {
        color: #999;
        font-size: 28upx;
        padding: 8upx 0;
        .t {
          color: #999;
          font-size: 28upx;
        }
      }
    }
  }
}
</style>
