package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.dao.*;
import com.cool.store.dao.order.StoreWishlistDAO;
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.GetPasswordDTO;
import com.cool.store.request.JoinIntentionRequest;
import com.cool.store.service.JoinIntentionService;
import com.cool.store.service.ThirdXinGuanJiaService;
import com.cool.store.service.UserAuthMappingService;
import com.cool.store.utils.PasswordUtil;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.utils.poi.StringUtils;
import com.cool.store.vo.PartnerBaseInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;


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

    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    JoinIntentionMapper joinIntentionMapper;
    @Resource
    ThirdXinGuanJiaService thirdXinGuanJiaService;
    @Resource
    QualificationsInfoDAO qualificationsInfoDAO;

    @Resource
    LineInfoDAO lineInfoDAO;

    @Resource
    HyOpenAreaInfoMapper openAreaInfoMapper;


    @Resource
    LineAuditInfoMapper lineAuditInfoMapper;

    @Resource
    UserAuthMappingService userAuthMappingService;

    @Resource
    RegionAreaConfigDao regionAreaConfigDao;

    @Resource
    LineInfoMapper lineInfoMapper;

    @Resource
    CommonService commonService;
    @Resource
    HyPartnerUserInfoDAO hyPartnerUserInfoDAO;
    @Resource
    StoreWishlistDAO wishlistDAO;


    @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 (StringUtils.isBlank(lineInfoParam.getInvestmentManager()) &&StringUtils.isBlank(lineInfoDO.getInvestmentManager())) {
            lineInfoParam.setFranchiseBrand(String.valueOf(FranchiseBrandEnum.ZXJP.getCode()));
            lineInfoParam.setLineStatus(0);
        }else{
            lineInfoParam.setFranchiseBrand(String.valueOf(FranchiseBrandEnum.ZXJP.getCode()));
            lineInfoParam.setLineStatus(1);
        }
        lineInfoParam.setUseStandardStore(request.getUseStandardStore());
        lineInfoDAO.insertOrUpdate(lineInfoParam);
        QualificationsInfoDO qualificationsInfoDO = request.toQualificationsInfoDO();
        qualificationsInfoDAO.insertOrUpdate(qualificationsInfoDO);
        LineInfoDO lineInfoDO1 = lineInfoDAO.getLineInfo(request.getLineId());
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("partnerUsername", lineInfoDO1.getUsername());
        requestMap.put("partnerMobile", lineInfoDO1.getMobile());
        commonService.sendQWMessage(Collections.singletonList(lineInfoDO1.getInvestmentManager()),
                MessageEnum.MESSAGE_1,
                requestMap);
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean auditPass(Long auditId, LineInfoDO lineInfo, String userId) {
        WorkflowSubStageEnum workflowSubStageEnum = WorkflowSubStageEnum.getWorkflowSubStageEnum(lineInfo.getWorkflowSubStage());
        WorkflowSubStageEnum nextStage = null;
        WorkflowSubStageStatusEnum nextStageStatus = null;
        Integer workflowSubStageStatus = lineInfo.getWorkflowSubStageStatus();
        Boolean flag = false;
        if (WorkflowSubStageStatusEnum.INTENT_5.getCode().equals(workflowSubStageStatus)){
            //如果状态为待加盟商审核 则下一阶段不变
            nextStage = WorkflowSubStageEnum.getWorkflowSubStageEnum(lineInfo.getWorkflowSubStage());
            nextStageStatus = WorkflowSubStageStatusEnum.INTENT_6;
        }else {
            //如果状态为待大区总审核
            nextStage = workflowSubStageEnum.getNextStage();
            nextStageStatus = nextStage.getInitStatus();
            flag = Boolean.TRUE;
        }
        //更新线索阶段
        lineInfoDAO.updateWorkflowStage(lineInfo.getId(), nextStage, nextStageStatus, userId,flag);
        //更新加盟问卷信息
        qualificationsInfoDAO.updateAuditIdByLineId(auditId, lineInfo.getId());
        if ( flag ){
            QualificationsInfoDO qualificationsInfoDO = qualificationsInfoDAO.getByLineId(lineInfo.getId());
            if (StringUtils.isBlank(qualificationsInfoDO.getIdCardNo()) || qualificationsInfoDO.getIdCardNo().length() < 6) {
                throw new ServiceException(ErrorCodeEnum.CREATE_PASSWORD_FAIL);
            }
            String substring = qualificationsInfoDO.getIdCardNo().substring(qualificationsInfoDO.getIdCardNo().length() - 6);
            //生成密码和盐值
            byte[] saltBytes = PasswordUtil.generateSalt();
            String salt = PasswordUtil.bytesToHex(saltBytes);
            String password = PasswordUtil.encryptPassword(substring, salt);
            GetPasswordDTO getPasswordDTO = new GetPasswordDTO();
            getPasswordDTO.setPassword(substring);
            String downstreamSystemSecondaryPassword = thirdXinGuanJiaService.getPassword(getPasswordDTO);
            HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(lineInfo.getPartnerId());
            hyPartnerUserInfoDO.setDownstreamSystemPassword(password);
            hyPartnerUserInfoDO.setDownstreamSystemSecondaryPassword(downstreamSystemSecondaryPassword);
            hyPartnerUserInfoDO.setDownstreamSystemSalting(salt);
            hyPartnerUserInfoDO.setUpdateTime(new Date());
            hyPartnerUserInfoDAO.updatePasswordByPartnerId(hyPartnerUserInfoDO);
            log.info("auditPass:大区老总审核通过");
            wishlistDAO.updateByLineId(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);
        }
        PartnerBaseInfoVO response = new PartnerBaseInfoVO();
        response.setSupervisorId(byLineId.getInvestmentManager());
        EnterpriseUserDO enterpriseUserDO = enterpriseUserDAO.getUserInfoById(byLineId.getInvestmentManager());
        if (Objects.nonNull(enterpriseUserDO)) {
            response.setSupervisorName(enterpriseUserDO.getName());
            response.setSupervisorMobile(enterpriseUserDO.getMobile());
        }
        if (Objects.isNull(result)) {
            return response;
        }
        response = PartnerBaseInfoVO.from(result, byLineId);
        if (response != null) {
            response.setSupervisorId(byLineId.getInvestmentManager());
            if (Objects.nonNull(enterpriseUserDO)) {
                response.setSupervisorName(enterpriseUserDO.getName());
                response.setSupervisorMobile(enterpriseUserDO.getMobile());
            }
        }

        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;
    }

}
