package com.yeejoin.amos.boot.module.jczs.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jczs.api.dto.TzsCitInfoDto;
import com.yeejoin.amos.boot.module.jczs.api.entity.TzsCitInfo;
import com.yeejoin.amos.boot.module.jczs.api.mapper.TzsCitInfoMapper;
import com.yeejoin.amos.boot.module.jczs.api.service.ITzsCitInfoService;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

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

/**
 *  服务实现类
 *
 * @author duanwei
 * @date 2022-12-19
 */
@Service
public class TzsCitInfoServiceImpl extends BaseService<TzsCitInfoDto, TzsCitInfo, TzsCitInfoMapper> implements ITzsCitInfoService {

    @Value("${duty.seats.role.ids}")
    private String dutySeatsRoleIds;

    @Autowired
    private RedisUtils redisUtils;

    /**
     *  获取值班所有人员列表
     */
    @Override
    public List<AgencyUserModel> getUserList(){
        ReginParams regionParam = this.getReginParams();
        Long companyId = regionParam.getCompany().getSequenceNbr();
        String[] roleIds = dutySeatsRoleIds.split(",");
        //通过roleIds拿到该对应的人员
        FeignClientResult<List<AgencyUserModel>> userListResult = Privilege.agencyUserClient.queryByCompanyId(companyId,null,null,null);
        List<AgencyUserModel> userList = userListResult.getResult();
        // 排除非系统中人员
        userList = userList.stream().filter(u -> {
            AgencyUserModel agencyUser = Privilege.agencyUserClient.queryByUserId(u.getUserId()).getResult();
            Set<Long> set = new HashSet<>(agencyUser.getOrgRoleSeqs().get(companyId));
            if(!ValidationUtil.isEmpty(set)) {
                for (int i = 0; i < roleIds.length; i++) {
                    if (set.contains(Long.valueOf(roleIds[i]))) {
                        return true;
                    }
                }
            }
            return false;
        }).collect(Collectors.toList());

        return userList;
    }

    @Override
    public String saveOrUpdateInfo(TzsCitInfo tzsCitInfo){
        //校验
        String massage = "",code = "",extphone  = "";
        TzsCitInfo citInfo = this.getById(tzsCitInfo.getSequenceNbr());
        if(!ValidationUtil.isEmpty(citInfo)){
            code = citInfo.getCode();
            extphone = citInfo.getExtphone();
        }
        if(ValidationUtil.isEmpty(tzsCitInfo.getSequenceNbr())) {
            if (!ValidationUtil.isEmpty(tzsCitInfo.getCtiUserId())) {
                if (!ValidationUtil.isEmpty(this.list(new LambdaQueryWrapper<TzsCitInfo>().eq(TzsCitInfo::getCtiUserId, tzsCitInfo.getCtiUserId())))) {
                    massage = "该用户已有坐席账号，不可重复添加！";
                    return massage;
                }
            }
        }
        if(!code.equals(tzsCitInfo.getCode())) {
            if (!ValidationUtil.isEmpty(this.list(new LambdaQueryWrapper<TzsCitInfo>().eq(TzsCitInfo::getCode, tzsCitInfo.getCode())))) {
                massage = "登录坐席参数code已存在，不可重复添加！";
                return massage;
            }
        }
        if(!extphone.equals(tzsCitInfo.getExtphone())) {
            if (!ValidationUtil.isEmpty(this.list(new LambdaQueryWrapper<TzsCitInfo>().eq(TzsCitInfo::getExtphone, tzsCitInfo.getExtphone())))) {
                massage = "登录坐席参数extphone已存在，不可重复添加！";
                return massage;
            }
        }

        //保存数据
        if(!ValidationUtil.isEmpty(tzsCitInfo.getCtiUserId())) {
            AgencyUserModel agencyUser = Privilege.agencyUserClient.queryByUserId(String.valueOf(tzsCitInfo.getCtiUserId())).getResult();
            tzsCitInfo.setCtiUserName(agencyUser.getRealName());
            tzsCitInfo.setRegionCode(agencyUser.getCompanys().iterator().next().getCompanyCode());
        }
        this.saveOrUpdate(tzsCitInfo);
        return null;
    }

    /**
     * 用户单位信息redis获取
     **/
    public ReginParams getReginParams() {
        return JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
    }
}
