package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.dao.LineInfoDAO;
import com.cool.store.dao.QualificationsInfoDAO;
import com.cool.store.dao.RegionAreaConfigDao;
import com.cool.store.entity.*;
import com.cool.store.enums.*;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.HyOpenAreaInfoMapper;
import com.cool.store.mapper.JoinIntentionMapper;
import com.cool.store.mapper.LineAuditInfoMapper;
import com.cool.store.mapper.LineInfoMapper;
import com.cool.store.request.JoinIntentionRequest;
import com.cool.store.service.JoinIntentionService;
import com.cool.store.service.UserAuthMappingService;
import com.cool.store.utils.poi.StringUtils;
import com.cool.store.vo.PartnerBaseInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service
@Slf4j
public class JoinIntentionServiceImpl extends LineFlowService implements JoinIntentionService {

    @Resource
    JoinIntentionMapper joinIntentionMapper;

    @Resource
    QualificationsInfoDAO  qualificationsInfoDAO;

    @Resource
    LineInfoDAO lineInfoDAO;

    @Resource
    HyOpenAreaInfoMapper openAreaInfoMapper;


    @Resource
    LineAuditInfoMapper lineAuditInfoMapper;

    @Resource
    UserAuthMappingService userAuthMappingService;

    @Resource
    RegionAreaConfigDao regionAreaConfigDao;

    @Resource
    LineInfoMapper lineInfoMapper;

    @Resource
    CommonService commonService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submit(JoinIntentionRequest request) {
        log.info("submit request ：{}", JSONObject.toJSONString(request));
        if (Objects.isNull(request)) {
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        LineInfoDO lineInfoDO = lineInfoMapper.getByLineId(request.getLineId());
        log.info("lineInfoDO : {}", JSONObject.toJSONString(lineInfoDO));
        if (!Objects.isNull(lineInfoDO) && (WorkflowSubStageEnum.INTEND.getCode()<lineInfoDO.getWorkflowSubStage())) {
            throw new ServiceException(ErrorCodeEnum.INTENT_PASS);
        }
        //更改线索流程子状态为【待审核】
        LineInfoDO lineInfoParam = request.toLineInfoDO();
        lineInfoParam.setWorkflowStage(WorkflowStageEnum.INTENT.getCode());
        lineInfoParam.setWorkflowSubStage(WorkflowSubStageEnum.INTEND.getCode());
        lineInfoParam.setWorkflowSubStageStatus(WorkflowSubStageStatusEnum.INTENT_5.getCode());
        if ((Objects.nonNull(request.getAreaCode()) && Objects.nonNull(lineInfoDO) && StringUtils.isBlank(lineInfoDO.getInvestmentManager())) || (Objects.isNull(lineInfoDO))) {
            EnterpriseUserDO userByRoleNameAndAreaId = userAuthMappingService.getUserByRoleEnumAndWantShopAreaId(UserRoleEnum.SUPERVISION, Long.valueOf(request.getAreaCode()));
            lineInfoParam.setInvestmentManager(userByRoleNameAndAreaId.getUserId());
        }
        lineInfoParam.setLineStatus(1);
        //强加盟 前期不确定意向区域
        if (lineInfoParam.getWantShopAreaId() != null&&lineInfoDO.getJoinMode()==1) {
            Long regionId = regionAreaConfigDao.getByWantShopAreaId(lineInfoParam.getWantShopAreaId());
            lineInfoParam.setRegionId(regionId);
        }
        lineInfoDAO.insertOrUpdate(lineInfoParam);
        QualificationsInfoDO qualificationsInfoDO = request.toQualificationsInfoDO();
        qualificationsInfoDAO.insertOrUpdate(qualificationsInfoDO);

        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("partnerUsername", lineInfoParam.getUsername());
        requestMap.put("partnerMobile", lineInfoParam.getMobile());
        requestMap.put("lineId", String.valueOf(lineInfoParam.getId()));
        HyOpenAreaInfoDO openAreaInfoDO = openAreaInfoMapper.selectById(lineInfoParam.getWantShopAreaId());
        requestMap.put("regionName", openAreaInfoDO.getAreaName());
        //工作通知后面对接企业微信
//        commonService.sendMessage(Collections.singletonList(lineInfoParam.getInvestmentManager()),
//                MessageEnum.MESSAGE_29,
//                requestMap);
        return Boolean.TRUE;
    }

    @Override
    protected Boolean auditPass(Long auditId, LineInfoDO lineInfo, String userId) {
        WorkflowSubStageEnum workflowSubStageEnum = WorkflowSubStageEnum.getWorkflowSubStageEnum(lineInfo.getWorkflowSubStage());
        WorkflowSubStageEnum nextStage = workflowSubStageEnum.getNextStage();
        lineInfoDAO.updateLineInfo(lineInfo);
        //更新线索阶段
        lineInfoDAO.updateWorkflowStage(lineInfo.getId(), nextStage, nextStage.getInitStatus(), userId);
        //更新加盟问卷信息
        qualificationsInfoDAO.updateAuditIdByLineId(auditId, lineInfo.getId());
        return Boolean.TRUE;
    }

    @Override
    protected Boolean auditReject(Long auditId, LineInfoDO lineInfo, String userId) {
        lineInfo.setWorkflowSubStageStatus(WorkflowSubStageStatusEnum.INTENT_7.getCode());
        lineInfo.setUpdateUserId(userId);
        lineInfoDAO.updateLineInfo(lineInfo);
        //更新加盟问卷信息
        qualificationsInfoDAO.updateAuditIdByLineId(auditId, lineInfo.getId());
        return Boolean.TRUE;
    }

    @Override
    public PartnerBaseInfoVO getByLineId(Long lineId) {
        LineInfoDO byLineId = lineInfoDAO.getLineInfo(lineId);
        QualificationsInfoDO result = qualificationsInfoDAO.getByLineId(lineId);

        if (Objects.isNull(byLineId)) {
            throw new ServiceException(ErrorCodeEnum.LINE_ID_IS_NOT_EXIST);
        }
        if (Objects.isNull(result)) {
            return new PartnerBaseInfoVO();
        }
        PartnerBaseInfoVO response = PartnerBaseInfoVO.from(result, byLineId);
        HyOpenAreaInfoDO openAreaInfoDO = openAreaInfoMapper.selectById(Long.valueOf(response.getAreaCode()));
        response.setArea(openAreaInfoDO.getAreaPath());
        if (Objects.nonNull(result.getAuditId())) {
            LineAuditInfoDO lineAuditInfoDO = lineAuditInfoMapper.selectByPrimaryKey(result.getAuditId());
            if (Objects.isNull(lineAuditInfoDO)) {
                response.setRejectPublicReason(null);
            }
            response.setRejectPublicReason(lineAuditInfoDO.getRejectPublicReason());
        }
        response.setBigRegionId(byLineId.getBigRegionId());
        return response;
    }
}
