package io.renren.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dao.ChannelsDao;
import io.renren.modules.sys.dao.LandingPagesDao;
import io.renren.modules.sys.dao.OperationsDao;
import io.renren.modules.sys.dao.RdAdvertiserDao;
import io.renren.modules.sys.dao.SysDictDataDao;
import io.renren.modules.sys.dto.LandingPagesDTO;
import io.renren.modules.sys.entity.ChannelsEntity;
import io.renren.modules.sys.entity.CompaniesEntity;
import io.renren.modules.sys.entity.LandingPagesEntity;
import io.renren.modules.sys.entity.OperationsEntity;
import io.renren.modules.sys.entity.RdAdvertiserEntity;
import io.renren.modules.sys.enums.SuperAdminEnum;
import io.renren.modules.sys.service.CompaniesService;
import io.renren.modules.sys.service.LandingPagesService;

/**
 * 落地页
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2022-05-28
 */
@Service
public class LandingPagesServiceImpl extends CrudServiceImpl<LandingPagesDao, LandingPagesEntity, LandingPagesDTO> implements LandingPagesService {
    @Autowired
    private ChannelsDao channelsDao;
    @Autowired
    private OperationsDao operationsDao;
    @Autowired
    private RdAdvertiserDao rdAdvertiserDao;
    @Autowired
    private SysDictDataDao sysDictDataDao;
    @Autowired
    private CompaniesService companiesService;
    
    @Override
    public QueryWrapper<LandingPagesEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String advertiserId = (String)params.get("advertiserId");
        String channelId = (String)params.get("channelId");
        String operationId = (String)params.get("operationId");
        String companyId = (String)params.get("companyId");
        String name = (String)params.get("name");
        String url = (String)params.get("url");

        QueryWrapper<LandingPagesEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id).eq("status",1)
                .apply(StringUtils.isNotBlank(companyId), "FIND_IN_SET ('" + companyId + "',company_ids)")
                .eq(StringUtils.isNotBlank(advertiserId), "advertiser_id", advertiserId)
                .eq(StringUtils.isNotBlank(channelId), "channel_id", channelId)
                .eq(StringUtils.isNotBlank(operationId), "operation_id", operationId)
                .eq(StringUtils.isNotBlank(name), "name", name)
                .eq(StringUtils.isNotBlank(url), "url", url)
                .orderByDesc("id");

        return wrapper;
    }

    @Override
    public PageData<LandingPagesDTO> page(Map<String, Object> params) {
        IPage<LandingPagesEntity> page = baseDao.selectPage(
                getPage(params, null, false),
                getWrapper(params)
        );
        List<LandingPagesDTO> landingPagesDTOList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(page.getRecords())){
            Map<String, CompaniesEntity> companyMap = new HashMap<>();
            LandingPagesDTO landingPagesDTO = null;
            for (LandingPagesEntity landingPagesEntity:page.getRecords()){
                landingPagesDTO = new LandingPagesDTO();
                BeanUtils.copyProperties(landingPagesEntity,landingPagesDTO);
                if(StringUtils.isNotEmpty(landingPagesEntity.getCompanyIds())){
                    String[] cpmpanyIdArr = landingPagesEntity.getCompanyIds().split(",");
                    if (cpmpanyIdArr!=null && cpmpanyIdArr.length>0){
                        List<String> companyNames = new ArrayList<>();
                        for (String companyId:cpmpanyIdArr){
                            CompaniesEntity companiesEntity = null;
                            if (companyMap.containsKey(companyId)){
                                companiesEntity = companyMap.get(companyId);
                                companyNames.add(companiesEntity.getName());
                            }else{
                                companiesEntity = companiesService.selectById(companyId);
                                if (companiesEntity!=null && companiesEntity.getStatus()==1) {
                                    companyNames.add(companiesEntity.getName());
                                    companyMap.put(companyId,companiesEntity);
                                }
                            }
                        }
                        landingPagesDTO.setCompanyNames(companyNames);
                        landingPagesDTO.setCompanyIds(cpmpanyIdArr);
                    }
                }
                if(landingPagesEntity.getChannelId()!=null){
                    ChannelsEntity channelsEntity = channelsDao.selectById(landingPagesEntity.getChannelId());
                    if (channelsEntity!=null && channelsEntity.getStatus()==1) {
                        landingPagesDTO.setChannelName(channelsEntity.getName());
                    }
                }
                if(landingPagesEntity.getOperationId()!=null){
                    OperationsEntity operationsEntity = operationsDao.selectById(landingPagesEntity.getOperationId());
                    if (operationsEntity!=null && operationsEntity.getStatus()==1) {
                        landingPagesDTO.setOperationName(operationsEntity.getName());
                    }
                }
                if(StringUtils.isNotEmpty(landingPagesEntity.getAdvertiserId())){
                    RdAdvertiserEntity rdAdvertiserEntity = rdAdvertiserDao.selectOne(new QueryWrapper<RdAdvertiserEntity>().eq("status",1)
                        .eq("advertiser_id",landingPagesEntity.getAdvertiserId()).last("limit 1"));
                    if (rdAdvertiserEntity!=null) {
                        landingPagesDTO.setAdvertiserName(rdAdvertiserEntity.getAdvertiserName());
                    }
                }
                if(StringUtils.isNotEmpty(landingPagesEntity.getLoanType())){
                    String loanTypeLabel = sysDictDataDao.getDictDataByTypeAndDictValue("loan_type",landingPagesEntity.getLoanType());
                    landingPagesDTO.setLoanType(loanTypeLabel);
                }
                landingPagesDTOList.add(landingPagesDTO);
            }
        }
        return new PageData<>(landingPagesDTOList, page.getTotal());
    }

    @Override
    public LandingPagesDTO get(Long id) {
        LandingPagesEntity landingPagesEntity = baseDao.selectById(id);
        LandingPagesDTO landingPagesDTO = new LandingPagesDTO();
        BeanUtils.copyProperties(landingPagesEntity,landingPagesDTO);
        if(StringUtils.isNotEmpty(landingPagesEntity.getCompanyIds())){
            String[] cpmpanyIdArr = landingPagesEntity.getCompanyIds().split(",");
            landingPagesDTO.setCompanyIds(cpmpanyIdArr);
        }
        return landingPagesDTO;
    }

    @Override
    public void save(LandingPagesDTO dto) {
        LandingPagesEntity landingPagesEntity = new LandingPagesEntity();
        BeanUtils.copyProperties(dto,landingPagesEntity);
        if (dto.getCompanyIds()!=null || dto.getCompanyIds().length>0){
            String companyIds = "";
            for (String companyId:dto.getCompanyIds()){
                companyIds = companyIds + companyId + ",";
            }
            companyIds = companyIds.substring(0,companyIds.length()-1);
            landingPagesEntity.setCompanyIds(companyIds);
        }
        baseDao.insert(landingPagesEntity);
    }

    @Override
    public void update(LandingPagesDTO dto) {
        LandingPagesEntity landingPagesEntity = new LandingPagesEntity();
        BeanUtils.copyProperties(dto,landingPagesEntity);
        if (dto.getCompanyIds()!=null || dto.getCompanyIds().length>0){
            String companyIds = "";
            for (String companyId:dto.getCompanyIds()){
                companyIds = companyIds + companyId + ",";
            }
            companyIds = companyIds.substring(0,companyIds.length()-1);
            landingPagesEntity.setCompanyIds(companyIds);
        }
        baseDao.updateById(landingPagesEntity);
    }

	@Override
	public List<LandingPagesDTO> getPagesListByUser() {
		
		List<Long> companiesList = companiesService.getCompaniesListByUserLong();
		
		QueryWrapper<LandingPagesEntity> qw = new QueryWrapper<>();
        //qw.eq("status", Constant.Status.ENABLE.getValue());
        UserDetail user = SecurityUser.getUser();
        //如果不是超级管理员，则进行数据过滤
        if(SuperAdminEnum.NO.value() == user.getSuperAdmin()) {
        	qw.in("dept_id", user.getDeptIdList());
        }
		return ConvertUtils.sourceToTarget(baseDao.selectList(qw), currentDtoClass());
	}

	@Override
	public List<Long> getPagesListByUserLong() {
		List<Long> returnList = new ArrayList<>();
		List<LandingPagesDTO> list = getPagesListByUser();
		for (LandingPagesDTO dto : list) {
			returnList.add(dto.getId());
		}
		return null;
	}
}