<template>
  <view class="root">
	  <view class="bgImg">
	  	<view class="orderSum">
	  	  <view class="orderSumLeft">
	  	   <view class="myShop">
	  	   	本月盈利
	  	   </view>
		   <view class="monthMoney">
		   	￥ {{ monthMoney }}
		   </view>
		   <view class="addMoney">
		   + {{ monthOrder }}
		   </view>
	  	  </view>
		  <!-- 登录 -->
		      <view class="orderSumRight" v-if="user.message==='ok'">
		        <view class="userImg">
		          <image :src="user.userAvatar" class="user"></image>
				  <view class="addOrder">
				  	今日盈利
				  </view>
				  <view class="monthOrder">
				  	￥{{ todayMoney }}
				  </view>
				  <view class="addOrder">
				  	+{{todayOrder}}
				  </view>
		        </view>
		      </view>
		  	<!-- 未登录 -->
		  <view class="orderSumRight" v-else>
		    <view class="userImg">
		      <image src="../../static/logo.png" class="user"></image>
		    </view>
		  </view>
	  	</view>
	  </view>
   
    <view class="feature">
      <view class="square" v-for="(item, index) in featureList" :key="index">
        <navigator class="imageContainer" :url="item.url">
          <image :src="item.imgUrl" class="image"></image>
        </navigator>
        <view class="featureName">{{ item.name }}</view>
      </view>
    </view>
	<view class="setting">
	   <view class="merchantSetting">
	     店铺设置
	   </view>
	   <view class="settingList">
	    <view class="state">
	      营业状态
	      &nbsp;&nbsp;&nbsp;
	      关
	     <switch 
	       :checked="storeStatus === 1" 
	       @change="handleSwitchChange" 
	       color="#FFCC33" 
	       style="transform:scale(0.7)"
	     />
	      开
	    </view>
	     <view class="state">
	       账号管理
	     </view>
	     <view class="logout" @click="logout">
	       退出登录
	     </view>
	   </view>
	 </view>
  </view>
   
</template>

<script>
import { apiImageUrl } from '../../API/api';

export default {
  data() {
    return {
      user: {
        userAvatar: '',
        userName: '',
        message: ''
      },
      featureList: [
        { url: '/pages/announcement/announcement', imgUrl: '../../static/Gourmet/meishi.png', name: '公告管理' },
        { url: '/pages/product/product', imgUrl: '../../static/Gourmet/meishi_caomei.png', name: '商品管理' },
        { url: '/pages/Statistics/Statistics', imgUrl: '../../static/Gourmet/meishi_hanbao.png', name: '数据统计' },
        { url: '/pages/orderManagement/orderManagement', imgUrl: '../../static/Gourmet/meishi_li.png', name: '订单管理' },
        { url: '/pages/bleConnect/bleConnect', imgUrl: '../../static/Gourmet/meishi_mangguo.png', name: '蓝牙服务' },
        { url: '/pages/evaluate/evaluate', imgUrl: '../../static/Gourmet/meishi_manyuemei.png', name: '评价管理' },
        { url: '/pages/distribution/distribution', imgUrl: '../../static/Gourmet/meishi_niunai.png', name: '配送服务' },
        { url: '/pages/more/more', imgUrl: '../../static/Gourmet/meishi_tusi.png', name: '更多功能' }
      ],
      range: [],
      storeStatus: 0,
	    monthMoney: '0.00',
		 monthOrder:'0',
		  todayMoney:'0.00',
		 todayOrder:'0'
    };
  },
  onLoad() {
    this.getLoginUser();
  },
  onShow() {
    this.getLoginUser();
  },
  methods: {
    getLoginUser() {
      uni.request({
        url: apiImageUrl + '/api/business/get/current',
        method: 'POST',
        header: {
          'cookie': uni.getStorageSync("cookie")
        },
        success: (res) => {
          console.log(res);
          uni.setStorageSync('businessId', res.data.data.id);
          uni.setStorageSync('businessName', res.data.data.businessName);
          this.storeStatus = res.data.data.storeStatus; 
          console.log(res.data.data);
          this.user.message = res.data.message;
          if (this.user.message === 'ok') {
            this.user.userName = res.data.data.businessName;
            this.user.userAvatar = res.data.data.businessAvatar;
            this.getMonthMoney(); 
            this.getMonthOrder(); 
            this.getDayMoney();
            this.getDayOrder();
          }
        },
        fail() {
          console.log('出错啦');
        }
      });
    },
	   async getMonthMoney() { 
	      try {
			const today = new Date(); 
			const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1); 
	        const response = await uni.request({
	          url: apiImageUrl + '/api/orders/count/money',
	          method: 'POST',
	          header: {
	            'cookie': uni.getStorageSync("cookie")
	          },
	          data: {
	            businessId: uni.getStorageSync("businessId"),
	            businessName: uni.getStorageSync("businessName"),
	            businessState: 0,
	            categoryId: 1,
	            endTime: today.toISOString().split('T')[0], 
	            startTime: firstDayOfMonth.toISOString().split('T')[0], 
	            state: 1,
	            type: "1"
	          }
	        });
	        console.log(response[1].data.data);
	        this.monthMoney = `${response[1].data.data}`; 
	      } catch (error) {
	        console.log(error);
	      }
	    },
		async getMonthOrder() { 
		   try {
			 const today = new Date();
			 const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
		     const response = await uni.request({
		       url: apiImageUrl + '/api/orders/count/number',
		       method: 'POST',
		       header: {
		         'cookie': uni.getStorageSync("cookie")
		       },
		       data: {
		         businessId: uni.getStorageSync("businessId"),
		         businessName: uni.getStorageSync("businessName"),
		         businessState: 0,
		         categoryId: 1,
		         endTime: today.toISOString().split('T')[0],
		         startTime: firstDayOfMonth.toISOString().split('T')[0],
		         state: 1,
		         type: "1"
		       }
		     });
		     console.log(response[1].data.data);
		     this.monthOrder = `${response[1].data.data}`; 
		   } catch (error) {
		     console.log(error);
		   }
		 },
		async getDayMoney() { 
		  try {
		    const today = new Date();
		    const startOfDay = new Date(today);
		    startOfDay.setHours(0, 0, 0, 0); 
		    const endOfDay = new Date(today);
		    endOfDay.setHours(23, 59, 59, 999); 
		
		    const response = await uni.request({
		      url: apiImageUrl + '/api/orders/count/money',
		      method: 'POST',
		      header: {
		        'cookie': uni.getStorageSync("cookie")
		      },
		      data: {
		        businessId: uni.getStorageSync("businessId"),
		        businessName: uni.getStorageSync("businessName"),
		        businessState: 0,
		        categoryId: 1,
		        endTime: endOfDay.toISOString().split('T')[0], 
		        startTime: startOfDay.toISOString().split('T')[0], 
		        state: 1,
		        type: "1"
		      }
		    });
		    console.log(response[1].data.data);
		    this.todayMoney = `${response[1].data.data}`; 
		  } catch (error) {
		    console.log(error);
		  }
		},
		async getDayOrder() {
		  try {
		    const today = new Date(); 
		    const startOfDay = new Date(today);
		    startOfDay.setHours(0, 0, 0, 0); 
		    const endOfDay = new Date(today);
		    endOfDay.setHours(23, 59, 59, 999); 
		
		    const response = await uni.request({
		      url: apiImageUrl + '/api/orders/count/number',
		      method: 'POST',
		      header: {
		        'cookie': uni.getStorageSync("cookie")
		      },
		      data: {
		        businessId: uni.getStorageSync("businessId"),
		        businessName: uni.getStorageSync("businessName"),
		        businessState: 0,
		        categoryId: 1,
		        endTime: endOfDay.toISOString().split('T')[0],
		        startTime: startOfDay.toISOString().split('T')[0], 
		        state: 1,
		        type: "1"
		      }
		    });
		    console.log(response[1].data.data);
		    this.todayOrder = `${response[1].data.data}`; 
		  } catch (error) {
		    console.log(error);
		  }
		},
    orderSumRight() {
      uni.navigateTo({
        url: '/pages/money/money'
      });
    },
    logout() {
      uni.removeStorageSync('identify');
      uni.removeStorageSync('cookie');
      uni.removeStorageSync('userInfo');
      uni.reLaunch({
        url: '/pages/login/login'
      });
      uni.showToast({
        title: '退出成功',
        duration: 2000
      });
    },
    handleSwitchChange(e) {
      const newStatus = e.detail.value ? 1 : 0; 
      const businessId = uni.getStorageSync('businessId'); 
    
      if (!businessId) {
        uni.showToast({ title: '未找到商家信息', icon: 'none' });
        return;
      }
    
      uni.request({
        url: `${apiImageUrl}/api/business/update/my`, 
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'cookie': uni.getStorageSync("cookie")
        },
        data: {
          storeStatus: newStatus
        },
        success: (res) => {
          console.log(res);
          if (res.data?.code === 0) { 
            this.storeStatus = newStatus; 
            uni.showToast({ 
              title: `已${newStatus ? '开业' : '打烊'}`, 
              icon: 'success'
            });
          } else {
            uni.showToast({ 
              title: res.data?.message || '操作失败', 
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          console.error('请求失败:', error);
          uni.showToast({ 
            title: '网络异常，请重试', 
            icon: 'none'
          });
        }
      });
    }
  }
};
</script>

<style>
.bgImg {
    width: 100%;
    height: 500rpx; 
    background-image: url(../../static/myBgc.jpg);
    background-size: cover; 
    background-position: center; 
    background-repeat: no-repeat;
	border-radius: 0 0 50px 50px;
}
.orderSum {
	width: 90%;
	height: 150px;
	margin: 0 auto;
	display: flex;
	align-items: center; 
	padding-top: 40px;
}

.orderSumLeft {
	flex: 1.5;
	height: 100%;
	padding-left: 15px;
}
.myShop {
	padding-top: 60rpx;
	font-size: 20px;
	color: #fff;
}
.monthMoney {
	padding-top: 30rpx;
	font-size: 30px;
	color: #fff;
}
.addMoney {
	padding-top: 20rpx;
	font-size: 14px;
	color: #fff;
}
.monthOrder {
	padding-top: 24rpx;
	font-size: 20px;
	color: #fff;
}
.addOrder {
	padding-top: 10rpx;
	font-size: 14px;
	color: #fff;
}
.orderSumRight {
	flex: 1;
	height: 100%;
}

.feature {
  width: 100%; 
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  padding: 10px; 
  box-sizing: border-box;
  margin: 0 auto;
  border-radius: 15px;
  border: 4px solid #ebebeb;
}

@media (max-width: 768px) { 
  .feature {
    flex-wrap: wrap;
  }
}


.square {
	width: calc((100% - 20px*3) / 4); 
	height: 70px; 
	margin-bottom: 10px; 
	margin-top: 10px;
	box-sizing: border-box;
}
.imageContainer {
	width: 70%;
	height: 70%;
	margin: 0 auto;
}
.image {
	width: 100%;
	height: 100%;
}
.featureName {
	font-size: 15px;
	margin-top: 5px;
	text-align: center;
}
.merchantSetting {
	margin-top: 10px;
	font-size: 35rpx;
	font-weight: 700;
	padding: 10px;
	color: #fff;
	background-color: #2237bf;
}
.settingList {
	width: 70%;
	margin: 0 auto;
}
.state {
	font-size:35rpx;
	font-weight: 700;
    margin-top: 20px;
}
.time {
	margin-top: 10px;
}
.logout {
	width: 80%;
	height: 100rpx;
	line-height: 100rpx;
	font-size: 35rpx;
	text-align: center;
    background-color: #2237bf;
	border-radius: 15px;
	margin: 0 auto;
	color: #fff;
	margin-top: 10px;
}
.userImg {
	width: 60%;
	height: 50%;
	margin-top: 30px;
	margin-left: 15px;
}
.user {
	width: 120rpx;
	height: 120rpx;
	border-radius: 50%;
	margin-left: 20px;
}

</style>