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

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.haoban.base.api.common.errCode.HaoBanErrCodeCommon;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.common.utils.PageUtil;
import com.gic.haoban.manage.api.dto.hm.HmGroupDTO;
import com.gic.haoban.manage.api.dto.hm.HmGroupQueryDTO;
import com.gic.haoban.manage.api.dto.qdto.hm.HmQrcodeListQDTO;
import com.gic.haoban.manage.api.enums.hm.HmGroupStatus;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.service.hm.HmGroupApiService;
import com.gic.haoban.manage.service.errorcode.HaoBanErrCode;
import com.gic.haoban.manage.service.pojo.bo.hm.HmGroupSettingBO;
import com.gic.haoban.manage.service.pojo.bo.hm.HmQrcodeGroupNumBO;
import com.gic.haoban.manage.service.pojo.qo.HmGroupInfoQO;
import com.gic.haoban.manage.service.service.hm.HmGroupService;
import com.gic.haoban.manage.service.service.hm.HmQrcodeService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
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 java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author MUSI
 * @Date 2022/7/1 4:02 PM
 * @Description
 * @Version
 **/
@Component
public class HmGroupApiServiceImpl implements HmGroupApiService {

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

    private static final Long DEFAULT_GROUP_ID = NumberUtils.LONG_ZERO;
    private static final String DEFAULT_GROUP_NAME = "默认分组";

    @Autowired
    private HmGroupService groupService;

    @Autowired
    private HmQrcodeService qrcodeService;

    @Autowired
    private StaffApiService staffApiService;

    @Override
    public ServiceResponse<Long> saveOrUpdateHmGroupSetting(HmGroupDTO hmGroupDTO) {
        log.info("[saveOrUpdateHmGroupSetting] params:{}", JSON.toJSONString(hmGroupDTO));
        if (StringUtils.isBlank(hmGroupDTO.getGroupName())) {
            return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_5.getCode() + "", "分组名称不存在");
        }
        if (StringUtils.equals(DEFAULT_GROUP_NAME, hmGroupDTO.getGroupName())) {
            return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_9.getCode() + "", "分组名称不能重复");
        }
        List<HmGroupSettingBO> groupSettingBos = groupService.queryGroupSettingByName(hmGroupDTO.getWxEnterpriseId(), hmGroupDTO.getEnterpriseId(), hmGroupDTO.getGroupName());
        if (hmGroupDTO.getGroupId() == null) {
            // insert
            // check groupName unique
            if (CollectionUtils.isNotEmpty(groupSettingBos)) {
                return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_5.getCode() + "", "分组名称不能重复");
            }
        } else {
            // update
            if (CollectionUtils.isNotEmpty(groupSettingBos)
                    && groupSettingBos.size() > 1) {
                // 名称重复
                return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_5.getCode() + "", "分组名称不能重复");
            }
            if (CollectionUtils.isNotEmpty(groupSettingBos)
                    && !groupSettingBos.get(0).getGroupId().equals(hmGroupDTO.getGroupId())) {
                // 名称重复
                return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_5.getCode() + "", "分组名称不能重复");
            }
            HmGroupSettingBO groupSettingBo = groupService.queryGroupSettingDetail(hmGroupDTO.getGroupId());
            if (groupSettingBo == null) {
                return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_8.getCode() + "", HaoBanErrCodeCommon.ERR_8.getMsg());
            }
            if (!StringUtils.equals(groupSettingBo.getEnterpriseId(), hmGroupDTO.getEnterpriseId())) {
                // 无权限
                return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_9.getCode() + "", HaoBanErrCodeCommon.ERR_9.getMsg());
            }
        }
        Long groupId = groupService.saveOrUpdateGroupSetting(hmGroupDTO);
        return ServiceResponse.success(groupId);
    }

    @Override
    public ServiceResponse<Page<HmGroupDTO>> queryHmGroupSettingList(HmGroupQueryDTO groupQueryDTO) {

        HmGroupInfoQO groupInfoQo = new HmGroupInfoQO();
        BeanUtils.copyProperties(groupQueryDTO, groupInfoQo);
        groupInfoQo.setStatus(HmGroupStatus.ENABLE.getCode());
        Page<HmGroupSettingBO> groupSettingPage = groupService.queryGroupSettingList(groupInfoQo);

        Page<HmGroupDTO> groupDtoPage = PageUtil.changeToCurrentPage(groupSettingPage, HmGroupDTO.class);
        List<HmGroupDTO> result = new ArrayList<>();
        if (groupQueryDTO.getPageNum() == 1
                && (StringUtils.isBlank(groupQueryDTO.getGroupName()) || DEFAULT_GROUP_NAME.contains(groupQueryDTO.getGroupName()))) {
            // 仅第一页展示默认分组选项
            result.add(buildDefault(0));
        }
        result.addAll(groupDtoPage.getResult());
        List<Long> groupIds = result.stream().map(HmGroupDTO::getGroupId).collect(Collectors.toList());
        Map<Long, Integer> qrcodeGroupNumMap = Collections.emptyMap();
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(groupQueryDTO.getClerkId(), groupQueryDTO.getWxEnterpriseId());
        log.info("导购拥有的门店权限 clerkId:{}, storeIds:{}", groupQueryDTO.getClerkId(), JSON.toJSONString(storeList));
        if (!CollectionUtils.isEmpty(storeList)) {
            List<String> hmIds = null;
            boolean isStatic = Boolean.TRUE;
            if (!storeList.contains("-1")) {
                // 非超关权限
                HmQrcodeListQDTO hmQrcodeListQdto = new HmQrcodeListQDTO();
                hmQrcodeListQdto.setEnterpriseId(groupQueryDTO.getEnterpriseId());
                hmQrcodeListQdto.setStoreId(storeList);
                hmQrcodeListQdto.setWxEnterpriseId(groupQueryDTO.getWxEnterpriseId());
                hmIds = qrcodeService.listHmIdForIndex(hmQrcodeListQdto);
                log.info("HMid列表={}", JSON.toJSONString(hmIds));
                if (CollectionUtils.isEmpty(hmIds)){
                    isStatic = false;
                }
            }
            if (isStatic) {
                List<HmQrcodeGroupNumBO> qrcodeGroupNumBoList = qrcodeService.getGroupIdNumByEnterpriseId(groupQueryDTO.getWxEnterpriseId(), groupQueryDTO.getEnterpriseId(), groupIds, hmIds);
                if (CollectionUtils.isNotEmpty(qrcodeGroupNumBoList)) {
                    qrcodeGroupNumMap = qrcodeGroupNumBoList.stream()
                            .collect(Collectors.toMap(HmQrcodeGroupNumBO::getHmGroupId, HmQrcodeGroupNumBO::getNum, (v1, v2) -> v1));
                }
            }
        }
        for (HmGroupDTO groupDTO : result) {
            Integer referNum = Optional.ofNullable(qrcodeGroupNumMap.get(groupDTO.getGroupId())).orElse(0);
            groupDTO.setReferNum(referNum);
            if (!DEFAULT_GROUP_ID.equals(groupDTO.getGroupId())) {
                groupDTO.setDefaultFlag(0);
            }
        }
        groupDtoPage.setResult(result);
        return ServiceResponse.success(groupDtoPage);
    }

    private HmGroupDTO buildDefault(Integer num) {
        HmGroupDTO groupSettingDTO = new HmGroupDTO();
        groupSettingDTO.setGroupId(DEFAULT_GROUP_ID);
        groupSettingDTO.setGroupName(DEFAULT_GROUP_NAME);
        groupSettingDTO.setDefaultFlag(1);
        groupSettingDTO.setReferNum(num);
        return groupSettingDTO;
    }

    @Override
    public ServiceResponse<Boolean> deleteGroupSetting(HmGroupDTO groupDTO) {
        log.info("[deleteGroupSetting] 删除分组, params:{}", JSON.toJSONString(groupDTO));
        if (groupDTO.getGroupId() == null) {
            return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_2.getCode() + "", HaoBanErrCodeCommon.ERR_2.getMsg());
        }
        if (DEFAULT_GROUP_ID.equals(groupDTO.getGroupId())) {
            return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_5.getCode() + "", HaoBanErrCodeCommon.ERR_5.getMsg());
        }
        HmGroupSettingBO groupSettingBo = groupService.queryGroupSettingDetail(groupDTO.getGroupId());
        if (groupSettingBo == null
                || !HmGroupStatus.ENABLE.getCode().equals(groupSettingBo.getStatus())) {
            return ServiceResponse.failure(HaoBanErrCodeCommon.ERR_8.getCode() + "", HaoBanErrCodeCommon.ERR_8.getMsg());
        }
        if (groupSettingBo.getReferNum() != null && groupSettingBo.getReferNum() > 0) {
            return ServiceResponse.failure(HaoBanErrCode.ERR_100033.getCode(), HaoBanErrCode.ERR_100033.getMsg());
        }
        
        List<HmQrcodeGroupNumBO> qrcodeGroupNumBoList = qrcodeService.getGroupIdNumByEnterpriseId(groupSettingBo.getWxEnterpriseId(), groupSettingBo.getEnterpriseId(), Arrays.asList(groupDTO.getGroupId()), null);
        if (CollectionUtils.isNotEmpty(qrcodeGroupNumBoList)) {
            if(qrcodeGroupNumBoList.get(0).getNum() > 0) {
                return ServiceResponse.failure(HaoBanErrCode.ERR_100034.getCode(), HaoBanErrCode.ERR_100034.getMsg());
            }
        }
        groupService.deleteGroupSetting(groupDTO);
        return ServiceResponse.success(Boolean.TRUE);
    }

    /**
     * 分组总引用次数
     *
     * @param enterpriseId
     * @param wxEnterpriseId
     * @return
     */
    @Override
    public ServiceResponse<Integer> queryGroupTotalReferCount(String clerkId, String enterpriseId, String wxEnterpriseId) {
        List<String> storeList = staffApiService.getHaoBanStoreIdsRolesByClerkId(clerkId, wxEnterpriseId);
        log.info("导购拥有的门店权限 clerkId:{}, storeIds:{}", clerkId, JSON.toJSONString(storeList));
        List<String> hmIds = null;
        if (!CollectionUtils.isEmpty(storeList)) {
            if (!storeList.contains("-1")) {
                HmQrcodeListQDTO hmQrcodeListQDTO = new HmQrcodeListQDTO();
                hmQrcodeListQDTO.setEnterpriseId(enterpriseId);
                hmQrcodeListQDTO.setStoreId(storeList);
                hmQrcodeListQDTO.setWxEnterpriseId(wxEnterpriseId);
                hmIds = qrcodeService.listHmIdForIndex(hmQrcodeListQDTO);
                log.info("导购拥有的活码权限列表:{}", JSON.toJSONString(hmIds));
                if (CollectionUtils.isEmpty(hmIds)){
                    return ServiceResponse.success(0);
                }
            }
        }
        int totalReferCount = qrcodeService.getTotalByEnterpriseId(wxEnterpriseId, enterpriseId, hmIds);
        return ServiceResponse.success(totalReferCount);
    }

    /**
     * 查询单个分组信息
     *
     * @param groupId
     * @return
     */
    @Override
    public ServiceResponse<HmGroupDTO> queryGroupDetail(Long groupId) {
        HmGroupSettingBO groupSettingBO = groupService.queryGroupSettingDetail(groupId);
        if (Objects.equals(DEFAULT_GROUP_ID, groupId)){
            HmGroupDTO defaultGroupDTO = new HmGroupDTO();
            defaultGroupDTO.setGroupId(DEFAULT_GROUP_ID);
            defaultGroupDTO.setGroupName(DEFAULT_GROUP_NAME);
            return ServiceResponse.success(defaultGroupDTO);
        }
        HmGroupDTO groupDTO = EntityUtil.changeEntityByOrika(HmGroupDTO.class, groupSettingBO);
        return ServiceResponse.success(groupDTO);
    }

    /**
     * 根据名称查询groupName
     *
     * @param groupName
     * @return
     */
    @Override
    public ServiceResponse<List<HmGroupDTO>> queryGroupListByName(String wxEnterpriseId, String enterpriseId, String groupName) {
        List<HmGroupSettingBO> hmGroupSettingBos = groupService.queryGroupSettingByName(wxEnterpriseId, enterpriseId, groupName);
        return ServiceResponse.success(EntityUtil.changeEntityListByOrika(HmGroupDTO.class, hmGroupSettingBos));
    }
}
