<template>
  <Theme>
    <view class="wrap">
      <Navbar fixed border :navShow="navShow">
        <template #center>
          <view class="nav_search">
            <Search
              v-model="searchValue"
              @confirm="searchConfirm"
              :placeholder="t('名称订单号商品名称')"
            >
              <template #prefix>
                <i class="icon-font icon-search"></i>
              </template>
            </Search>
          </view>
        </template>
        <template #right>
          <navFilter @submit="filterSubmit" v-if="tabActive == 0" />
          <navMenu
            :options="{ icon: 'icon-home', text: '主页' }"
            page="order"
          />
        </template>
      </Navbar>
      <view class="content1">
        <view class="cont_tab">
          <up-tabs
            :key="tabActive"
            :current="tabActive"
            :list="tabList"
            keyName="text"
            @click="tabConfirm"
            lineColor="var(--black)"
            :activeStyle="{
              color: 'var(--black)',
              fontWeight: 'bold',
              transform: 'scale(1.05)',
            }"
            :inactiveStyle="{
              color: '#606266',
              transform: 'scale(1)',
            }"
          >
          </up-tabs>
        </view>
        <view
          class="cont"
          :style="{ '--height': footerHeight + tabbarHeight + 'px' }"
        >
          <List
            url="/shop/order/list"
            :topHeight="tabHeight"
            :defaultParams="{ keywords: searchValue, ...params }"
            ref="listRef"
            @datas="getAllData"
          >
            <template #item="{ item }">
              <view class="order_list">
                <view class="order_header">
                  <template v-if="tabActive == 1 && navShow">
                    <up-checkbox-group
                      :modelValue="ids"
                      activeColor="var(--black)"
                      labelSize="14"
                      labelColor="#676969"
                      iconSize="16"
                      @change="checkedChanges(item.id)"
                    >
                      <up-checkbox :name="item.id" />
                    </up-checkbox-group>
                  </template>
                  <view class="header_img">
                    <image
                      :src="`../../static/shop/icon_${item.channel}.png`"
                      class="img"
                    ></image>
                  </view>
                  <view class="create_time">
                    <trans _t="创建时间" />:
                    {{ useGlobal().$format(item.indate) }}
                  </view>
                </view>
                <view class="order_item">
                  <view
                    class="order_item_wrapper"
                    v-for="(val, num) in item.goods"
                    :key="num"
                    @click="listClick(item)"
                  >
                    <view class="_item_wrapper">
                      <view class="thumb_img">
                        <image :src="val.pic_url" class="_img"></image>
                      </view>
                      <view class="goods_info">
                        <view class="info_name">
                          <view class="_name">{{ val.goodTitle }}</view>
                          <view class="_price"
                            >{{ symbol.symbol }}&nbsp;{{
                              Moneyhtml(val.price)
                            }}</view
                          >
                        </view>
                        <view class="spec_info">
                          <view class="spec_desc">{{ val.sku_desc }}</view>
                          <view class="spec_num">x{{ val.total }}</view>
                        </view>
                      </view>
                    </view>
                    <view class="order_status">
                      <text>{{ item.status_txt }}&nbsp;</text>
                      <!-- <i class="icon-font icon-question2"></i> -->
                    </view>
                  </view>
                  <view class="order_footer">
                    <view class="order_price">
                      <view class="price_text"> <trans _t="总价" />： </view>
                      <text
                        >{{ symbol.symbol }}{{ Moneyhtml(item.amount) }}</text
                      >
                      <!-- <i class="icon-font icon-question2"></i> -->
                    </view>
                    <view class="end_time" v-if="item.payStatus == 100">
                      <trans _t="结束时间" />:
                      {{ useGlobal().$format(item.enddate) }}
                    </view>
                    <view class="order_btns" v-if="item.status == 900">
                      <view class="btn">
                        <trans _t="删除订单" />
                      </view>
                    </view>
                    <view class="order_btns" v-if="item.status == 100">
                      <view class="btn" @click="orderCancel(item)">
                        <trans _t="取消" />
                      </view>
                      <view class="btn pay_btn" @click="paySubmit(item)">
                        <trans _t="支付" />
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </template>
          </List>
        </view>
        <view
          class="cont_footer"
          id="footer"
          v-if="tabActive == 1 && navShow"
          :style="{ '--tabbarHeight': tabbarHeight + 'px' }"
        >
          <up-checkbox
            :label="t('全选')"
            :disabled="!allId.length"
            activeColor="var(--black)"
            labelSize="14"
            labelColor="#676969"
            iconSize="16"
            name="agree"
            usedAlone
            v-model:checked="selectAllChecked"
            @change="selectAllChange"
          >
          </up-checkbox>
          <view
            class="total_btn"
            @click.stop="submit"
            :style="{ opacity: ids.length ? 1 : 0.5 }"
          >
            <trans _t="合并付款" />
          </view>
        </view>
      </view>
    </view>

    <cancelModel ref="cancelModelRef" />
  </Theme>
</template>
<script setup>
import Navbar from "@/components/navbar";
import navMenu from "@/components/nav_menu";
import navFilter from "@/components/nav_filter";
import Search from "@/components/input";
import Tab from "@/components/tabs";
import List from "@/components/list";
import cancelModel from "./components/cancelModel.vue";
import { ref, onMounted, nextTick, computed, watch, watchEffect } from "vue";
import { t } from "@/locale";
import { useGlobal, Toast, Moneyhtml, query } from "@/utils";
import { useSystemStore, useShopStore } from "@/store";
import { SHOP_ORDER_GETPAY } from "@/api";
import { onShow, onReachBottom } from "@dcloudio/uni-app";

const props = defineProps({
  tabHeight: {
    type: Number,
    default: 0,
  },
  tabbarHeight: {
    type: Number,
    default: 0,
  },
  tabParams: {
    type: Object,
  },
  navShow: Boolean,
});

const useSystem = useSystemStore();
const useShop = useShopStore();
const searchValue = ref("");
const tabActive = ref(0);
const footerHeight = ref(0);
const listRef = ref(null);

const tabList = ref([]);

watchEffect(() => {
  tabList.value = [
    { text: t("全部"), status: 0 },
    { text: t("待付款"), status: 100 },
    { text: t("运输中"), status: 200 },
    { text: t("待入库"), status: 500 },
    { text: t("待质检"), status: 520 },
    { text: t("退款和售后"), status: 40 },
  ];
});
const params = ref({
  status: 0,
});
const symbol = computed(() => useSystem.getSymbol);
const selectAllChecked = ref(false);
const allId = ref([]);
const ids = ref([]);

watch(
  () => props.tabParams,
  (newVal) => {
    if (newVal && newVal.tab == 0) {
      tabActive.value = newVal.type;
      params.value.status = newVal.status;
      useShop.setTabParams(null);

      nextTick(() => {
        listRef.value?.handleRefresh();
        getHeight();
      });
    }
  },
  { immediate: true }
);

const searchConfirm = () => {
  nextTick(() => {
    listRef.value && listRef.value.handleRefresh();
  });
};
const getAllData = (list) => {
  if (tabActive.value == 0) return;
  if (!list.length) return (selectAllChecked.value = false);
  allId.value = list.reduce((acc, item) => {
    acc.push(item.id);
    return acc;
  }, []);
};

const checkedChanges = (id) => {
  let arr = JSON.parse(JSON.stringify(ids.value));
  let findIndex = ids.value.findIndex((item) => item == id);
  if (findIndex != -1) {
    arr = arr.filter((item) => item != id);
  } else {
    arr.push(id);
  }
  ids.value = arr;
  let flag = allId.value.every((value) => arr.includes(value));
  selectAllChecked.value = flag;
};
const selectAllChange = (e) => {
  selectAllChecked.value = e;
  ids.value = e ? allId.value : [];
};

const paySubmit = (item) => {
  ids.value = [item.id];
  nextTick(() => {
    shopConfirm();
  });
};

const cancelModelRef = ref(null);
const orderCancel = (item) => {
  cancelModelRef.value && cancelModelRef.value.open(item.id);
};

const listClick = (item) => {
  uni.navigateTo({ url: `/pages/order/details?oid=${item.id}` });
  // uni.navigateTo({ url: `/pages/dashboard/order_detail?orderid=${item.id}` })
};

const submit = () => {
  if (!ids.value.length) return;
  shopConfirm();
};

const tabConfirm = (item, index) => {
  if (!item) return;
  tabActive.value = index;
  params.value.status = item.status;
  nextTick(() => {
    listRef.value && listRef.value.handleRefresh();
  });
};

const filterSubmit = (obj) => {
  params.value = obj;
  nextTick(() => {
    listRef.value && listRef.value.handleRefresh();
  });
};

const shopConfirm = async () => {
  try {
    const res = await SHOP_ORDER_GETPAY(ids.value.join(","));
    uni.navigateTo({
      url: `/pages/shop/payment?oid=${res.data.oid}&type=order`,
    });
    ids.value = [];
    selectAllChecked.value = false;
  } catch (error) {
    Toast(error.msg);
  }
};

const getHeight = async () => {
  try {
    const res = await query("#footer");
    nextTick(() => {
      footerHeight.value = res.height;
    });
  } catch (error) {}
};

onMounted(() => {
  // listRef.value && listRef.value.getData();
});
onShow(() => {
  nextTick(() => {
    listRef.value && listRef.value.getData();
  });
});
onReachBottom(() => {
  nextTick(() => {
    listRef.value && listRef.value.scrolltolower();
  });
});
</script>
<style lang="less" scoped>
@import url("@/style.less");

.wrap {
  max-height: calc(100vh - 44rpx);
  background-color: var(--bg);
  .flex();
  flex-direction: column;

  /deep/ .u-navbar__content {
    justify-content: unset;

    .u-navbar__content__left {
      position: unset;
    }
  }

  .nav_search {
    .icon-search {
      color: #a8abb2;
      .size(28px);
    }
  }

  .content1 {
    flex-grow: 1;
    flex-direction: column;
    .flex();
    // height: calc(100vh - 44px - var(--height));
    .cont_tab {
      background-color: var(--light);
      padding: 0 48rpx;

      :deep(.tab) {
        .active {
          color: var(--text) !important;

          &::before {
            background-color: var(--text) !important;
          }
        }
      }
    }

    .cont {
      flex-grow: 1;
      overflow: hidden scroll;
      padding: 0 24rpx var(--height);

      .order_list {
        margin-top: 24rpx;
        padding: 16rpx 24rpx;
        background-color: var(--light);
        border-radius: 16rpx;

        .order_header {
          .ver();
          margin-bottom: 16rpx;

          .header_img {
            width: 48rpx;
            height: 48rpx;

            .img {
              width: inherit;
              height: inherit;
              border-radius: 8rpx;
            }
          }

          .create_time {
            margin-left: 16rpx;
            .size(24rpx);
            color: var(--text);
            font-weight: 700;

            text {
              font-weight: 500;
            }
          }
        }

        .order_item {
          &_wrapper {
            margin-top: 16rpx;

            ._item_wrapper {
              .flex();

              .thumb_img {
                width: 140rpx;
                height: 140rpx;

                ._img {
                  width: inherit;
                  height: inherit;
                  border-radius: 16rpx;
                }
              }

              .goods_info {
                margin-left: 16rpx;
                flex: 1;

                .info_name {
                  color: var(--text);
                  .size(24rpx);
                  font-weight: 700;
                  line-height: 44rpx;
                  .ver();

                  ._name {
                    flex: 1;
                    .ellipsis();
                    margin-right: 8rpx;
                  }
                }

                .spec_info {
                  .flex();
                  flex: 1;
                  margin-top: 8rpx;
                  color: var(--text-01);
                  .size(24rpx);
                  line-height: 40rpx;

                  .spec_desc {
                    flex: 1;
                    margin-right: 8rpx;
                  }
                }

                .no_return {
                  border: var(--danger-bor);
                  border-radius: 40rpx;
                  color: var(--danger);
                  cursor: pointer;
                  .size(24rpx);
                  line-height: 40rpx;
                  margin-top: 16rpx;
                  padding: 0 24rpx;
                  width: max-content;
                }
              }
            }

            .order_status {
              color: var(--primary);
              .size(24rpx);
              height: 40rpx;
              .flex_position(flex-end);
              margin-top: 16rpx;

              .icon-question2 {
                .size(36rpx);
              }
            }

            .order-cancel {
              margin-top: 16rpx;
              color: var(--text-01);
              .size(24rpx);
              line-height: 40rpx;

              .time {
                color: var(--danger);
                font-weight: 700;
              }

              .content {
                margin-top: 8rpx;
                color: var(--text);
                font-weight: 500;
              }
            }
          }

          .order_footer {
            margin-top: 16rpx;
            border-top: 1px solid #f5f6f7;

            .order_price {
              padding-top: 16rpx;
              .flex_position(flex-end);
              color: var(--primary);
              color: var(--red);
              .size();
              font-weight: 700;
              height: 48rpx;
              line-height: 1;

              .price_text {
                color: var(--text);
                .size(24rpx);
                font-weight: 400;
              }

              .icon-question2 {
                font-weight: 400;
                color: var(--text-01);
                margin-left: 8rpx;
              }
            }

            .end_time {
              .flex_position(flex-end);
              margin-top: 16rpx;
              color: #e62e2e;
              font-weight: 700;
              .size(24rpx);

              text {
                font-weight: 400;
              }
            }

            .order_btns {
              .flex_position(flex-end);
              margin-top: 16rpx;
              gap: 16rpx;

              .btn {
                .flex_center();
                border-radius: 16rpx;
                padding: 0 30rpx;
                .size(24rpx);
                height: 48rpx;
                border: 1px solid var(--black);
                background-color: var(--light);
                color: var(--black);
              }

              .pay_btn {
                color: var(--light);
                background-color: var(--black);
              }
            }
          }
        }
      }
    }

    .cont_footer {
      position: fixed;
      bottom: var(--tabbarHeight);
      left: 0;
      right: 0;
      line-height: 100rpx;
      background-color: var(--light);
      box-shadow: 0 -4px 6px #0000000d;
      padding: 0 24rpx;
      .flex_position(space-between);

      .total_btn {
        .size(24rpx);
        height: 38px;
        margin-left: 16rpx;
        min-width: 180rpx;
        background-color: var(--primary);
        background-color: var(--black);
        color: var(--light);
        border-radius: 16rpx;
        padding: 16rpx 30rpx;
        text-align: center;
        .flex_center();
        margin-left: 24rpx;
      }
    }
  }
}
</style>