package com.friday.custody.service.logicService.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.friday.custody.dao.DaasBuriedPointRecordInfoDao;
import com.friday.custody.entity.DaasBuriedPointRecordInfoEntity;
import com.friday.custody.enums.DaasDataTypeEnum;
import com.friday.custody.enums.RetCodeEnum;
import com.friday.custody.exception.RRException;
import com.friday.custody.req.DaasBuriedPointRecordReq;
import com.friday.custody.service.logicService.DaasBuriedPointRecordInfoService;
import com.friday.custody.utils.PageUtil;
import com.friday.custody.utils.PageUtils;
import com.friday.custody.utils.Query;
import com.friday.custody.utils.R;
import com.friday.custody.vo.DaasBuriedPointRecordInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;



@Service("daasBuriedPointRecordInfoService")
@Slf4j
public class DaasBuriedPointRecordInfoServiceImpl extends ServiceImpl<DaasBuriedPointRecordInfoDao, DaasBuriedPointRecordInfoEntity> implements DaasBuriedPointRecordInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DaasBuriedPointRecordInfoEntity> page = this.page(
                new Query<DaasBuriedPointRecordInfoEntity>().getPage(params),
                new QueryWrapper<DaasBuriedPointRecordInfoEntity>()
        );

        return new PageUtils(page);
    }

    public void saveDaasBuriedPointRecord(String admin, String invokeType, String type, String params) {
        try {
            String dataType = DaasDataTypeEnum.fromCode(type).getType();
            log.info("DaasBuriedPointRecord admin = {}, invokeType = {}, dataType = {}, params = {}", admin, invokeType, dataType, params);
            Date now = new Date();
            DaasBuriedPointRecordInfoEntity daasBuriedPointRecordInfoEntity = DaasBuriedPointRecordInfoEntity.builder()
                    .admin(admin)
                    .invokeType(invokeType)
                    .dataType(dataType)
                    .reqParam(JSONObject.toJSONString(params))
                    .invokeTime(now)
                    .createTime(now)
                    .updateTime(now)
                    .build();
            baseMapper.insert(daasBuriedPointRecordInfoEntity);
        }catch (Exception e){
            log.error("埋点记录失败！", e);
        }

    }

    public R queryDaasRecord(String params) {
        try {
            log.info("开始查询Daas数据为:{}", JSON.toJSONString(params));
            //1 封装查询参数
            DaasBuriedPointRecordReq req = JSON.parseObject(params, DaasBuriedPointRecordReq.class);
            //1.1 封装分页查询参数
            Map<String, Object> pageParams = PageUtil.getPageParams(req);
            //1.2 封装查询参数
            QueryWrapper<DaasBuriedPointRecordInfoEntity> queryWrapper = new QueryWrapper<>();

            if (StringUtils.isNotBlank(req.getAdmin())) {
                queryWrapper.eq("admin", req.getAdmin());
            }
            if (StringUtils.isNotBlank(req.getInvokeType())) {
                queryWrapper.eq("invoke_type", req.getInvokeType());
            }
            if (StringUtils.isNotBlank(req.getDataType())) {
                queryWrapper.eq("data_type", req.getDataType());
            }
            if (StringUtils.isNotBlank(req.getReqParam())) {
                queryWrapper.eq("req_param", req.getReqParam());
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            //开始和结束时间都为空，默认为一年
            //开始和结束时间都为空，默认为一年
            if (StringUtils.isBlank(req.getBeginDate())&&StringUtils.isBlank(req.getEndDate())) {
                c.setTime(new Date());
                c.add(Calendar.YEAR, -1);
                Date m = c.getTime();
                String beginYear = format.format(m);
                req.setBeginDate(beginYear);
                req.setEndDate(format.format(new Date()));
            }
            //开始不为空和结束时间为空，默认当天
            if (StringUtils.isBlank(req.getEndDate())&&StringUtils.isNotBlank(req.getBeginDate())) {
                c.setTime(format.parse(req.getBeginDate()));
                c.add(Calendar.YEAR, 1);
                Date m = c.getTime();
                String endYear = format.format(m);
                req.setBeginDate(req.getBeginDate());
                req.setEndDate(endYear);
            }

            try {
                LocalDate beginDate = LocalDate.parse(req.getBeginDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                LocalDate endDate = LocalDate.parse(req.getEndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Duration duration = Duration.between(beginDate.atTime(0, 0, 0),endDate.atTime(0, 0, 0));
                long days = duration.toDays(); //相差的天数
                if (days < 0) {
                    return R.error(RetCodeEnum.PARAM_ERROR.getCode(),"endDate早于beginDate");
                }
                if (days > 366) {
                    return R.error(RetCodeEnum.PARAM_ERROR.getCode(),"beginDate与endDate间隔的天数不能超过365天");
                }
            } catch (Exception e) {
                log.error("参数有误：beginDate :{"+ req.getBeginDate() + "}, endDate :{"+ req.getEndDate() +"}",e);
                return R.error(RetCodeEnum.PARAM_ERROR.getCode(),"beginDate或endDate格式不正确");
            }
            queryWrapper.ge("invoke_time", req.getBeginDate() + " 00:00:00");
            queryWrapper.le("invoke_time",req.getEndDate() + " 23:59:59");
            queryWrapper.orderBy(true,false, "admin","invoke_type","data_type","invoke_time");

            //2 执行检索
            IPage<DaasBuriedPointRecordInfoEntity> page = this.page(
                    new Query<DaasBuriedPointRecordInfoEntity>().getPage(pageParams),
                    queryWrapper
            );
            //封装数据
            PageUtils pageUtils = new PageUtils(page);
            List<DaasBuriedPointRecordInfoEntity> entities = page.getRecords();
            //entities 转vo
            ArrayList<DaasBuriedPointRecordInfoVO> vos = new ArrayList<>();
            for (DaasBuriedPointRecordInfoEntity entity : entities) {
                vos.add(DaasBuriedPointRecordInfoVO.builder()
                        .admin(entity.getAdmin())
                        .invokeType(entity.getInvokeType())
                        .dataType(entity.getDataType())
                        .reqParam(entity.getReqParam())
                        .invokeTime(entity.getInvokeTime())
                        .build());
            }
            pageUtils.setList(vos);
            log.info("Daas埋点信息查询成功...");
            return R.ok("Daas埋点信息查询成功").put("data",pageUtils);
        } catch (RRException rrException) {
            log.error("the QueryDataVo is :" + JSON.toJSONString(params) + ".the DaasBuriedPointRecord RRException is :", rrException);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), rrException.getMsg());
        } catch (Exception e) {
            log.error("the QueryDataVo is :" + JSON.toJSONString(params) + ".the DaasBuriedPointRecord Exception is :", e);
            return R.error(RetCodeEnum.OPERATION_ERROR.getCode(), "查询数据失败!");
        }
    }
}