package org.dromara.work.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.dto.RoleDTO;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysDept;
import org.dromara.system.domain.SysRoleDept;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.mapper.SysRoleDeptMapper;
import org.dromara.system.mapper.SysRoleMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.work.domain.TpClient;
import org.dromara.work.domain.TpOrder;
import org.dromara.work.domain.bo.OrderRankingBo;
import org.dromara.work.domain.vo.OrderRankingSumVo;
import org.dromara.work.domain.vo.OrderRankingVo;
import org.dromara.work.mapper.TpClientMapper;
import org.dromara.work.mapper.TpOrderMapper;
import org.dromara.work.service.ITpNewOrderService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: Maosw
 */
@RequiredArgsConstructor
@Service
public class TpNewOrderServiceImpl extends MPJBaseServiceImpl<TpOrderMapper, TpOrder> implements ITpNewOrderService {

    private final TpOrderMapper baseMapper;

    private final SysUserMapper sysUserMapper;

    private final SysDeptMapper deptMapper;

    private final SysRoleDeptMapper roleDeptMapper;

    private final TpClientMapper clientMapper;


    private MPJLambdaWrapper<TpOrder> buildQueryRankingMPJWrapper(OrderRankingBo bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        MPJLambdaWrapper<TpOrder> lqw = new MPJLambdaWrapper<>();
        if(bo.getDeptIds()!= null && bo.getDeptIds().size() > 0){
            if(bo.getType() == 1){
                lqw.in(TpOrder::getDeptId,bo.getDeptIds());
            } else if (bo.getType() == 2) {
                lqw.in(TpOrder::getDeptIdJs,bo.getDeptIds());
            }
        }else {
            int scope = getDataScope();
            if(scope == 2){
                List<Long> deptIds = getDeptIds();
                if(bo.getType() == 1){
                    lqw.in(TpOrder::getDeptId,deptIds);
                } else if (bo.getType() == 2) {
                    lqw.in(TpOrder::getDeptIdJs,deptIds);
                }
            }else if(scope == 3){
                if(bo.getType() == 1){
                    lqw.eq(TpOrder::getDeptId,loginUser.getDeptId());
                } else if (bo.getType() == 2) {
                    lqw.eq(TpOrder::getDeptIdJs,loginUser.getDeptId());
                }
            }else if(scope == 4){
                List<Long> deptIds = deptMapper.selectList(new LambdaQueryWrapper<SysDept>().like(SysDept::getAncestors, loginUser.getDeptId())).stream().map(SysDept::getDeptId).collect(Collectors.toList());
                deptIds.add(loginUser.getDeptId());
                if(bo.getType() == 1){
                    lqw.in(TpOrder::getDeptId,deptIds);
                } else if (bo.getType() == 2) {
                    lqw.in(TpOrder::getDeptIdJs,deptIds);
                }
            }else if(scope == 5){
                if(bo.getType() == 1){
                    lqw.eq(TpOrder::getSid,loginUser.getUserId());
                } else if (bo.getType() == 2) {
                    lqw.eq(TpOrder::getBid,loginUser.getUserId());
                }
            }
        }
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), SysUser::getNickName, bo.getUserName());
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), SysUser::getRealName, bo.getRealName());
        lqw.between(bo.getStartTime() != null && bo.getEndTime() != null,
            TpOrder::getAddTime ,bo.getStartTime(), bo.getEndTime());
        return lqw;
    }

    private MPJLambdaWrapper<TpOrder> buildKHRankingMPJWrapper(OrderRankingBo bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        MPJLambdaWrapper<TpOrder> lqw = new MPJLambdaWrapper<>();

        if(bo.getDeptIds()!= null && bo.getDeptIds().size() > 0){
            lqw.in(TpOrder::getDeptId,bo.getDeptIds());
        }else {
            int scope = getDataScope();
            if(scope == 2){
                List<Long> deptIds = getDeptIds();
                lqw.in(TpOrder::getDeptId,deptIds);
            }else if(scope == 3){
                lqw.eq(TpOrder::getDeptId,loginUser.getDeptId());
            }else if(scope == 4){
                List<Long> deptIds = deptMapper.selectList(new LambdaQueryWrapper<SysDept>().like(SysDept::getAncestors, loginUser.getDeptId())).stream().map(SysDept::getDeptId).collect(Collectors.toList());
                deptIds.add(loginUser.getDeptId());
                lqw.in(TpOrder::getDeptId,deptIds);
            }else if(scope == 5){
                lqw.eq(TpOrder::getSid,loginUser.getUserId());
            }
        }
        lqw.eq(StringUtils.isNotBlank(bo.getUserName()), TpClient::getCode, bo.getUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getRealName()), TpClient::getName, bo.getRealName());
        lqw.between(bo.getStartTime() != null && bo.getEndTime() != null,
            TpOrder::getAddTime ,bo.getStartTime(), bo.getEndTime());
        return lqw;
    }

    /**
     * 客服排行榜
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<OrderRankingVo> rankingList(OrderRankingBo bo, PageQuery pageQuery) {
        /*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");*/

        MPJLambdaWrapper<TpOrder> wrapper = buildQueryRankingMPJWrapper(bo)
            .selectAs(SysUser::getNickName,OrderRankingVo::getUserName)
            .selectAs(SysUser::getRealName,OrderRankingVo::getRealName)
            .selectAs(SysDept::getDeptName,OrderRankingVo::getDeptName)
            .selectAs("count(1)",OrderRankingVo::getOrderNum)
            .selectAs("sum(price)",OrderRankingVo::getTotalPerformance)
            .selectAs("sum(pay_price - kfpay)",OrderRankingVo::getCompletionAmount)
            .selectAs("sum(end_price)",OrderRankingVo::getUnpaidAmount)
            .selectAs("concat(round(sum(pay_price)/(SELECT CASE WHEN m.gongsi = 0 THEN m.geren ELSE m.gongsi END AS result_field FROM tp_month m WHERE m.sid = t.sid AND m.`month` = '" + bo.getMonth() + "') * 100),'%')",OrderRankingVo::getTargetCompletionRate)
            .selectAs("concat(round(sum(end_price)/sum(price) * 100),'%')",OrderRankingVo::getDeadOrderRate)
            .leftJoin(SysUser.class,SysUser::getUserId,TpOrder::getSid)
            .leftJoin(SysDept.class,SysDept::getDeptId,SysUser::getDeptId)
            .eq(TpOrder::getIsDel,1)
//            .ne(TpOrder::getPayState,1)
            .groupBy(TpOrder::getSid);

        wrapper.orderBy(bo.getSort() == 1,bo.getIsAsc(),OrderRankingVo::getOrderNum);
        wrapper.orderBy(bo.getSort() == 2,bo.getIsAsc(),OrderRankingVo::getTotalPerformance);
        wrapper.orderBy(bo.getSort() == 3,bo.getIsAsc(),OrderRankingVo::getCompletionAmount);
        wrapper.orderBy(bo.getSort() == 4,bo.getIsAsc(),OrderRankingVo::getUnpaidAmount);
        wrapper.orderBy(bo.getSort() == 5,bo.getIsAsc(),OrderRankingVo::getTargetCompletionRate);
        wrapper.orderBy(bo.getSort() == 6,bo.getIsAsc(),OrderRankingVo::getDeadOrderRate);

        IPage<OrderRankingVo> listPage = baseMapper.selectJoinPage(new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize()), OrderRankingVo.class, wrapper);
        return TableDataInfo.build(listPage);
    }

    /**
     * 技术排行榜
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<OrderRankingVo> rankingListJS(OrderRankingBo bo, PageQuery pageQuery) {
        MPJLambdaWrapper<TpOrder> wrapper = buildQueryRankingMPJWrapper(bo)
            .selectAs(SysUser::getNickName,OrderRankingVo::getUserName)
            .selectAs(SysUser::getRealName,OrderRankingVo::getRealName)
            .selectAs(SysDept::getDeptName,OrderRankingVo::getDeptName)
            .selectAs("count(1)",OrderRankingVo::getOrderNum)
            .selectAs("sum(js_price)",OrderRankingVo::getTotalPerformance)
            .selectAs("sum(js_pay_price)",OrderRankingVo::getCompletionAmount)
            .selectAs("sum(js_price) - sum(js_pay_price)",OrderRankingVo::getUnpaidAmount)
            .selectAs("concat(round(sum(js_pay_price)/sum(js_price) * 100),'%')",OrderRankingVo::getTargetCompletionRate)
            .selectAs("concat(round((sum(js_price) - sum(js_pay_price))/sum(js_price) * 100),'%')",OrderRankingVo::getDeadOrderRate)
            .leftJoin(SysUser.class,SysUser::getUserId,TpOrder::getBid)
            .leftJoin(SysDept.class,SysDept::getDeptId,SysUser::getDeptId)
            .eq(TpOrder::getIsDel,1)
            .groupBy(TpOrder::getBid);

        wrapper.isNotNull(TpOrder::getBid);
        wrapper.orderBy(bo.getSort() == 1,bo.getIsAsc(),OrderRankingVo::getOrderNum);
        wrapper.orderBy(bo.getSort() == 2,bo.getIsAsc(),OrderRankingVo::getTotalPerformance);
        wrapper.orderBy(bo.getSort() == 3,bo.getIsAsc(),OrderRankingVo::getCompletionAmount);
        wrapper.orderBy(bo.getSort() == 4,bo.getIsAsc(),OrderRankingVo::getUnpaidAmount);
        wrapper.orderBy(bo.getSort() == 5,bo.getIsAsc(),OrderRankingVo::getTargetCompletionRate);
        wrapper.orderBy(bo.getSort() == 6,bo.getIsAsc(),OrderRankingVo::getDeadOrderRate);

        IPage<OrderRankingVo> listPage = baseMapper.selectJoinPage(new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize()), OrderRankingVo.class, wrapper);
        return TableDataInfo.build(listPage);
    }

    /**
     * 客服排行榜统计
     *
     * @param bo
     * @return
     */
    @Override
    public OrderRankingSumVo rankingListKFSum(OrderRankingBo bo) {
        Long totalNum = sysUserMapper.selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getIdentity, 3));
        MPJLambdaWrapper<TpOrder> wrapper = buildQueryRankingMPJWrapper(bo)
            .selectAs("count(1)",OrderRankingSumVo::getTotalOrderNum)
            .selectAs("sum(price)",OrderRankingSumVo::getTotalPerformance)
            .selectAs("sum(pay_price - kfpay)",OrderRankingSumVo::getTotalPaidAmount)
            .selectAs("concat(round(sum(pay_price - kfpay)/sum(price) * 100),'%')",OrderRankingSumVo::getTotalCompletionRate)
            .leftJoin(SysUser.class,SysUser::getUserId,TpOrder::getSid)
            .leftJoin(SysDept.class,SysDept::getDeptId,SysUser::getDeptId)
            .eq(TpOrder::getIsDel,1);
//            .ne(TpOrder::getPayState,1);

        OrderRankingSumVo orderRankingSumVo = baseMapper.selectJoinOne(OrderRankingSumVo.class, wrapper);
        orderRankingSumVo.setTotalNum(totalNum);
        return orderRankingSumVo;
    }

    /**
     * 技术排行榜统计
     *
     * @param bo
     * @return
     */
    @Override
    public OrderRankingSumVo rankingListJSSum(OrderRankingBo bo) {
        Long totalNum = sysUserMapper.selectCount(new LambdaQueryWrapper<SysUser>().eq(SysUser::getIdentity, 2));
        MPJLambdaWrapper<TpOrder> wrapper = buildQueryRankingMPJWrapper(bo)
            .selectAs("count(1)",OrderRankingSumVo::getTotalOrderNum)
            .selectAs("sum(js_price)",OrderRankingSumVo::getTotalPerformance)
            .selectAs("sum(js_pay_price)",OrderRankingSumVo::getTotalPaidAmount)
            .selectAs("concat(round(sum(js_pay_price)/sum(js_price) * 100),'%')",OrderRankingSumVo::getTotalCompletionRate)
            .leftJoin(SysUser.class,SysUser::getUserId,TpOrder::getBid)
            .leftJoin(SysDept.class,SysDept::getDeptId,SysUser::getDeptId)
            .eq(TpOrder::getIsDel,1)
            .isNotNull(TpOrder::getBid);
//            .ne(TpOrder::getPayState,1);

        OrderRankingSumVo orderRankingSumVo = baseMapper.selectJoinOne(OrderRankingSumVo.class, wrapper);
        orderRankingSumVo.setTotalNum(totalNum);
        return orderRankingSumVo;
    }


    /**
     * 客户下单排行榜
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<OrderRankingVo> khRankingList(OrderRankingBo bo, PageQuery pageQuery) {
        MPJLambdaWrapper<TpOrder> wrapper = buildKHRankingMPJWrapper(bo)
            .selectAs(TpClient::getCode,OrderRankingVo::getUserName)
            .selectAs(TpClient::getName,OrderRankingVo::getRealName)
//            .selectAs(SysDept::getDeptName,OrderRankingVo::getDeptName)
            .selectAs("count(1)",OrderRankingVo::getOrderNum)
            .selectAs("sum(t.price)",OrderRankingVo::getTotalPerformance)
            .selectAs("sum(t.khpay)",OrderRankingVo::getCompletionAmount)
            .selectAs("sum(t.price) - sum(t.khpay)",OrderRankingVo::getUnpaidAmount)
            .selectAs("concat(round(sum(t.khpay)/sum(t.price) * 100),'%')",OrderRankingVo::getTargetCompletionRate)
            .leftJoin(TpClient.class,TpClient::getId,TpOrder::getKid)
//            .leftJoin(SysDept.class,SysDept::getDeptId,SysUser::getDeptId)
            .eq(TpOrder::getIsDel,1)
//            .ne(TpOrder::getPayState,1)
            .groupBy(TpOrder::getKid);
//            .orderByDesc("sum(js_price)");

        wrapper.orderBy(bo.getSort() == 1,bo.getIsAsc(),OrderRankingVo::getOrderNum);
        wrapper.orderBy(bo.getSort() == 2,bo.getIsAsc(),OrderRankingVo::getTotalPerformance);
        wrapper.orderBy(bo.getSort() == 3,bo.getIsAsc(),OrderRankingVo::getCompletionAmount);
        wrapper.orderBy(bo.getSort() == 4,bo.getIsAsc(),OrderRankingVo::getUnpaidAmount);
        wrapper.orderBy(bo.getSort() == 5,bo.getIsAsc(),OrderRankingVo::getTargetCompletionRate);

        IPage<OrderRankingVo> listPage = baseMapper.selectJoinPage(new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize()), OrderRankingVo.class, wrapper);
        return TableDataInfo.build(listPage);
    }

    /**
     * 客户下单排行榜统计
     *
     * @param bo
     * @return
     */
    @Override
    public OrderRankingSumVo khRankingListSum(OrderRankingBo bo) {
//        Long totalNum = clientMapper.selectCount(new LambdaQueryWrapper<TpClient>().eq(TpClient::getIsDel, 1));

        // 统计下单客户数量（去重）
        MPJLambdaWrapper<TpOrder> lqw = buildKHRankingMPJWrapper(bo)
            .selectAs("count(t.sid)", OrderRankingSumVo::getTotalNum)
            .leftJoin(TpClient.class, TpClient::getId, TpOrder::getKid)
            .groupBy(TpOrder::getKid);
        List<OrderRankingSumVo> list = baseMapper.selectJoinList(OrderRankingSumVo.class, lqw);

        MPJLambdaWrapper<TpOrder> wrapper = buildKHRankingMPJWrapper(bo)
            .selectAs("count(1)",OrderRankingSumVo::getTotalOrderNum)
            .selectAs("sum(t.price)",OrderRankingSumVo::getTotalPerformance)
            .selectAs("sum(t.khpay)",OrderRankingSumVo::getTotalPaidAmount)
            .selectAs("concat(round(sum(t.khpay)/sum(t.price) * 100),'%')",OrderRankingSumVo::getTotalCompletionRate)
            .leftJoin(TpClient.class,TpClient::getId,TpOrder::getKid)
            .eq(TpOrder::getIsDel,1);
//            .ne(TpOrder::getPayState,1);

        OrderRankingSumVo orderRankingSumVo = baseMapper.selectJoinOne(OrderRankingSumVo.class, wrapper);
        orderRankingSumVo.setTotalNum((long) list.size());
        return orderRankingSumVo;
    }

    public int getDataScope() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<String> ids = loginUser != null ?
            loginUser.getRoles().stream().filter(Objects::nonNull).map(role -> role.getDataScope()).filter(Objects::nonNull).collect(Collectors.toList()) :
            Collections.emptyList();

        if (ids.contains("1")) {
            return 1;
        } else if (ids.contains("2")) {
            return 2;
        } else if (ids.contains("3")) {
            return 3;
        } else if (ids.contains("4")) {
            return 4;
        } else if (ids.contains("5")) {
            return 5;
        }
        return 0;
    }

    public List<Long> getDeptIds(){
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<Long> roleIds = loginUser.getRoles().stream().map(RoleDTO::getRoleId).collect(Collectors.toList());
        List<Long> getDeptIds = roleDeptMapper.selectList(new LambdaQueryWrapper<SysRoleDept>().in(SysRoleDept::getRoleId, roleIds)).stream().map(SysRoleDept::getDeptId).collect(Collectors.toList());
        return getDeptIds.stream().distinct().collect(Collectors.toList());
    }


}
