package com.ruoyi.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.code.DictConstant;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.controller.req.CanFellReq;
import com.ruoyi.controller.req.StatisticsReq;
import com.ruoyi.controller.resp.StatisticsResp;
import com.ruoyi.enums.order.OrderStatusEnums;
import com.ruoyi.frequency.customer.entity.Customer;
import com.ruoyi.frequency.customer.service.CustomerService;
import com.ruoyi.frequency.order.entity.Order;
import com.ruoyi.frequency.order.service.OrderService;
import com.ruoyi.frequency.store.entity.Store;
import com.ruoyi.frequency.store.service.StoreService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.RyController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 首页
 */
@CrossOrigin
@RestController
@RequestMapping("/api/home")
@Api(tags = "首页")
public class ApiHomeController extends RyController {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private BusinessUtil businessUtil;

    @Autowired
    private RedisService redisService;


    @PostMapping("/canFell")
    @ApiOperation(value = "是否可以体验app或者小程序", notes = "是否可以体验app或者小程序")
    public ResponseData canFell(@RequestBody CanFellReq req) {
        SysDictData dict = businessUtil.getDict("need_fell");
        if (dict == null || StrUtil.isBlank(dict.getDictValue())) {
            return ResponseData.success();
        }
        if ("2".equals(dict.getDictValue())) {
            return ResponseData.success();
        }

        dict = businessUtil.getDict("fell_pwd");
        if (dict == null) {
            return ResponseData.error("未配置字典，请联系平台");
        }
        if (StrUtil.isBlank(dict.getDictValue())) {
            return ResponseData.error("未配置字典，请联系平台");
        }
        if (!dict.getDictValue().equals(req.getCode())) {
            return ResponseData.error("密码错误");
        }
        return ResponseData.success();
    }


    @PostMapping("/statistics")
    @ApiOperation(value = "首页统计", notes = "首页统计")
    public ResponseData<StatisticsResp> statistics(@RequestBody(required = false) StatisticsReq req) {
        StatisticsResp statisticsResp = new StatisticsResp();

        //平台设置比例系数
        Integer scale = Integer.valueOf(businessUtil.getDict(DictConstant.平台设置比例系数).getDictValue());

        //查询入驻设计师
        int customerNum = customerService.count(new QueryWrapper<Customer>().lambda()
                .ne(Customer::getDelFlag, PublicCommon.删除));
        statisticsResp.setCustomerNum(customerNum + scale);

        //在线入驻设计师
        int onlineCustomerNum = customerService.count(new QueryWrapper<Customer>().lambda()
                .eq(Customer::getOnlineStatus, PublicCommon.在线)
                .ne(Customer::getDelFlag, PublicCommon.删除));
        statisticsResp.setOnlineCustomerNum(onlineCustomerNum);

        //查询入驻技术
        List<Store> list = storeService.list(new QueryWrapper<Store>().lambda()
                .ne(Store::getDelFlag, PublicCommon.删除));

        int storeNum = 0;
        if (list.size() > 0) {
            //查询已经认证的表现师
            storeNum = storeService.getAuthStore(list.stream().map(Store::getId).collect(Collectors.toList()), req.getIfHighend());
        }

        statisticsResp.setStoreNum(storeNum + scale);


        List<Long> userIds = new ArrayList<>();

        //在线表现师数
        String last_time_map_key = "last_time_" + 2;

        Map<String, Object> cacheMap = redisService.getCacheMap(last_time_map_key);

        cacheMap.forEach((key, value) -> {

            long lastTimes = Long.valueOf(value.toString());

            if (System.currentTimeMillis() - lastTimes < (6 * 60 * 1000)) {
                userIds.add(Long.valueOf(key));
            }
        });

        int onlineStoreNum = userIds.size();

        if (userIds.size() > 0) {
            //查询已经认证的表现师
            onlineStoreNum = storeService.getAuthStore(userIds, req.getIfHighend());
        }

        statisticsResp.setOnlineStoreNum(onlineStoreNum + scale);

        //成交订单数
        int orderNum = orderService.count(new QueryWrapper<Order>().lambda()
                .ge(Order::getStatus, OrderStatusEnums.to_be_evaluated.getCode()));
        statisticsResp.setOrderNum(orderNum + scale);

        return ResponseData.success(statisticsResp);
    }
}
