package com.ruoyi.demo.service.impl;

import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.demo.entity.*;
import com.ruoyi.demo.entity.bo.PlanBo;
import com.ruoyi.demo.entity.bo.StatisticsAddBo;
import com.ruoyi.demo.entity.vo.PlanHomeVo;
import com.ruoyi.demo.entity.vo.ScanListVo;
import com.ruoyi.demo.entity.vo.TimeAndCountVo;
import com.ruoyi.demo.mapper.*;
import com.ruoyi.demo.service.StatisticsService;
import com.ruoyi.demo.utils.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Transactional
public class StatisticsServiceImpl implements StatisticsService {
    @Autowired
    StatisticsMapper statisticsMapper;
    @Autowired
    DlUserMapper dlUserMapper;
    @Autowired
    AppMapper appMapper;
    @Autowired
    EquipmentMapper equipmentMapper;
    @Autowired
    PlanMapper planMapper;

    @Override
    public PageInfo<List<ScanListVo>> getScanList(PlanBo bo) {
        PageHelper.startPage(bo.getPageNum(),bo.getPageSize(),true);
        QueryWrapper<Statistics> queryWrapper = new QueryWrapper<>();
        if (bo.getStartTime() != null)
            queryWrapper.apply("`time` >= STR_TO_DATE({0},'%Y-%m-%d %H:%i:%s')",bo.getStartTime());
        if (bo.getEndTime() != null)
            queryWrapper.apply("`time` <= STR_TO_DATE({0},'%Y-%m-%d %H:%i:%s')",bo.getEndTime());
        List<Statistics> list = statisticsMapper.selectList(queryWrapper);
        List<ScanListVo> vos = new ArrayList<>();
        for (Statistics statistics : list){
            vos.add(new ScanListVo(statistics));
        }
        return new PageInfo(vos);
    }

    @Override
    public PlanHomeVo getScanTotal() {
        PlanHomeVo vo = new PlanHomeVo();
        vo.setTotal(statisticsMapper.selectTotal());
        vo.setTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        return vo;
    }

    @Override
    public String getSign(StatisticsAddBo bo) {
        QueryWrapper<App> appQueryWrapper = new QueryWrapper<>();
        appQueryWrapper.eq("appkey",bo.getAppkey());
        appQueryWrapper.eq("state",1);
        appQueryWrapper.eq("deleted","0");
        App app = appMapper.selectOne(appQueryWrapper);
        if (app == null)
            return "error";
        Map<String,Object> params = Dict.create()
            .set("appkey",bo.getAppkey())
            .set("equipmentCode",bo.getEquipmentCode())
            .set("goodsId",bo.getGoodsId())
            .set("goodsName",bo.getGoodsName())
            .set("time",bo.getTime())
            .set("userId",bo.getUserId())
            .set("userName",bo.getUserName())
            .set("userTelephone",bo.getUserTelephone())
            .set("vendorId",bo.getVendorId())
            .set("vendorName",bo.getVendorName())
            .set("sign",bo.getSign());
        return SignUtil.sign(params,app.getAppSecret());
    }

    // 添加扫码行为记录
    @Override
    public int add(StatisticsAddBo bo) {
        QueryWrapper<App> appQueryWrapper = new QueryWrapper<>();
        appQueryWrapper.eq("appkey",bo.getAppkey());
        appQueryWrapper.eq("state",1);
        appQueryWrapper.eq("deleted","0");
        App app = appMapper.selectOne(appQueryWrapper);
        if (app == null)
            return -1;
        Map<String,Object> params = Dict.create()
            .set("appkey",bo.getAppkey())
            .set("equipmentCode",bo.getEquipmentCode())
            .set("goodsId",bo.getGoodsId())
            .set("goodsName",bo.getGoodsName())
            .set("time",bo.getTime())
            .set("userId",bo.getUserId())
            .set("userName",bo.getUserName())
            .set("userTelephone",bo.getUserTelephone())
            .set("vendorId",bo.getVendorId())
            .set("vendorName",bo.getVendorName())
            .set("sign",bo.getSign());
        if (!SignUtil.verify(params,app.getAppSecret()))
            return -3;
        // 验证通过后，如果用户不存在，则添加用户；否则不管
        QueryWrapper<Equipment> equipmentQueryWrapper = new QueryWrapper<>();
        equipmentQueryWrapper.eq("equipment_code",bo.getEquipmentCode());
        Equipment equipment = equipmentMapper.selectOne(equipmentQueryWrapper);

        QueryWrapper<DlUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id",bo.getUserId());
        DlUser user = dlUserMapper.selectOne(userQueryWrapper);

        if (user == null)
            dlUserMapper.insert(new DlUser(bo,equipment));
        // 添加扫码行为记录
        return statisticsMapper.insert(new Statistics(bo,equipment));
    }

    @Override
    public Map<String, Integer> getTimeDis(String option) {
        Map<String, Integer> map = new LinkedHashMap<>();
        if (option.equals("day")){
            for (int i=0;i<30;i++){
                String day = LocalDateTime.now(ZoneId.of("Asia/Shanghai")).plusDays(-i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                map.put(day,statisticsMapper.selectTimeDisByDay(day));
            }
        } else if (option.equals("year")){
            for (int i=0;i<12;i++){
                String year = LocalDateTime.now(ZoneId.of("Asia/Shanghai")).plusYears(-i).format(DateTimeFormatter.ofPattern("yyyy"));
                map.put(year,statisticsMapper.selectTimeDisByYear(year));
            }
        } else {
            for (int i=0;i<12;i++){
                String month = LocalDateTime.now(ZoneId.of("Asia/Shanghai")).plusMonths(-i).format(DateTimeFormatter.ofPattern("yyyy-MM"));
                map.put(month,statisticsMapper.selectTimeDisByMonth(month));
            }
        }
        return map;
    }

    @Override
    public List<TimeAndCountVo> getTimeDisToVo(String option) {
        List<TimeAndCountVo> vos = new ArrayList<>();
        if (option.equals("day")){
            for (int i=0;i<30;i++){
                TimeAndCountVo vo = new TimeAndCountVo();
                vo.setTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")).plusDays(-i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                vo.setCount(statisticsMapper.selectTimeDisByDay(vo.getTime()));
                vos.add(vo);
            }
        } else if (option.equals("year")){
            for (int i=0;i<12;i++){
                TimeAndCountVo vo = new TimeAndCountVo();
                vo.setTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")).plusYears(-i).format(DateTimeFormatter.ofPattern("yyyy")));
                vo.setCount(statisticsMapper.selectTimeDisByYear(vo.getTime()));
                vos.add(vo);
            }
        } else {
            for (int i=0;i<12;i++){
                TimeAndCountVo vo = new TimeAndCountVo();
                vo.setTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")).plusMonths(-i).format(DateTimeFormatter.ofPattern("yyyy-MM")));
                vo.setCount(statisticsMapper.selectTimeDisByMonth(vo.getTime()));
                vos.add(vo);
            }
        }
        return vos;
    }
}
