package com.ruoyi.frequency.enterprise.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.DictConstant;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.controller.req.StorePageReq;
import com.ruoyi.controller.req.UserEditReqVo;
import com.ruoyi.controller.resp.StorePageResp;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.frequency.enterprise.entity.Enterprise;
import com.ruoyi.frequency.enterprise.mapper.EnterpriseMapper;
import com.ruoyi.frequency.enterprise.model.result.EnterpriseCount;
import com.ruoyi.frequency.enterprise.service.EnterpriseService;
import com.ruoyi.frequency.store.service.StoreService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业信息Service业务层处理
 *
 * @author liwenlong
 * @date 2023-10-26
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise>  implements EnterpriseService
{
    @Autowired
    private EnterpriseMapper enterpriseMapper;

    /**
     * 查询企业信息
     *
     * @param id 企业信息主键
     * @return 企业信息
     */
    @Override
    public Enterprise selectEnterpriseById(Long id)
    {

        Enterprise enterprise = enterpriseMapper.selectEnterpriseById(id);

        if (enterprise != null){
            Set<UserVo> userVoSet = CollectionUtil.newHashSet(new UserVo(enterprise.getUserType(), enterprise.getUserId()));
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,null);

            enterprise.setUserInfo(userMap.get(new UserVo(enterprise.getUserType(), enterprise.getUserId())));
        }

        return enterprise;
    }


    @Autowired
    private UserService userService;

    /**
     * 查询企业信息列表
     *
     * @param enterprise 企业信息
     * @return 企业信息
     */
    @Override
    public List<Enterprise> selectEnterpriseList(Enterprise enterprise)
    {

        List<Enterprise> enterprises = enterpriseList(enterprise);

        if (enterprises.size() > 0){
            Set<UserVo> userVoSet = enterprises.stream().map(s -> new UserVo(s.getUserType(), s.getUserId())).collect(Collectors.toSet());
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,null);

            enterprises.stream().forEach(s ->{
                s.setUserInfo(userMap.get(new UserVo(s.getUserType(), s.getUserId())));
            });
        }

        return enterprises;
    }

    private List<Enterprise> enterpriseList(Enterprise enterprise){
        List<Enterprise> enterprises = enterpriseMapper.selectEnterpriseList(enterprise);
        return enterprises;
    }

    @Override
    public EnterpriseCount statistics(Enterprise enterprise) {
        List<Enterprise> enterprises = enterpriseList(enterprise);
        List<Long> enterpriseList = enterprises.stream().map(x -> x.getId()).collect(Collectors.toList());
        enterpriseList.add(-1L);

        return enterpriseMapper.statistics(enterpriseList);
    }



    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService sysUserService;
    /**
     * 新增企业信息
     *
     * @param enterprise 企业信息
     * @return 结果
     */
    @Override
    public int insertEnterprise(Enterprise enterprise)
    {

        //生成企业后台账号
        SysUser user = new SysUser();
        user.setUserName(enterprise.getAccount());
//        user.setPhonenumber(s.getAccount());
        String password = configService.selectConfigByKey("sys.user.initPassword");
        user.setPassword(SecurityUtils.encryptPassword(ObjectUtil.isNotEmpty(enterprise.getLoginPwd())?enterprise.getLoginPwd():password));
        user.setNickName(enterprise.getName());
        user.setUserType("01");
        if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(user.getUserName())))
        {

            throw new CustomException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user)))
        {
            throw new CustomException("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        SysRole sysRole = new SysRole();
        sysRole.setRoleKey("enterprise");
        List<SysRole> sysRoles = sysRoleService.selectRoleList(sysRole);

        //角色
        user.setRoleIds(new Long[]{sysRoles.get(0).getRoleId()});

        sysUserService.insertUser(user);

        //表现师关联企业
        enterprise.setSysUserId(user.getUserId());
        this.save(enterprise);

        return 1;

    }

    /**
     * 修改企业信息
     *
     * @param enterprise 企业信息
     * @return 结果
     */
    @Override
    public int updateEnterprise(Enterprise enterprise)
    {
        enterprise.setUpdateTime(DateUtils.getNowDate());
        int i = enterpriseMapper.updateById(enterprise);
        if (ObjectUtil.isNotEmpty(enterprise.getLoginPwd())){
            Enterprise enterprise1 = enterpriseMapper.selectEnterpriseById(enterprise.getId());
            String password = SecurityUtils.encryptPassword(enterprise.getLoginPwd());
            SysUser sysUser = new SysUser();
            sysUser.setUserId(enterprise1.getSysUserId());
            sysUser.setPassword(password);
            sysUserService.updateUser(sysUser);
        }
        return i;
    }


    @Autowired
    private StoreService storeService;
    /**
     * 批量删除企业信息
     *
     * @param ids 需要删除的企业信息主键
     * @return 结果
     */
    @Override
    public int deleteEnterpriseByIds(Long[] ids,Integer delFlag)
    {
        this.lambdaUpdate().set(Enterprise::getDelFlag,delFlag).in(Enterprise::getId,ids).update();

        //修改对应后台企业账号状态
        if(ObjectUtil.equal(PublicCommon.删除,delFlag)){
//            storeService.lambdaUpdate().set(Store::getBindEnterpriseId,null).in(Store::getBindEnterpriseId,ids).update();

            List<Enterprise> enterprises = enterpriseMapper.selectBatchIds(Arrays.asList(ids));

            Long[] sysUserIds = enterprises.stream().map(Enterprise::getSysUserId).toArray(Long[]::new);
            //删除对应后台企业账号
            sysUserService.deleteUserByIds(sysUserIds);
        }else if(ObjectUtil.equal(PublicCommon.禁用,delFlag)){
//            storeService.lambdaUpdate().set(Store::getBindEnterpriseId,null).in(Store::getBindEnterpriseId,ids).update();
        }

        return ids.length;
    }

    /**
     * 删除企业信息信息
     *
     * @param id 企业信息主键
     * @return 结果
     */
    @Override
    public int deleteEnterpriseById(Long id)
    {
        this.lambdaUpdate().set(Enterprise::getDelFlag,PublicCommon.删除).eq(Enterprise::getId,id).update();
        return 1;
    }

    @Override
    public ResponseData editInfo(UserEditReqVo req, UserVo userVo) {

        LambdaUpdateChainWrapper<Enterprise> lambdaUpdate = this.lambdaUpdate();
        //头像
        if (ObjectUtil.isNotEmpty(req.getAvatar())){
            lambdaUpdate.set(Enterprise::getAvatar, req.getAvatar());
        }

        //区域
        if (ObjectUtil.isNotEmpty(req.getArea())){
            lambdaUpdate.set(Enterprise::getArea, req.getArea());
        }

        //条件
        lambdaUpdate.eq(Enterprise::getId, userVo.getUserId()).update();

        if (ObjectUtil.isNotEmpty(req.getEnterDate())){
            userService.storeByEnterprise(userVo);
            UserEditReqVo userEditReqVo = new UserEditReqVo();
            userEditReqVo.setEnterDate(req.getEnterDate());
            return storeService.editInfo(userEditReqVo, userVo);
        }

        return ResponseData.success();
    }

    @Autowired
    private RedisService redisService;

    @Autowired
    private BusinessUtil businessUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public ResponseData<PageResult<Page<StorePageResp>>> enterprisePage(StorePageReq req, UserVo userVo) {
        //筛去拉黑与被拉黑用户
        List<UserVo> blockUserList = userService.blockUserList(userVo);
        req.setBlockUserList(blockUserList);

        //筛去屏蔽用户
        List<UserVo> shieldUserList = userService.shieldUserList(userVo);
        req.setShieldUserList(shieldUserList);

        if (req.getType() == 1) {
            //拼接排序
            List<SysDictData> dictList = businessUtil.getDictList(DictConstant.技术列表排序权重);

            dictList = dictList.stream().sorted(Comparator.comparing(SysDictData::getDictValue)).collect(Collectors.toList());

            String sortSql = "";

            if (dictList != null && dictList.size() > 0) {

                for (SysDictData dictData : dictList) {
                    if (dictData.getCode().equals(DictConstant.TechnologySort.在线时长)) {
                        sortSql = sortSql.concat(" tt.online_duration DESC,");
                    } else if (dictData.getCode().equals(DictConstant.TechnologySort.订单数量)) {
                        sortSql = sortSql.concat(" tt.orderNum DESC,");
                    } else if (dictData.getCode().equals(DictConstant.TechnologySort.订单金额)) {
                        sortSql = sortSql.concat(" tt.orderAmount DESC,");
                    } else if (dictData.getCode().equals(DictConstant.TechnologySort.好评率)) {
                        sortSql = sortSql.concat(" tt.star DESC");
                    }
                }
                req.setSortSql(sortSql);
            }
        }

        //从业年限筛选
        if (ObjectUtil.isNotEmpty(req.getYearRange())){
            String[] split = req.getYearRange().split("-");
            if (split.length == 1){
                req.setMaxYear(Integer.valueOf(split[0]));
            }
            if (split.length == 2){
                req.setMinYear(Integer.valueOf(split[0]));
                req.setMaxYear(Integer.valueOf(split[1]));
            }
        }

        //在线状态筛选;1:在线,2离线
        if (ObjectUtil.isNotEmpty(req.getOnlineStatus())){

            //企业
            Integer userType = UserEnums.enterprise.getCode();

            //上次调用此接口的时间
            String last_time_map_key = "last_time_" + userType;

            List<Long> userIds = new ArrayList<>();

            if (redisTemplate.hasKey(last_time_map_key)) {

                Map<String, Object> cacheMap = redisService.getCacheMap(last_time_map_key);

                cacheMap.forEach((key,value)->{

                    long lastTimes = Long.valueOf(value.toString());

                    if (System.currentTimeMillis() - lastTimes < (6 * 60 * 1000)){
                        userIds.add(Long.valueOf(key));
                    }
                });

                //userIds为空 直接返回
                if (userIds.size() == 0){
                    if (ObjectUtil.equal(1,req.getOnlineStatus())){
                        return ResponseData.success(new PageResult<>(new Page<>(req.getPageNo(),req.getPageSize())));
                    }else {
                        req.setOnlineStatus(null);
                    }
                }else {
                    req.setUserIds(userIds);
                }

            }else {
                if (ObjectUtil.equal(1,req.getOnlineStatus())){
                    return ResponseData.success(new PageResult<>(new Page<>(req.getPageNo(),req.getPageSize())));
                }else {
                    req.setOnlineStatus(null);
                }
            }


        }


        Page<StorePageResp> page = enterpriseMapper.enterprisePage(new Page<>(req.getPageNo(), req.getPageSize()), req, userVo);

        if (!page.getRecords().isEmpty()){

            //上次调用此接口的时间
            String last_time_map_key = "last_time_" + UserEnums.enterprise.getCode();

            //用户id
            Set<UserVo> userVoSet = page.getRecords().stream().map(s -> new UserVo(s.getUserType(), s.getId())).collect(Collectors.toSet());

            //获取用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,userVo);

            page.getRecords().stream().forEach(s->{

                //获取在线状态
                Integer onlineStatus =  businessUtil.getOnlineStatus(req.getIsWorkingDrawing() ==2?s.getBindEnterpriseId():s.getId(), last_time_map_key);
                s.setOnlineStatus(onlineStatus);

                s.setUserInfo(userMap.get(new UserVo(s.getUserType(), s.getId())));
            });
        }

        return ResponseData.success(new PageResult<>(page));
    }
}
