package com.sckw.system.dubbo;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.web.response.result.PageDataResult;
import com.sckw.system.api.model.dto.res.*;
import com.sckw.system.dao.KwsAuthorityDao;
import com.sckw.system.dao.KwsEntDeptDao;
import com.sckw.system.dao.KwsEntTypeDao;
import com.sckw.system.dao.KwsEnterpriseDao;
import com.sckw.system.model.*;
import com.sckw.system.model.pojo.FindManagePojo;
import com.sckw.system.model.vo.res.CertificateResVo;
import com.sckw.system.model.vo.res.KwsUserResVo;
import com.sckw.system.repository.KwsEnterpriseRepository;
import com.sckw.system.service.KwsEnterpriseService;
import com.sckw.system.service.KwsRoleService;
import com.sckw.system.service.KwsSpecialService;
import com.sckw.system.service.KwsUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

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

/**
 * @author czh
 * @desc 提取公共
 * @date 2023/7/7
 */
@Service
public class RemoteBaseService {

    @Resource
    private KwsEnterpriseService kwsEnterpriseService;

    @Resource
    private KwsSpecialService kwsSpecialService;

    @Resource
    private KwsAuthorityDao kwsAuthorityDao;

//    @Resource
//    private KwsDeptService kwsDeptService;

    @Resource
    private KwsUserService kwsUserService;

    @Resource
    private KwsRoleService kwsRoleService;

    @Resource
    private KwsEntDeptDao kwsEntDeptDao;

    @Resource
    private KwsEntTypeDao kwsEntTypeDao;

    @Resource
    private KwsEnterpriseDao kwsEnterpriseDao;
    @Resource
    private KwsEnterpriseRepository kwsEnterpriseReposiory;


    public KwsEnterpriseResDto queryEnterpriseById(Long id) {
        if (Objects.isNull(id)) {
            return null;
        }
        KwsEnterprise kwsEnterprise = kwsEnterpriseService.queryKwsEnterpriseById(id);
        if (Objects.isNull(kwsEnterprise)) {
            return null;
        }

        KwsEnterpriseResDto kwsEnterpriseResDto = new KwsEnterpriseResDto();
        BeanUtils.copyProperties(kwsEnterprise, kwsEnterpriseResDto);
        return kwsEnterpriseResDto;
    }

    public KwsUserResDto getUserByAccount(String username) {
        Map<String, Object> params = new HashMap<>(Global.NUMERICAL_SIXTEEN) {{
            put("account", username);
        }};
        List<KwsUserResVo> list = kwsUserService.findList(params);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        KwsUserResDto kwsUserResDto = new KwsUserResDto();
        BeanUtils.copyProperties(list.get(0), kwsUserResDto);
        return kwsUserResDto;
    }

    public List<KwsUserDeptResDto> queryUserDeptByUserId(Long userId) {
        List<KwsUserDept> kwsUserDepts = kwsUserService.queryUserDeptByUserId(userId);
        if (CollectionUtils.isEmpty(kwsUserDepts)) {
            return Collections.emptyList();
        }
        return BeanUtils.copyToList(kwsUserDepts, KwsUserDeptResDto.class);
    }

    public List<KwsDeptResDto> queryDeptByIds(List<Long> ids) {
        List<KwsDept> kwsDepts = kwsUserService.queryDeptByIds(ids);
        if (CollectionUtils.isEmpty(kwsDepts)) {
            return Collections.emptyList();
        }

        return BeanUtils.copyToList(kwsDepts, KwsDeptResDto.class);
    }

    public List<KwsRoleResDto> queryRoleInfoByUserId(Long userId) {
        List<KwsRole> kwsRoles = kwsRoleService.queryRoleByUserId(userId);
        if (CollectionUtils.isEmpty(kwsRoles)) {
            return Collections.emptyList();
        }
        return BeanUtils.copyToList(kwsRoles, KwsRoleResDto.class);
    }

    public List<EntCertificateResDto> queryCertificateByEntId(Long entId) {
        List<CertificateResVo> certificate = kwsEnterpriseService.queryCertificate(entId);
        if (CollectionUtils.isEmpty(certificate)) {
            return Collections.emptyList();
        }
        return BeanUtils.copyToList(certificate, EntCertificateResDto.class);
    }

    public List<EntCheckTrackResDto> checkTrackByEntId(Long entId) {
        List<KwsEntCheckTrack> kwsEntCheckTracks = kwsEnterpriseService.entCheck(entId);
        if (CollectionUtils.isEmpty(kwsEntCheckTracks)) {
            return Collections.emptyList();
        }
        return BeanUtils.copyToList(kwsEntCheckTracks, EntCheckTrackResDto.class);
    }

//    public List<DeptInfoPojo> queryDeftInfoByEntId(long entId) {
//        KwsDept kwsDept = new KwsDept();
//        kwsDept.setEntId(entId);
//        kwsDept.setDelFlag(Global.NO);
//        List<KwsDeptResVo> list = kwsDeptService.findList(kwsDept);
//        if (CollectionUtils.isEmpty(list)) {
//            return Collections.emptyList();
//        }
//        return BeanUtils.copyToList(list, DeptInfoPojo.class);
//    }

    public List<KwsEnterprise> findEnts(Map<String, Object> params) {
        return kwsEnterpriseService.findEnts(params);
    }

    /**
     * @param entCacheResDto 返参
     * @desc: 填充父子属id
     * @author: czh
     * @date: 2023/7/17
     */
    public void fillRelate(EntCacheResDto entCacheResDto) {
        Long id = entCacheResDto.getId();
        KwsEntDept kwsEntDept = kwsEntDeptDao.selectByEntId(id);
        //不为空则是主体单位
        if (Objects.nonNull(kwsEntDept)) {
            entCacheResDto.setParentId(kwsEntDept.getEntPid());
            return;
        }

        List<KwsEntDept> kwsEntDepts = kwsEntDeptDao.selectByEntPid(id);
        if (CollectionUtils.isNotEmpty(kwsEntDepts)) {
            entCacheResDto.setEntDeptIds(String.join(Global.COMMA, kwsEntDepts.stream().map(KwsEntDept::getEntId).map(String::valueOf).toList()));
        }
    }

    public List<KwsEntDept> queryEntDeptCacheByIds(List<Long> entIds) {
        return kwsEntDeptDao.selectByEntPidList(entIds);
    }

    public Integer queryEntType(Long entId) {
        List<KwsEntType> list = kwsEntTypeDao.findListByEntId(entId);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }

        return list.get(0).getType();
    }

    public List<EntTypeResDto> queryEntTypeById(Long entId) {
        List<KwsEntType> list = kwsEntTypeDao.findListByEntId(entId);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }

        return BeanUtils.copyToList(list, EntTypeResDto.class);
    }

    /**
     * 根据用户姓名模糊查用户信息
     *
     * @param name 用户姓名
     * @return list
     */
    public List<KwsUserResDto> getUserByName(String name) {
        return kwsUserService.getUserByName(name);
    }

    /**
     * @param entId 企业ID
     * @desc 企业详情(企业登录 / 司机登录)
     * @author zk
     * @date 2023/8/10
     **/
    public EntCacheResDto queryEntDetails(Long entId) {
        return kwsEnterpriseService.queryEntDetails(entId);
    }

    /**
     * @param entName 企业名称
     * @return EntCacheResDto
     * @desc: 查企业
     * @author: czh
     * @date: 2023/7/17
     */
    public EntCacheResDto queryEntByName(String entName) {
        List<KwsEnterprise> ents = kwsEnterpriseService.findEnts(new HashMap<>() {{
            put("entName", entName);
        }});
        if (CollectionUtils.isEmpty(ents)) {
            return null;
        }
        return kwsEnterpriseService.queryEntDetails(ents.get(NumberConstant.ZERO).getId());
    }

    /**
     * @param cityCode 区域code  entTypeList 企业类型  entIdList 企业id
     * @return PageResult
     * @desc: 根据区域code和企业类型分页查询企业信息
     * @author: czh
     * @date: 2023/9/1
     */
    public List<KwsEnterprise> queryEntInfoByCityCodeAndEntTypesWithPage(Integer cityCode, List<Integer> entTypeList, List<Long> entIdList, String entName) {
        return kwsEnterpriseService.queryEntInfoByCityCodeAndEntTypesWithPage(cityCode, entTypeList, entIdList, entName);
    }

    /**
     * @param roleIds 角色id
     * @return KwsAuthority
     * @desc: 根据角色id查数据权限信息
     * @author: czh
     * @date: 2023/9/4
     */
    public List<KwsAuthority> queryAuthorityByRoles(List<Long> roleIds) {
        return kwsAuthorityDao.selectByRoleIds(roleIds);
    }

    /**
     * @param deptIds 机构id
     * @return KwsUser
     * @desc: 查机构下的用户
     * @author: czh
     * @date: 2023/9/4
     */
    public List<KwsUser> queryUserByDeptIds(List<Long> deptIds) {
        return kwsUserService.queryUserByDeptIds(deptIds);
    }

    /**
     * @param entId 企业id
     * @return KwsUser
     * @desc: 查管理员
     * @author: czh
     * @date: 2023/9/13
     */
    public KwsUser queryManageByEntId(Long entId) {
        FindManagePojo manageInfoByEntId = kwsEnterpriseDao.findManageInfoByEntId(entId);
        if (Objects.isNull(manageInfoByEntId)) {
            return null;
        }
        return kwsUserService.selectByKey(manageInfoByEntId.getUserId());
    }

    /**
     * @desc 查询专场集
     * @author zk
     * @date 2023/12/14
     **/
    public List<SpecialResVo> findSpecial() {
        List<KwsSpecial> specials = kwsSpecialService.findList(null);
        if (CollectionUtils.isNotEmpty(specials)) {
            return BeanUtils.copyToList(specials, SpecialResVo.class);
        }
        return new ArrayList<>();
    }

    /**
     * @param code 专场编号
     * @param type 企业类型
     * @desc 专场编号查询关联企业ID()
     * @author zk
     * @date 2023/12/16
     **/
    public List<Long> findEntIdsByCode(String code, String type) {
        return kwsSpecialService.findEntIdsByCode(code, type);
    }

    /**
     * @param code 专场编号
     * @desc 专场编号查询是否为主平台
     * @author zk
     * @date 2023/12/16
     **/
    public boolean queryMainPlatform(String code) {
        return kwsSpecialService.queryMainPlatform(code);
    }

    /**
     * @param entIds 企业id查询数据库企业信息
     * @desc 企业主键id查询数据库企业信息
     * @author zk
     * @date 2023/12/16
     **/
    public Map<Long, KwsEnterpriseResDto> queryEnterpriseByEntIds(List<Long> entIds) {
        List<KwsEnterprise> enterpriseList = kwsEnterpriseDao.queryEnterpriseByEntIds(entIds);
        List<KwsEnterpriseResDto> dtoList = new ArrayList<>();
        Map<Long, KwsEnterpriseResDto> map = new HashMap<>();
        if (enterpriseList.size() > 0) {
            enterpriseList.forEach(enterprise -> {
                KwsEnterpriseResDto dto = new KwsEnterpriseResDto();
                org.springframework.beans.BeanUtils.copyProperties(enterprise, dto);
                dtoList.add(dto);
            });
        }
        if (dtoList.size() > 0) {
            map = dtoList.stream().collect(Collectors.toMap(KwsEnterpriseResDto::getId, x -> x, (oldValue, newValue) -> newValue));
        }
        return map;
    }

    public KwsEnterpriseResDto findEnterpriseByName(String enterpriseName) {
        KwsEnterprise kwsEnterprise = kwsEnterpriseDao.findEnterpriseByName(enterpriseName);
        KwsEnterpriseResDto kwsEnterpriseResDto = new KwsEnterpriseResDto();
        BeanUtils.copyProperties(kwsEnterprise, kwsEnterpriseResDto);
        return kwsEnterpriseResDto;
    }

    public PageDataResult<KwsEnterpriseResDto> pageEnt(int pageNum, int pageSize, Long entId) {
        IPage<KwsEnterprise> kwsEnterprisePage = kwsEnterpriseReposiory.pageEnt(pageNum, pageSize, entId);
        List<KwsEnterprise> records = kwsEnterprisePage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageDataResult<>();
        }
        List<KwsEnterpriseResDto> enterpriseResDtoList = records.stream().map(RemoteBaseService::getKwsEnterpriseResDto).collect(Collectors.toList());
        return PageDataResult.of(kwsEnterprisePage, enterpriseResDtoList);
    }


    private static KwsEnterpriseResDto getKwsEnterpriseResDto(KwsEnterprise kwsEnterprise) {
        KwsEnterpriseResDto kwsEnterpriseResDto = new KwsEnterpriseResDto();
        kwsEnterpriseResDto.setId(kwsEnterprise.getId());
        kwsEnterpriseResDto.setRemark(kwsEnterprise.getRemark());
        kwsEnterpriseResDto.setStatus(kwsEnterprise.getStatus());
        kwsEnterpriseResDto.setCreateBy(kwsEnterprise.getCreateBy());
        kwsEnterpriseResDto.setCreateTime(kwsEnterprise.getCreateTime());
        kwsEnterpriseResDto.setUpdateBy(kwsEnterprise.getUpdateBy());
        kwsEnterpriseResDto.setUpdateTime(kwsEnterprise.getUpdateTime());
        kwsEnterpriseResDto.setDelFlag(kwsEnterprise.getDelFlag());
        kwsEnterpriseResDto.setCode(kwsEnterprise.getCode());
        kwsEnterpriseResDto.setFirmName(kwsEnterprise.getFirmName());
        kwsEnterpriseResDto.setContacts(kwsEnterprise.getContacts());
        kwsEnterpriseResDto.setPhone(kwsEnterprise.getPhone());
        kwsEnterpriseResDto.setLegalName(kwsEnterprise.getLegalName());
        kwsEnterpriseResDto.setLegalPhone(kwsEnterprise.getLegalPhone());
        kwsEnterpriseResDto.setHead(kwsEnterprise.getHead());
        kwsEnterpriseResDto.setIntegral(kwsEnterprise.getIntegral());
        kwsEnterpriseResDto.setBalance(kwsEnterprise.getBalance());
        kwsEnterpriseResDto.setExperience(kwsEnterprise.getExperience());
        kwsEnterpriseResDto.setMemberLevel(kwsEnterprise.getMemberLevel());
        kwsEnterpriseResDto.setRegTime(kwsEnterprise.getRegTime());
        kwsEnterpriseResDto.setRegSource(kwsEnterprise.getRegSource());
        kwsEnterpriseResDto.setOrgCode(kwsEnterprise.getOrgCode());
        kwsEnterpriseResDto.setCityCode(kwsEnterprise.getCityCode());
        kwsEnterpriseResDto.setCityName(kwsEnterprise.getCityName());
        kwsEnterpriseResDto.setDetailAddress(kwsEnterprise.getDetailAddress());
        kwsEnterpriseResDto.setLat(kwsEnterprise.getLat());
        kwsEnterpriseResDto.setLng(kwsEnterprise.getLng());
        kwsEnterpriseResDto.setApproval(kwsEnterprise.getApproval());
        kwsEnterpriseResDto.setApprovalTime(kwsEnterprise.getApprovalTime());
        kwsEnterpriseResDto.setManager(kwsEnterprise.getManager());
        kwsEnterpriseResDto.setBusiness(kwsEnterprise.getBusiness());

        return kwsEnterpriseResDto;
    }

    public List<KwsEnterpriseResDto> queryEntListByEntIds(List<Long> entIds) {
        List<KwsEnterprise> enterpriseList = kwsEnterpriseDao.queryEnterpriseByEntIds(entIds);
        List<KwsEnterpriseResDto> dtoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(enterpriseList)) {
            enterpriseList.forEach(enterprise -> {
                KwsEnterpriseResDto dto = new KwsEnterpriseResDto();
                org.springframework.beans.BeanUtils.copyProperties(enterprise, dto);
                dtoList.add(dto);
            });
        }
        return dtoList;
    }
}
