package com.zcloud.basic.info.command.query;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.PageResponse;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jjb.saas.framework.auth.model.SSOUser;
import com.jjb.saas.framework.auth.utils.AuthContext;
import com.zcloud.basic.info.command.convertor.UserCoConvertor;
import com.zcloud.basic.info.domain.gateway.UserGateway;
import com.zcloud.basic.info.domain.model.UserE;
import com.zcloud.basic.info.dto.*;
import com.zcloud.basic.info.dto.clientobject.UserCO;
import com.zcloud.basic.info.dto.clientobject.UserXmfCO;
import com.zcloud.basic.info.persistence.dataobject.UserCorpDO;
import com.zcloud.basic.info.persistence.dataobject.UserDO;
import com.zcloud.basic.info.persistence.repository.UserCorpRepository;
import com.zcloud.basic.info.persistence.repository.UserRepository;
import com.zcloud.gbscommon.excelEntity.UserExcelExportEntity;
import com.zcloud.gbscommon.utils.DesensitizationUtils;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * web-app
 *
 * @Author zhangyue
 * @Date 2025-11-04 14:07:36
 */
@Component
@AllArgsConstructor
public class UserQueryExe {
    private final UserRepository userRepository;
    private final UserGateway userGateway;
    private final UserCoConvertor userCoConvertor;
    private final UserCorpRepository userCorpRepository;

    /**
     * 分页
     *
     * @param userPageQry
     * @return
     */
    public PageResponse<UserCO> execute(UserPageQry userPageQry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(userPageQry);
        UserE userE = new UserE();
        userE.dataProcessingRights(AuthContext.getTenantId(), params);
        PageResponse<UserDO> pageResponse = userRepository.listPage(params);
        List<UserCO> examCenterCOS = userCoConvertor.converDOsToCOs(pageResponse.getData());

        return PageResponse.of(examCenterCOS, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }


    /**
     * 查询集合
     *
     * @param userQryCmd
     * @return
     */
    public MultiResponse<UserCO> executeListAll(UserQryCmd userQryCmd) {

        Map<String, Object> params = PageQueryHelper.toHashMap(userQryCmd);
        List<UserDO> imgFilesDOList = userRepository.listAll(params);
        List<UserCO> imgFilesCOList = userCoConvertor.converDOsToCOs(imgFilesDOList);

        return MultiResponse.of(imgFilesCOList);
    }


    /**
     * 详情
     *
     * @param id
     * @return
     */
    public SingleResponse<UserCO> executeGetInfo(Long id) {
        UserDO userDO = userRepository.getInfoById(id);
        UserCO userCO = new UserCO();
        BeanUtils.copyProperties(userDO, userCO);
        //如果是相关方流动人员，查找岗位部门
        UserCorpDO userCorpDO = userCorpRepository.getInfoByUserId(userCO.getId(),AuthContext.getTenantId());
        if(userCorpDO != null){
            userCO.setDepartmentId(userCorpDO.getDepartmentId());
            userCO.setPostId(userCorpDO.getPostId());
            userCO.setPostName(userCorpDO.getPostName());
            userCO.setRoleId(userCorpDO.getRoleId());
            userCO.setSort(userCorpDO.getSort());
            userCO.setCorpinfoId(userCorpDO.getCorpinfoId());
            userCO.setEmploymentFlag(userCorpDO.getEmploymentFlag());
        }

        return SingleResponse.of(userCO);
    }


    /**
     * 验证用户是否存在
     *
     * @param userVerifyQryCmd
     * @return
     */
    public Response executeVerifyUser(UserVerifyQryCmd userVerifyQryCmd) {
        Map<String, Object> params = PageQueryHelper.toHashMap(userVerifyQryCmd);
        Response response = userGateway.countUser(params);
        return response;
    }

    /**
     * 验证手机号是否存在
     *
     * @return
     */
    public void executeVerifyPhone(UserVerifyPhoneCmd cmd) {
        List<UserDO> userDOS = userRepository.listByPhone(cmd.getPhone());
        if(CollUtil.isNotEmpty(userDOS)){
            throw new BizException("手机号已被注册。");
        }
    }


    public List<UserCO> listByUserIds(Collection<Long> collection) {
        QueryWrapper<UserDO> userDOQueryWrapper = new QueryWrapper<>();
        userDOQueryWrapper.in("id",collection);
        List<UserDO> list = userRepository.list(userDOQueryWrapper);
        List<UserCO> userCOS = userCoConvertor.converDOsToCOs(list);
        return userCOS;
    }

    public List<UserCO> getUserList() {
        List<UserDO> list = userRepository.list();
        List<UserCO> userCOS = userCoConvertor.converDOsToCOs(list);
        return userCOS;
    }

//    private void desensitize(UserCO userCO) {
//        userCO.setUserIdCard(DesensitizationUtils.idCardDesensitize(userCO.getUserIdCard()));
//        userCO.setPhone(DesensitizationUtils.mobileDesensitize(userCO.getPhone()));
//    }

    public UserCO getInfoByUserId(Long aLong) {
        UserDO byId = userRepository.getById(aLong);
        UserCO userCO = userCoConvertor.converDOToCO(byId);
        return userCO;
    }

    /**
     * 导出用户
     */
    public void exportUserTable(HttpServletResponse httpServletResponse, Long[] ids, Long corpinfoId) {
        Map<String, Object> params = new HashMap<>();
        params.put("corpinfoId", corpinfoId);
        if(ids != null && ids.length > 0) {
            params.put("userIdList", Arrays.asList(ids));
        }
        List<UserDO> userDOList = userRepository.listAll(params);
        List<UserExcelExportEntity> userExcelExportEntities = userCoConvertor.converDOsToExcelEntitys(userDOList);
        UserE userE  = new UserE();
        userE.exportUserTable(httpServletResponse, userExcelExportEntities);
    }



    /**
     * 详情
     *
     *
     * @return
     */
    public SingleResponse<UserCO> executeGetInfoBySession() {
        SSOUser ssoUser = AuthContext.getCurrentUser();
        Long id = ssoUser.getUserId();
        UserDO userDO = userRepository.getInfoById(id);
        UserCO userCO = new UserCO();
        BeanUtils.copyProperties(userDO, userCO);
        return SingleResponse.of(userCO);
    }

    public SingleResponse<UserCO> getEncryInfo(UserCheckPassWordCmd userCheckPassWordCmd) {
        UserE userE = new UserE();
        BeanUtils.copyProperties(userCheckPassWordCmd, userE);
        userE.encryptionPassword();
        UserDO userDO = userRepository.getEncryInfo(userE);
        return SingleResponse.of(userCoConvertor.converDOToCO(userDO));
    }

    public PageResponse<UserXmfCO> listXgf(UserPageQry userPageQry) {
        Map<String, Object> params = PageQueryHelper.toHashMap(userPageQry);
        UserE userE = new UserE();
        userE.dataProcessingRights(AuthContext.getTenantId(), params);
        PageResponse<UserDO> pageResponse = userRepository.listXgf(params);
        List<UserXmfCO> userXmfCOList = userCoConvertor.converDOsToXgfCOs(pageResponse.getData());

        return PageResponse.of(userXmfCOList, pageResponse.getTotalCount(), pageResponse.getPageSize(), pageResponse.getPageIndex());
    }
}

