<template>
  <view class="app-main app-content">
    <view style="position:fixed;top:100upx;background-color:white;z-index:999999;height:auto;font-size:33upx;color:#333333;width:100%;">
      <view style="width:80%;border:1upx solid #CCCCCC;margin:0 auto;padding:10upx 0 0 20upx;overflow: scroll;" v-if="showSearch">
        <block v-if="!$util.isEmpty(searchList)">
          <block v-for="(item, index) in searchList" :key="index">
            <view style="margin-bottom:30upx;" @click="getCustom(item)">
              <view style="font-size:37upx;margin-bottom:10upx;">{{item.name}}</view>
              <view style="font-size:29upx;color:#999999;">
                {{item.visitTime?item.visitTime.substr(5,11):''}}
                  <text v-if="item.overTimeUnExpend && item.overTimeUnExpend == 10000" style="margin-left:20upx;color:green;">没有下过单</text>
                  <text v-if="item.overTimeUnExpend && item.overTimeUnExpend == 7" style="margin-left:20upx;color:green;">超1周未下单</text>
                  <text v-if="item.overTimeUnExpend && item.overTimeUnExpend == 30" style="margin-left:20upx;color:green;">超1个月未下单</text>
                  <text v-if="item.overTimeUnExpend && item.overTimeUnExpend == 180" style="margin-left:20upx;color:green;">超半年未下单</text>
                  <text v-if="item.overTimeUnExpend && item.overTimeUnExpend == 365" style="margin-left:20upx;color:green;">超1年未下单</text>
              </view>
            </view>
          </block>
        </block>
      </view>
    </view>
    <view class="input-wrap_box">
      <view class="select-dn_bx">
        <DateSelect class="bar" top="0" @selectDateFn="selectDateFn" defaultShowName='时间' />
      </view>
      <button class="admin-button-com middle" @click="changeSearchStyle()">{{searchStyle==0?'客户':'编号'}}</button>
      <view class="search-container">
        <AppSearchModule ref="searchRef" placeholder="填写" v-model="searchText" @input="searchFn"/>
        <view v-if="customId != 0" class="search-clear-overlay" @click.stop="clearFn">清空</view>
      </view>
      <button class="admin-button-com middle blue filter-btn" @click.stop="openFilterPanel">
        筛选
        <text v-if="hasActiveFilters" class="filter-dot"></text>
      </button>
    </view>
    <app-tabs :tabs="tabs" class="app-tabs" :isFixed="false" :top="50" :currentTab="tabIndex" :height="100" @change="change" itemWidth="20%" />
    <view class="list-wrap">
      <block v-if="!$util.isEmpty(list.data)">
        <view class="list" v-for="(item, index) in list.data" :key="index" @click="$util.pageTo({ url: '/admin/order/detail', query: { id: item.id } })" >
          <view class="list-top flex-center-between" style="border-bottom:1upx solid #EEEEEE;">
            <view class="app-color-3" style="font-size:28upx;font-weight:bold;color:#333333;">{{ item.customName||'' }}<text v-if="item.bookName!=''" style="margin-left:30upx;color:#866b6b;font-weight: normal;">{{item.bookName}}</text></view>
            <view style="border:1upx solid red;border-radius:18upx;font-size:19upx;padding:5upx 10upx;background-color: red;color:white;" v-if="item.debt == 1">赊账</view>
            <view style="border:1upx solid #0e7ed8;border-radius:18upx;font-size:19upx;color:white;padding:5upx 10upx;background-color: #0e7ed8;" v-if="item.refund == 1">有售后</view>
            <view style="font-size:28upx;" class='app-price app-green' v-if="item.status==2&&item.sendType==1">待取货</view>
            <view style="font-size:28upx;" class='app-price app-green' v-else>{{ item.status | constantfilter('ORDER_STATUS') }}</view>
          </view>
          <view class="list-blo">
              <orderItem :info="item"></orderItem>
          </view>
          <view class="list-bottom" style="padding-top:0upx;">
            <view style="border-bottom:1upx solid #EEEEEE;padding-bottom:8upx;">
              <text v-if="item.sendCost > 0" class="freight-text">运费 ￥{{ item.sendCost ? parseFloat(item.sendCost) : 0 }}</text>
              <text class="app-size-30 app-bold" v-if="item.forward==0">
                <text v-if="item.orderPrice == item.actPrice">￥{{ item.orderPrice ? parseFloat(item.orderPrice):0 }}</text>
                <text v-else>
                  <text style="text-decoration: line-through;color:#847676;">￥{{ item.orderPrice ? parseFloat(item.orderPrice):0 }}</text>
                  <text style="margin-left:10upx;">￥{{ item.actPrice ? parseFloat(item.actPrice):0 }}</text>
                </text>
              </text>
              <text class="app-size-30 app-bold" v-else>售后付款 -¥{{ item.orderPrice ? parseFloat(item.orderPrice) :0 }}</text>
            </view>

        <view v-if="item.sameTimeIdsNum && item.sameTimeIdsNum>1" style="text-align: center;color:white;
        margin-top:20upx;font-size:34upx;background-color:#09C567;padding-top:12upx;padding-bottom:12upx;display: flex;justify-content: center;"
        @click.stop="$util.pageTo({url:'/admin/order/itemOrder?ids='+item.sameTimeIds})">
          本客户共有{{item.sameTimeIdsNum?item.sameTimeIdsNum:0}}个订单，可合并发货
        </view>
            <view class="list-button">

              <view class="admin-button-com middle" v-if="item.payStatus == 1 && (item.hasWork == 0 || item.hasWork == 2)" @click.stop="sendWork(item)">通知制作</view>
              <view class="admin-button-com default" v-else>通知制作</view>

              <block v-if="item.status == 2">
                <view class="admin-button-com middle" v-if="item.sendType == 1" @click.stop="getOrderFn(item)">已取货</view>
                <view class="admin-button-com middle" v-else @click.stop="sendOrderFn(item)">自配送</view>
              </block>
              <block v-if="item.status == 3">
                <view class="admin-button-com middle" @click.stop="confirmReach(item)">确认送达</view>
              </block>

              <view class="admin-button-com middle" v-if="item.payStatus == 1" @click.stop="printOrder(item)">打印</view>
              <view class="admin-button-com default" v-else @click.stop="">打印</view>

              <block v-if="item.payStatus == 0">
                <view class="admin-button-com middle default" @click.stop="">呼叫跑腿</view>
              </block>
              <block v-else>
                <view class="admin-button-com middle" v-if="item.sendStatus == -4 && item.status == 2" @click.stop="openExpressPage(item.id)">呼叫跑腿</view>
                <view class="admin-button-com middle" v-else-if="[-1, -2].includes(Number(item.sendStatus)) && item.status == 2" @click.stop="openExpressPage(item.id)">重叫跑腿</view>
                <view class="admin-button-com default" v-else-if="item.sendStatus == 5">跑腿完成</view>
                <view class="admin-button-com default" v-else-if="[0, 1, 2, 3, 4, 10, 20, 30].includes(Number(item.sendStatus)) && item.payStatus == 1">已发跑腿</view>
              </block>

            </view>
          </view>
        </view>
      </block>
      <block v-else>
        <app-wrapper-empty title="暂无数据" :is-empty="$util.isEmpty(list.data)" />
      </block>
    </view>
    <NotLogin></NotLogin>

    <!--选择员工 -->
    <uni-popup ref="getStaffRef" background-color="#fff" type="center" :animation="false">
      <view style="display:flex;padding:20upx;min-height:25vh;justify-content: space-between;align-items:center;flex-wrap:wrap;">

        <text v-for="(item, index) in staffList" :key="index" @click="getCurrentStaff(item.id)" 
        style="margin-left:25upx;border:1upx solid #999999;width:100upx;height:100upx;border-radius:20upx;justify-content:center;align-items:center;display:flex;">
          {{item.name}}
        </text>

      </view>
    </uni-popup>

    <!-- 筛选下拉面板 -->
    <view v-if="showFilterPanel" class="filter-overlay" @click="closeFilterPanel">
      <view class="filter-panel" @click.stop>
        <view class="filter-header">筛选订单</view>

        <!-- 扫码筛选 -->
        <view class="filter-section">
          <view class="filter-title">扫码</view>
          <view class="filter-options">
            <view
              v-for="(item, index) in repeatOptions"
              :key="index"
              class="filter-option"
              :class="{ 'active': repeat === item.value }"
              @click="selectRepeat(item.value)"
            >
              {{ item.label }}
            </view>
          </view>
        </view>

        <!-- 员工筛选 -->
        <view class="filter-section">
          <view class="filter-title">下单人</view>
          <view class="filter-options">
            <view
              class="filter-option"
              :class="{ 'active': shopAdminId === 0 }"
              @click="selectStaff(0)"
            >全部</view>
            <view
              v-for="(item, index) in staffList"
              :key="index"
              class="filter-option"
              :class="{ 'active': shopAdminId === item.id }"
              @click="selectStaff(item.id)"
            >
              {{ item.name }}
            </view>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="filter-actions">
          <button class="filter-action-btn clear-btn middle" @click="clearFilters">重置</button>
          <button class="filter-action-btn confirm-btn middle blue" @click="confirmFilters">确定</button>
        </view>
      </view>
    </view>

  </view>
</template>
<script>
import AppTabs from "@/components/plugin/tabs";
import orderItem from "./components/order-item";
import AppWrapperEmpty from "@/components/app-wrapper-empty";
import { list } from "@/mixins";
import { onlinePrintOrder } from '@/api/order'
import { getListB, sendOrder,fetchOrder,sendReach } from "@/api/order";
import NotLogin from "@/components/not-login";
import {getStaffList} from '@/api/staff'
import AppSearchModule from "@/components/module/app-search"
import { cancelExpressOrder } from '@/api/shop-express'
import DateSelect from "@/components/module/dateSelect";
import { getList } from "@/api/member";
import { needWork } from "@/api/work"
export default {
  name: "order",
  components: {
    orderItem,
    AppTabs,
    AppWrapperEmpty,
    NotLogin,
    AppSearchModule,
    DateSelect
  },
  mixins: [list],
  data () {
    return {
      tabIndex: 0,
      tabs: [ { name: "全部", value: 0 }, { name: "待付款", value: 0 }, { name: "待发货", value: 0 }, { name: "配送中", value: 0 }, { name: "已完成", value: 0 } ],
      staffList:[],
      shopAdminId:0,
      refreshPage:1,
      showSearch:false,
      searchList:[],
      customId:0,
      searchTime:'',
      startTime:'',
      endTime:'',
      repeat:-1,
      searchStyle:0,//0客户 1编号
      searchText:'',
      lastSearchText:'',
      searchKey: 0,
      // 面板相关
      showFilterPanel: false,
      repeatOptions: [
        { label: '全部', value: -1 },
        { label: '扫码单', value: 1 }
      ]
    };
  },
  computed: {
    // 是否存在激活的筛选条件
   hasActiveFilters () {
      return this.repeat !== -1 || this.shopAdminId !== 0;
    }
  },
  onLoad() {
    uni.$on('updateOrderStatus', this.updateOrderStatus);
  },
  onUnload() {
    uni.$off('updateOrderStatus', this.updateOrderStatus);
  },
  onPullDownRefresh () {
    this.resetList();
    this.getOrderList().then(res => {
      uni.stopPullDownRefresh()
    });
  },
  onReachBottom () {
    if (!this.list.finished) {
      this.getOrderList().then(res => {
        uni.stopPullDownRefresh()
      });
    } else {
      uni.stopPullDownRefresh()
    }
  },
  onShow () {
    let tabIndex = uni.getStorageSync("switchTabQuery") || null;
    if (tabIndex) {
      uni.removeStorageSync("switchTabQuery");
      this.tabIndex = parseInt(tabIndex.tabIndex);
    }

    // 重置搜索
    if (this.customId !== 0) {
      this.clearFn()
    }

    //需要控制订单详情页，返回到列表页时不需要刷新页面
    if(this.refreshPage == 1){
      this.resetList();
      this.getOrderList()
    }else{
      this.refreshPage = 1
    }
  },
  methods: {
    init () {
      getStaffList().then(res=>{
        if(res.code ==1){
          this.staffList = res.data.list
        }
      })
    },
    // 面板相关
    openFilterPanel () {
      this.showFilterPanel = true
    },
    closeFilterPanel () {
      this.showFilterPanel = false
    },
    selectRepeat (value) {
      this.repeat = value
    },
    selectStaff (id) {
      this.shopAdminId = id
    },
    clearFilters () {
      // 恢复默认筛选
      this.repeat = -1
      this.shopAdminId = 0
      // 关闭面板并刷新
      this.closeFilterPanel()
      this.resetList()
      this.getOrderList()
    },
    confirmFilters () {
      // 关闭面板并刷新
      this.closeFilterPanel()
      this.resetList()
      this.getOrderList()
    },
    getCustom(item){
      this.showSearch = false
      this.customId = item.id
      this.resetList()
      this.getOrderList()
    },
    selectDateFn(val) {
      this.searchTime = val.searchTime
      this.startTime = val.startTime
      this.endTime = val.endTime
      this.resetList();
      this.getOrderList();
    },
    searchFn(e) {
      let that = this
      if(this.searchStyle == 0){
        // 首次点击搜索框：searchText 为空，lastSearchText 也为空 → 跳过搜索
        if (this.$util.isEmpty(this.searchText) && this.$util.isEmpty(this.lastSearchText)) {
          return;
        } else {
          // console.log('000002')
        }

        if(that.$util.isEmpty(e)){
          that.showSearch = false
          that.searchList = []
        }else{
          this.lastSearchText = this.searchText;
          getList({ page:1, name:e, type:0}).then((res) => {
              if (!that.$util.isEmpty(res.data) && !that.$util.isEmpty(res.data.list)){
                that.showSearch = true
                that.searchList = res.data.list
              }else{
                that.showSearch = false
                that.searchList = []
              }
          })
        }
      }else{
        // 首次点击搜索框：searchText 为空，lastSearchText 也为空 → 跳过搜索
        if (this.$util.isEmpty(this.searchText) && this.$util.isEmpty(this.lastSearchText)) {
          return;
        }

        if (this.searchText === this.lastSearchText) {
          return;
        }

        this.lastSearchText = this.searchText;
        this.resetList()
        this.getOrderList()
      }
    },
    sendWork(item){
      let that = this
      that.$util.confirmModal({content:'确认通知制作？'},() => {
        needWork({id:item.id}).then(res=>{
          if(res.code == 1){
            item.hasWork = 1
            that.$msg(res.msg)
          }
        })
      })
    },
    getOrderFn(item){
      let that = this
      that.$util.confirmModal({content:'确认取货？'},() => {
        fetchOrder({id:item.id}).then(res=>{
          if(res.code == 1){
            that.$msg('操作成功')
            that.resetList()
            that.getOrderList()
          }
        })          
      })
    },
    confirmReach(item){
      let that = this
      that.$util.confirmModal({content:'确认送达？'},() => {
        sendReach({id:item.id}).then(res=>{
          if(res.code == 1){
            that.$msg('操作成功')
            that.resetList()
            that.getOrderList()
          }
        })          
      })
    },
    sendOrderFn(item){
      let that = this
      that.$util.confirmModal({content:'确认自配送？'},() => {
        sendOrder({id:item.id}).then(res=>{
          if(res.code == 1){
            that.$msg('操作成功')
            that.resetList()
            that.getOrderList()
          }
        })          
      })
    },
    changeSearchStyle(){
      this.searchStyle = this.searchStyle ==0 ? 1 : 0
      this.showSearch = false
      this.customId = 0
      this.searchText=''
      this.resetList()
      this.getOrderList()
    },
    getScanOrder(){
      this.repeat = this.repeat == -1 ? 1 : -1
      this.resetList()
      this.getOrderList()
    },
    getCurrentStaff(id){
      this.resetList();
      this.shopAdminId = id
      this.$refs.getStaffRef.close()
      this.getOrderList()
    },
    selectStaffFn(){
      this.$refs.getStaffRef.open('top')
    },
    clearFn(){
      this.resetList();
      this.shopAdminId = 0
      this.searchText = ''
      this.lastSearchText = ''
      this.showSearch = false
      this.customId = 0
      this.searchTime = ''
      this.startTime = ''
      this.endTime = ''
      if (this.$refs && this.$refs.searchRef) {
        this.$refs.searchRef.search = ''
      }
      this.getOrderList()
    },
    printOrder(item){
      onlinePrintOrder({id:item.id}).then(res=>{
        if(res.code == 1){
          this.$msg('操作成功')
        }
      })
    },
    getOrderList () {
      let status = JSON.parse(JSON.stringify(this.tabIndex));
      return getListB({
        searchTime: this.searchTime,
        startTime: this.startTime,
        endTime: this.endTime,
        status: status,
        shopAdminId:this.shopAdminId,
        searchText:this.searchText,
        page: this.list.page,
        customId:this.customId,
        repeat:this.repeat,
        searchStyle:this.searchStyle
      }).then(res => {
        this.completes(res);
        if (this.$util.isEmpty(res.data)){
          return false
        } 
        this.tabs[0].value = 0;
        this.tabs[1].value = 0;
        this.tabs[2].value = 0;
        this.tabs[3].value = 0;
        this.tabs[4].value = 0;
      })
    },
    change (e) {
      if (this.tabIndex == e.index) {
        return false;
      } else {
        this.tabIndex = e.index;
        this.resetList();
        this.getOrderList();
      }
    },
    /**
     * 更新订单状态及配送状态
     * @param orderId 订单ID
     * @param orderStatus 订单状态 
     * @param sendStatus 配送状态
     */
    updateOrderStatus(orderId, orderStatus, sendStatus) {
      if (this.list && this.list.data) {
        const item = this.list.data.find(item => item.id == orderId);
        if (item) {
          item.status = orderStatus;
          item.sendStatus = Number(sendStatus);
        }
      }
    },
    /**
     * 打开配送页面
     */
    openExpressPage(orderId) {
      //this.$util.pageTo({url:'/admin/express/create?orderId='+orderId})
      this.$util.pageTo({url:'/admin/delivery/allDelivery?orderId='+orderId})
    },
    /**
     * 取消配送订单
     */
    async cancelExpress(orderId) {
      this.$util.confirmModal({content: '确认取消？(若配送员接单1分钟后取消，扣2元违约金)'}, async () => {
          const res = await cancelExpressOrder({orderId: orderId})
          if (res.code === 1) {
            this.$msg('取消成功')
            this.resetList()
            this.getOrderList()
          }
      })
    },
    /**
     * 查看配送成功详情
     */
    selectExpress(orderId) {
      this.$util.pageTo({ url: '/admin/express/success', query: { orderId: orderId } })
    }
  }
};
</script>
<style lang="scss" scoped>
.app-content {
  padding-top: 100upx;
  padding-bottom: 1px;
  .select-dn_bx {
    padding-left: 14upx;
    padding-right:10upx;
  }
  .app-tabs {
    position: fixed;
    /* 手机mobile屏幕小于1000px */
    @media screen and (max-width: 1100px) {
      width: 100%;
    }
    z-index: 9;
  }
  .input-wrap_box {
    background-color: #fff;
    position: fixed;
    top: 0;
    z-index: 10;
    @media screen and (max-width: 1100px) {
      width: 100%;
    }
    height: 100upx;
    display: flex;
    align-items: center;
    padding: 0 20upx;
    gap: 10upx;
    
    .select-dn_bx {
      flex-shrink: 0;
    }
    
    .search-container {
      flex: 1;
      min-width: 0;
        position: relative;
    }
    
    button {
      flex-shrink: 0;
      white-space: nowrap;
    }
    /* 筛选按钮样式（含红点） */
    .filter-btn {
      position: relative;
      .filter-dot {
        position: absolute;
        top: 5upx;
        right: 5upx;
        width: 15upx;
        height: 15upx;
        background-color: white;
        border-radius: 50%;
        animation: filterDotBlink 2s infinite;
      }
    }
  }
  .search-clear-overlay {
    position: absolute;
    top: 50%;
    right: 20upx;
    transform: translateY(-50%);
    z-index: 11;
    padding: 10upx 20upx;
    border-radius: 24upx;
    font-size: 24upx;
    color: #09C567;
    border: 1upx solid #09C567;
    background-color: rgba(255,255,255,0.9);
  }
  .list-wrap {
    padding-top: 115upx;
    .list {
      padding: 0 30upx;
      background-color: #fff;
      margin-bottom: 20upx;
      .list-top,.list-bottom {
        padding: 20upx 0;
        color: #999999;
        .app-bold {
          color: #333;
        }
        .freight-text {
          margin-right: 60upx;
        }
        .app-green {
          color: green;
        }
      }
      .list-bottom {
        & > view {
          @include disFlex(center, flex-end);
        }
        .list-button {
          margin-top: 26upx;
          display: flex;
          justify-content: flex-end;
          flex-wrap: nowrap;
          .admin-button-com {
            margin-left: 30upx;
            padding: 16upx 20upx;
            white-space: nowrap;
          }
        }
      }
    }
  }
}
.input-wrap {
  padding: 10upx 10upx 0upx 10upx;
  height:110upx;
  .search-bar {
    display:inline-block;
    width:190upx;
  }
}

/* 筛选面板样式（参考 goods/list.vue） */
.filter-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: flex-start;
  justify-content: center;
}

.filter-panel {
  background-color: #fff;
  border-radius: 0 0 20upx 20upx;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-50upx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes filterDotBlink {
  0%, 100% {
    background-color: #ffffff;
  }
  50% {
    background-color: #ff3b30;
  }
}

.filter-header {
  text-align: center;
  padding: 16upx 0;
  font-size: 32upx;
  font-weight: bold;
  border-bottom: 1upx solid #f0f0f0;
  color: #333;
}

.filter-section {
  padding: 28upx 40upx;
  border-bottom: 1upx solid #f0f0f0;
  &:last-child {
    border-bottom: none;
  }
}

.filter-title {
  font-size: 28upx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20upx;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 20upx;
}

.filter-option {
  padding: 16upx 32upx;
  border: 2upx solid #e0e0e0;
  border-radius: 25upx;
  font-size: 26upx;
  color: #666;
  background-color: #fff;
  text-align: center;
  min-width: 120upx;
  transition: all 0.3s ease;
  &.active {
    border-color: #52c41a;
    background-color: #f6ffed;
    color: #52c41a;
    font-weight: 600;
  }
}

.filter-actions {
  display: flex;
  padding: 30upx 40upx;
  gap: 20upx;
}

.filter-action-btn {
  flex: 1;
  padding: 14upx 0;
  border-radius: 12upx;
  font-size: 28upx;
  border: none;
  font-weight: 600;
  &.clear-btn {
    background-color: #f5f5f5;
    color: #666;
  }
  &.confirm-btn {
    background-color: #09C567;
    color: #fff;
  }
}
</style>