package com.gic.haoban.manage.service.service.out.impl.hm;

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.haoban.base.api.common.errCode.HaoBanErrCodeCommon;
import com.gic.haoban.common.utils.PageUtil;
import com.gic.haoban.manage.api.dto.hm.HmPageDTO;
import com.gic.haoban.manage.api.dto.hm.HmPageRelationDTO;
import com.gic.haoban.manage.api.dto.qdto.hm.HmPageQDTO;
import com.gic.haoban.manage.api.dto.qdto.hm.HmPageRelationQDTO;
import com.gic.haoban.manage.api.enums.hm.HmPageStatus;
import com.gic.haoban.manage.api.service.hm.HmPageApiService;
import com.gic.haoban.manage.service.pojo.bo.hm.HmLinkBO;
import com.gic.haoban.manage.service.pojo.bo.hm.HmPageBO;
import com.gic.haoban.manage.service.pojo.qo.HmPageTemplateQO;
import com.gic.haoban.manage.service.service.hm.HmLinkService;
import com.gic.haoban.manage.service.service.hm.HmPageService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author MUSI
 * @Date 2022/7/3 8:22 PM
 * @Description
 * @Version
 **/
@Component(value = "hmPageTemplateApiServiceImpl")
public class HmPageApiServiceImpl implements HmPageApiService {

    private static final Logger log = LoggerFactory.getLogger(HmPageApiServiceImpl.class);

    @Autowired
    private HmPageService haobanHmPageService;

    @Autowired
    private HmLinkService linkService;

    @Override
    public ServiceResponse<Long> saveOrUpdateHmPage(HmPageDTO pageDTO) {

        if (Objects.nonNull(pageDTO.getPageId())) {
            // update
            HmPageBO pageDetail = haobanHmPageService.queryHmPageDetail(pageDTO.getPageId());
            if (Objects.isNull(pageDetail)) {
                // 数据不存在
                return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_8.getCode() + "", HaoBanErrCodeCommon.ERR_8.getMsg());
            }
            if (!StringUtils.equals(pageDetail.getEnterpriseId(), pageDTO.getEnterpriseId())) {
                // 无权限
                return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_9.getCode() + "", HaoBanErrCodeCommon.ERR_9.getMsg());
            }
            if (!StringUtils.equals(pageDetail.getWxEnterpriseId(), pageDTO.getWxEnterpriseId())) {
                // 无权限
                return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_9.getCode() + "", HaoBanErrCodeCommon.ERR_9.getMsg());
            }
        }
        return ServiceResponse.success(haobanHmPageService.saveOrUpdateHmPage(pageDTO));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ServiceResponse<Boolean> deleteHmPage(HmPageDTO pageDTO) {
        log.info("[deleteHmPage] 删除落地页模板, params:{}", JSON.toJSONString(pageDTO));
        HmPageBO pageBo = haobanHmPageService.queryHmPageDetail(pageDTO.getPageId());
        if (Objects.isNull(pageBo) || !Objects.equals(HmPageStatus.ENABLE.getCode(), pageBo.getStatus())) {
            return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_8.getCode() + "", HaoBanErrCodeCommon.ERR_8.getMsg());
        }
        if (this.checkPageIsBeQuoted(pageBo.getPageId(), pageBo.getEnterpriseId()) > 0) {
            return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_9.getCode() + "", HaoBanErrCodeCommon.ERR_9.getMsg());
        }
        haobanHmPageService.deleteHmPage(pageDTO);
        return ServiceResponse.success(Boolean.TRUE);
    }

    @Override
    public ServiceResponse<Page<HmPageDTO>> queryPageList(HmPageQDTO pageQueryDTO) {
        HmPageTemplateQO pageTemplateQo = new HmPageTemplateQO();
        BeanUtils.copyProperties(pageQueryDTO, pageTemplateQo);
        pageTemplateQo.setStatus(HmPageStatus.ENABLE.getCode());
        Page<HmPageBO> hmPageBoPages = haobanHmPageService.queryPageList(pageTemplateQo);
        Page<HmPageDTO> pageRespVos = PageUtil.changeToCurrentPage(hmPageBoPages, HmPageDTO.class);
        return ServiceResponse.success(pageRespVos);
    }

    /**
     * 校验落地页模板pageTemplateCode 是否被关联
     *
     * @param pageId
     * @return true 存在关联
     * false 不存在关联关系
     */
    private Integer checkPageIsBeQuoted(Long pageId, String enterpriseId) {
        BasePageInfo pageInfo = new BasePageInfo();
        pageInfo.setPageSize(1);
        Page<HmLinkBO> linkBOPage = linkService.queryPageRelationList(pageId, enterpriseId, null, pageInfo);
        return linkBOPage.getTotalCount();
    }

    /**
     * 条件查询落地页关联详情
     *
     * @param relationQueryDTO
     * @return
     */
    @Override
    public ServiceResponse<Page<HmPageRelationDTO>> queryPageRelation(HmPageRelationQDTO relationQueryDTO) {
        BasePageInfo pageInfo = new BasePageInfo();
        pageInfo.setPageNum(relationQueryDTO.getPageNum());
        pageInfo.setPageSize(relationQueryDTO.getPageSize());
        Page<HmLinkBO> hmLinkBOPage = linkService.queryPageRelationList(relationQueryDTO.getPageId(), relationQueryDTO.getEnterpriseId(), relationQueryDTO.getSearchText(), pageInfo);
        if (CollectionUtils.isEmpty(hmLinkBOPage.getResult())) {
            Page<HmPageRelationDTO> empty = new Page<>();
            empty.setResult(Collections.emptyList());
            return ServiceResponse.success(empty);
        }
        Page<HmPageRelationDTO> pageRelationDTOPage = PageUtil.changeToCurrentPage(hmLinkBOPage, HmPageRelationDTO.class);
        List<HmPageRelationDTO> pageRelations = hmLinkBOPage.getResult().stream()
                .map(item -> {
                    HmPageRelationDTO pageRelation = new HmPageRelationDTO();
                    pageRelation.setReferName(item.getName());
                    pageRelation.setReferId(item.getLinkId() + "");
                    pageRelation.setReleationId(item.getLinkCode());
                    return pageRelation;
                }).collect(Collectors.toList());
        pageRelationDTOPage.setResult(pageRelations);
        return ServiceResponse.success(pageRelationDTOPage);
    }

    /**
     * 根据页面id 查询
     *
     * @param pageId
     * @return
     */
    @Override
    public ServiceResponse<HmPageDTO> queryPageDetail(Long pageId) {
        HmPageBO pageBO = haobanHmPageService.queryHmPageDetail(pageId);
        if (pageBO == null) {
            return ServiceResponse.success();
        }
        HmPageDTO hmPageDTO = new HmPageDTO();
        BeanUtils.copyProperties(pageBO, hmPageDTO);
        return ServiceResponse.success(hmPageDTO);
    }
}
