package com.ruoyi.demo.service.impl;

import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.demo.entity.*;
import com.ruoyi.demo.entity.bo.PlanAddBo;
import com.ruoyi.demo.entity.bo.PlanBo;
import com.ruoyi.demo.entity.vo.PlanDetailVo;
import com.ruoyi.demo.entity.vo.PlanItemVo;
import com.ruoyi.demo.entity.vo.PlanListVo;
import com.ruoyi.demo.entity.vo.PlanPushVo;
import com.ruoyi.demo.mapper.*;
import com.ruoyi.demo.service.PlanService;
import com.ruoyi.demo.utils.SignUtil;
import com.ruoyi.demo.utils.StateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class PlanServiceImpl implements PlanService {
    @Autowired
    PlanMapper planMapper;
    @Autowired
    PlanItemMapper planItemMapper;
    @Autowired
    PlanAuditMapper planAuditMapper;
    @Autowired
    AppMapper appMapper;
    @Autowired
    CommercialMapper commercialMapper;
    @Autowired
    SystemSetterMapper systemSetterMapper;

    @Override
    public int addPlan(PlanAddBo bo) {
        QueryWrapper<App> appQueryWrapper = new QueryWrapper<>();
        appQueryWrapper.eq("appkey",bo.getAppkey());
        appQueryWrapper.eq("show_delete",0);
        App app = appMapper.selectOne(appQueryWrapper);
        if (app == null)
            return -1;
        QueryWrapper<Commercial> commercialQueryWrapper = new QueryWrapper<>();
        commercialQueryWrapper.eq("commercial_id",bo.getCommercialId());
        Commercial commercial = commercialMapper.selectOne(commercialQueryWrapper);
        if (commercial == null)
            return -2;
        Map<String,Object> params = Dict.create()
            .set("appkey",bo.getAppkey())
            .set("commercialId",bo.getCommercialId())
            .set("goodsId",bo.getGoodsId())
            .set("goodsImg",bo.getGoodsImg())
            .set("goodsName",bo.getGoodsName())
            .set("goodsLogo",bo.getGoodsLogo())
            .set("goodsIntroduce",bo.getGoodsIntroduce())
            .set("goodsPrice",bo.getGoodsPrice())
            .set("goodsClassify",bo.getGoodsClassify())
            .set("planCreateTime",bo.getPlanCreateTime())
            .set("planStartTime",bo.getPlanStartTime())
            .set("planEndTime",bo.getPlanEndTime())
            .set("items",bo.getItems())
            .set("sign",bo.getSign());
        if (!SignUtil.verify(params,app.getAppSecret()))
            return -3;
        // 插入广告计划
        Plan plan = new Plan();
        plan.setCommercialId(commercial.getCommercialId());
        plan.setCommercialName(commercial.getCommercialName());
        plan.setAppkey(app.getAppkey());
        plan.setAppName(app.getAppName());
        plan.setGoodsId(bo.getGoodsId());
        plan.setGoodsImg(bo.getGoodsImg());
        plan.setGoodsName(bo.getGoodsName());
        plan.setGoodsLogo(bo.getGoodsLogo());
        plan.setGoodsIntroduce(bo.getGoodsIntroduce());
        plan.setGoodsClassify(bo.getGoodsClassify());
        plan.setPlanCreateTime(bo.getPlanCreateTime());
        plan.setPlanStartTime(bo.getPlanStartTime());
        plan.setPlanEndTime(bo.getPlanEndTime());
        plan.setState(StateUtil.NOT_AUDITED);
        planMapper.insert(plan);
        // 插入广告计划明细
        for (PlanItem item : bo.getItems()) {
            item.setPlanId(plan.getPlanId());
            planItemMapper.insert(item);
        }
        return 1;
    }

    @Override
    public int deletePlan(List<String> ids) {
        int i = 0;
        for (String id : ids){
            QueryWrapper<Plan> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("plan_id",id);
            i += planMapper.delete(queryWrapper);
        }
        return i;
    }

    @Override
    public int checkPlan(String planId, Integer state, String auditComment,String userId) {
        QueryWrapper<Plan> planQueryWrapper = new QueryWrapper<>();
        planQueryWrapper.eq("plan_id",planId);
        planQueryWrapper.eq("show_delete",0);
        Plan plan = planMapper.selectOne(planQueryWrapper);
        if (plan == null)
            return -1;
        plan.setState(state);
        int i = planMapper.updateById(plan);
        if (i == 0)
            return 0;
        PlanAudit audit = new PlanAudit();
        audit.setPlanId(planId);
        audit.setUserId(userId);
        audit.setState(state);
        audit.setAuditComment(auditComment);
        audit.setAuditTime(LocalDateTime.now());
        planAuditMapper.insert(audit);
        return 1;
    }

    @Override
    public List<PlanListVo> getPlanList(PlanBo bo) {
        QueryWrapper<Plan> planQueryWrapper = new QueryWrapper<>();
        if (bo.getState() != null)
            planQueryWrapper.eq("state",bo.getState());
        if (bo.getAppkey() != null)
            planQueryWrapper.like("appkey",bo.getAppkey());
        if (bo.getAppName() != null)
            planQueryWrapper.like("app_name",bo.getAppName());
        if (bo.getGoods() != null){
            planQueryWrapper.like("goods_name",bo.getGoods())
                .or()
                .like("goods_introduce",bo.getGoods());
        }
        planQueryWrapper.eq("show_delete",0);
        List<Plan> plans = planMapper.selectList(planQueryWrapper);
        List<PlanListVo> vos = new ArrayList<>();
        for (Plan plan : plans){
            vos.add(new PlanListVo(plan));
        }
        return vos;
    }

    @Override
    public PlanDetailVo getPlanDetail(String planId) {
        QueryWrapper<Plan> planQueryWrapper = new QueryWrapper<>();
        planQueryWrapper.eq("plan_id",planId);
        planQueryWrapper.eq("show_delete",0);
        Plan plan = planMapper.selectOne(planQueryWrapper);
        if (plan == null)
            return null;
        QueryWrapper<PlanItem> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("plan_id",planId);
        List<PlanItem> items = planItemMapper.selectList(itemQueryWrapper);
        List<PlanItemVo> itemVos = new ArrayList<>();
        if (items != null)
            for (PlanItem item : items){
                itemVos.add(new PlanItemVo(item));
            }
        PlanDetailVo vo = new PlanDetailVo(plan, itemVos);
        return vo;
    }

    @Override
    public List<PlanPushVo> getPlanPush() {
//        查询可投放的广告计划
//        再根据每个广告计划，查询其明细
//        返回结果
        QueryWrapper<SystemSetter> systemSetterQueryWrapper = new QueryWrapper<>();
        SystemSetter setter = systemSetterMapper.selectOne(systemSetterQueryWrapper);
        QueryWrapper<Plan> planQueryWrapper = new QueryWrapper<>();
        planQueryWrapper.apply("DATE_FORMAT(plan_start_time,'%Y-%m-%d %H:%i:%s') <= DATE_FORMAT({0},'%Y-%m-%d %H:%i:%s')",LocalDateTime.now());
        planQueryWrapper.apply("DATE_FORMAT(plan_end_time,'%Y-%m-%d %H:%i:%s') > DATE_FORMAT({0},'%Y-%m-%d %H:%i:%s')",LocalDateTime.now());
        planQueryWrapper.eq("state",1);
        List<PlanPushVo> pushVos = new ArrayList<>();
        for (Plan plan : planMapper.selectList(planQueryWrapper)) {
            QueryWrapper<PlanItem> itemQueryWrapper = new QueryWrapper<>();
            itemQueryWrapper.eq("plan_id",plan.getPlanId());
            for (PlanItem item : planItemMapper.selectList(itemQueryWrapper)) {
                pushVos.add(new PlanPushVo(item,plan,setter));
            }
        }
        return pushVos;
    }
}
