package org.dromara.work.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Month;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.system.domain.SysDept;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.SysDeptBo;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.domain.vo.SysDeptVo;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.work.domain.TpClientStaff;
import org.dromara.work.domain.TpOrder;
import org.dromara.work.domain.bo.OrderRankingBo;
import org.dromara.work.domain.vo.DeptRankingVo;
import org.dromara.work.domain.vo.OrderDayListVo;
import org.dromara.work.domain.vo.PerCountVo;
import org.dromara.work.domain.vo.PerSumVo;
import org.dromara.work.mapper.TpClientStaffMapper;
import org.dromara.work.mapper.TpOrderMapper;
import org.dromara.work.service.IOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

@RequiredArgsConstructor
@Service
public class OrderServiceImpl extends MPJBaseServiceImpl<TpOrderMapper, TpOrder> implements IOrderService {

    private final TpOrderMapper baseMapper;

    private final SysDeptMapper deptMapper;

    private final TpClientStaffMapper clientStaffMapper;

    private final SysUserMapper sysUserMapper;

    /**
     * 部门排行榜（客服）
     *
     * @param bo
     * @return
     */
    @Override
    public List<DeptRankingVo> deptRankingList(SysDeptBo bo) {
//        DateTime dateTime = new DateTime(bo.getMonth(), DatePattern.NORM_MONTH_FORMAT);
//        Month month1 = dateTime.monthEnum();
//        int lastDay = month1.getLastDay(false);
//        bo.setStartTime(bo.getMonth() + "-01 00:00:00");
//        bo.setEndTime(bo.getMonth() + "-" + lastDay + " 23:59:59");

        List<SysDeptVo> list = deptMapper.selectVoList(new LambdaQueryWrapper<SysDept>().eq(SysDept::getParentId, bo.getDeptId()));
        for (SysDeptVo dept : list){
            boolean exist = deptMapper.exists(new LambdaQueryWrapper<SysDept>().eq(SysDept::getParentId, dept.getDeptId()));
            if(exist){
                bo.setIsNull(1);
                break;
            }else {
                bo.setIsNull(0);
            }
        }
        return baseMapper.deptRankingList(bo);
    }

    @Override
    public List<DeptRankingVo> deptRankingList1(SysDeptBo bo) {
//        DateTime dateTime = new DateTime(bo.getMonth(), DatePattern.NORM_MONTH_FORMAT);
//        Month month1 = dateTime.monthEnum();
//        int lastDay = month1.getLastDay(false);
//        bo.setStartTime(bo.getMonth() + "-01 00:00:00");
//        bo.setEndTime(bo.getMonth() + "-" + lastDay + " 23:59:59");
        bo.setIsNull(0);
        return baseMapper.deptRankingList(bo);
    }


        /**
     * 部门排行榜（技术）
     * @param bo
     * @return
     */
    @Override
    public List<DeptRankingVo> deptRankingJSList(SysDeptBo bo) {
//        DateTime dateTime = new DateTime(bo.getMonth(), DatePattern.NORM_MONTH_FORMAT);
//        Month month1 = dateTime.monthEnum();
//        int lastDay = month1.getLastDay(false);
//        bo.setStartTime(bo.getMonth() + "-01 00:00:00");
//        bo.setEndTime(bo.getMonth() + "-" + lastDay + " 23:59:59");

        List<SysDeptVo> list = deptMapper.selectVoList(new LambdaQueryWrapper<SysDept>().eq(SysDept::getParentId, bo.getDeptId()));
        for (SysDeptVo dept : list){
            boolean exist = deptMapper.exists(new LambdaQueryWrapper<SysDept>().eq(SysDept::getParentId, dept.getDeptId()));
            if(exist){
                bo.setIsNull(1);
                break;
            }else {
                bo.setIsNull(0);
            }
        }
        return baseMapper.deptRankingJSList(bo);
    }

    @Override
    public List<DeptRankingVo> deptRankingJSList1(SysDeptBo bo) {
//        DateTime dateTime = new DateTime(bo.getMonth(), DatePattern.NORM_MONTH_FORMAT);
//        Month month1 = dateTime.monthEnum();
//        int lastDay = month1.getLastDay(false);
//        bo.setStartTime(bo.getMonth() + "-01 00:00:00");
//        bo.setEndTime(bo.getMonth() + "-" + lastDay + " 23:59:59");
        bo.setIsNull(0);
        return baseMapper.deptRankingJSList(bo);
    }

    /**
     * 客服日统计
     *
     * @param bo
     * @param userIds
     * @return
     */
    @Override
    public List<OrderDayListVo> kfDayList(OrderRankingBo bo, List<Long> userIds) {
        return baseMapper.kfDayList(bo, userIds);
    }

    /**
     * 分图月统计
     *
     * @param bo
     * @param userIds
     * @return
     */
    @Override
    public List<OrderDayListVo> ftDayList(OrderRankingBo bo, List<Long> userIds) {
        return baseMapper.ftDayList(bo, userIds);
    }

    /**
     * 技术月统计
     *
     * @param bo
     * @param userIds
     * @return
     */
    @Override
    public List<OrderDayListVo> jsDayList(OrderRankingBo bo, List<Long> userIds) {
        return baseMapper.jsDayList(bo, userIds);
    }


     /**
     * 业绩按月统计
     *
     * @param month
     * @param deptId
     * @return
     */
    @Override
    public List<PerSumVo> monthArrivedPer(String month, Long deptId) {
        List<Long> deptIds = null;
        if(deptId != null){
            deptIds = deptMapper.selectList(new LambdaQueryWrapper<SysDept>().like(SysDept::getAncestors, deptId)).stream().map(SysDept::getDeptId).collect(Collectors.toList());
            deptIds.add(deptId);
        }
        return baseMapper.monthArrivedPer(month,deptIds);
    }

    /**
     * 业绩按年统计
     *
     * @param year
     * @param deptId
     * @return
     */
    @Override
    public List<PerSumVo> yearArrivedPer(String year, Long deptId) {
        List<Long> deptIds = null;
        if(deptId != null){
            deptIds = deptMapper.selectList(new LambdaQueryWrapper<SysDept>().like(SysDept::getAncestors, deptId)).stream().map(SysDept::getDeptId).collect(Collectors.toList());
            deptIds.add(deptId);
        }
        return baseMapper.yearArrivedPer(year,deptIds);
    }

    /**
     * 订单类型统计
     *
     * @param month
     * @param deptId
     * @return
     */
    @Override
    public List<PerCountVo> monthOrderType(String month, Long deptId) {
        List<Long> deptIds = null;
        if(deptId != null){
            deptIds = deptMapper.selectList(new LambdaQueryWrapper<SysDept>().like(SysDept::getAncestors, deptId)).stream().map(SysDept::getDeptId).collect(Collectors.toList());
            deptIds.add(deptId);
        }
        return baseMapper.monthOrderType(month,deptIds);
    }

    /**
     * 订单空间统计
     *
     * @param month
     * @param deptId
     * @return
     */
    @Override
    public List<PerCountVo> monthOrderSpace(String month, Long deptId) {
        List<Long> deptIds = null;
        if(deptId != null){
            deptIds = deptMapper.selectList(new LambdaQueryWrapper<SysDept>().like(SysDept::getAncestors, deptId)).stream().map(SysDept::getDeptId).collect(Collectors.toList());
            deptIds.add(deptId);
        }
        return baseMapper.monthOrderSpace(month,deptIds);
    }

    /**
     * 订单风格统计
     *
     * @param month
     * @param deptId
     * @return
     */
    @Override
    public List<PerCountVo> monthOrderStyle(String month, Long deptId) {
        List<Long> deptIds = null;
        if(deptId != null){
            deptIds = deptMapper.selectList(new LambdaQueryWrapper<SysDept>().like(SysDept::getAncestors, deptId)).stream().map(SysDept::getDeptId).collect(Collectors.toList());
            deptIds.add(deptId);
        }
        return baseMapper.monthOrderStyle(month,deptIds);
    }

    /**
     * 新老客户占比
     *
     * @param month
     * @param deptId
     * @return
     */
    @Override
    public List<PerCountVo> newOldOrderPer(String month, Long deptId) {
        String startDay = "";
        String endDay = "";
        if (StringUtils.isEmpty(month)){
            month = DateUtil.format(new Date(), "yyyy-MM");
            DateTime dateTime = new DateTime(month, DatePattern.NORM_MONTH_FORMAT);
            Month month1 = dateTime.monthEnum();
            int lastDay = month1.getLastDay(false);
            startDay = month + "-01 00:00:00";
            endDay = month + "-" + lastDay + " 23:59:59";

        }else{
            DateTime dateTime = new DateTime(month, DatePattern.NORM_MONTH_FORMAT);
            Month month1 = dateTime.monthEnum();
            int lastDay = month1.getLastDay(false);
            startDay = month + "-01 00:00:00";
            endDay = month + "-" + lastDay + " 23:59:59";
        }
        List<Long> deptIds = null;
        List<Long> userIds = null;
        if(deptId != null){
            deptIds = deptMapper.selectList(new LambdaQueryWrapper<SysDept>().like(SysDept::getAncestors, deptId)).stream().map(SysDept::getDeptId).collect(Collectors.toList());
            deptIds.add(deptId);
            userIds = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>().in(SysUser::getDeptId, deptIds)).stream().map(SysUser::getUserId).collect(Collectors.toList());
        }
        Long newCount = clientStaffMapper.selectCount(new LambdaQueryWrapper<TpClientStaff>().between(TpClientStaff::getAddTime, startDay, endDay).in(userIds != null, TpClientStaff::getSid,userIds));
        Long oldCount = clientStaffMapper.selectCount(new LambdaQueryWrapper<TpClientStaff>().between(TpClientStaff::getAddTime, "2023-04-01 00:00:01", startDay).in(userIds != null,TpClientStaff::getSid,userIds));

        List<PerCountVo> list = new ArrayList<>();
        PerCountVo newPer = new PerCountVo();
        newPer.setType("新用户");
        newPer.setCount(newCount);

        PerCountVo oldPer = new PerCountVo();
        oldPer.setType("老用户");
        oldPer.setCount(oldCount);

        list.add(newPer);
        list.add(oldPer);
        return list;
    }

    /**
     * @param sysUserBo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateOrder(SysUserBo sysUserBo) {
        SysDept dept = deptMapper.selectById(sysUserBo.getDeptId());
        SysUser user = sysUserMapper.selectById(sysUserBo.getUserId());
        user.setDeptId(dept.getDeptId());
        sysUserMapper.updateById(user);

        if(sysUserBo.getIdentity() == 2){
            return baseMapper.update(null,
                Wrappers.<TpOrder>lambdaUpdate()
                    .set(TpOrder::getDeptIdJs, dept.getDeptId())
                    .set(TpOrder::getAncestorsJs,dept.getAncestors())
                    .eq(TpOrder::getBid, sysUserBo.getUserId())
                    .eq(TpOrder::getIsDel, 1)) > 0;
        }else if(sysUserBo.getIdentity() == 3){
            return baseMapper.update(null,
                Wrappers.<TpOrder>lambdaUpdate()
                    .set(TpOrder::getDeptId, dept.getDeptId())
                    .set(TpOrder::getAncestors,dept.getAncestors())
                    .eq(TpOrder::getSid, sysUserBo.getUserId())
                    .eq(TpOrder::getIsDel, 1)) > 0;
        }
        return false;
    }
}
