package com.cool.store.mq.consumer.listener;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.cool.store.constants.CommonConstants;
import com.cool.store.dao.*;
import com.cool.store.dto.ehr.StaffBaseInfoDTO;
import com.cool.store.dto.ehr.SyncXfsgTrainingPersonInfoDTO;
import com.cool.store.entity.*;
import com.cool.store.enums.RocketMqTagEnum;
import com.cool.store.enums.UserRoleEnum;
import com.cool.store.service.XfsgEhrService;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.utils.poi.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 鲜丰门店下培训人员拉取
 * @author wxp
 * @since 2024/4/29
 */
@Slf4j
@Service
public class XfsgTrainingPersonSyncListener implements MessageListener {

    @Resource
    public XfsgEhrService xfsgEhrService;

    @Resource
    private ShopInfoDAO shopInfoDAO;

    @Resource
    private TempUserDetailDAO tempUserDetailDAO;

    @Autowired
    public RedisUtilPool redisUtilPool;

    @Autowired
    public StoreDao storeDao;

    @Autowired
    public RegionDao regionDao;

    @Autowired
    public EnterpriseUserDAO enterpriseUserDAO;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        String text = new String(message.getBody());
        if(StringUtils.isBlank(text)){
            log.info("消息体为空,tag:{},messageId:{}",message.getTag(),message.getMsgID());
            return Action.CommitMessage;
        }
        String lockKey = "XfsgTrainingPersonSyncListener:" + message.getMsgID();
        boolean lock = redisUtilPool.setNxExpire(lockKey, message.getMsgID(), CommonConstants.NORMAL_LOCK_TIMES);
        if(lock){
            try {
//                switch (RocketMqTagEnum.getByTag(message.getTag())){
//                    case SYNC_TRAINING_PERSON:
//                        syncXfsgTrainingPerson(text);
//                        break;
//                    case SYNC_TRAINING_SHOP_PERSON:
//                        syncXfsgTrainingShopPerson(text);
//                        break;
//                }
            }catch (Exception e){
                log.error("XfsgTrainingPersonSyncListener consume error",e);
                return Action.ReconsumeLater;
            }finally {
                redisUtilPool.delKey(lockKey);
            }
            log.info("消费成功,tag:{},messageId:{},reqBody={}",message.getTag(),message.getMsgID(),text);
            return Action.CommitMessage;
        }
        return Action.ReconsumeLater;
    }

    public void syncXfsgTrainingPerson(String text) {
        log.info("syncXfsgTrainingPerson, reqBody={}", text);
        SyncXfsgTrainingPersonInfoDTO request = JSONObject.parseObject(text, SyncXfsgTrainingPersonInfoDTO.class);
        if(StringUtils.isAnyBlank(request.getStoreNum(), request.getJobnumber(), request.getIdCard())){
            log.info("syncXfsgTrainingPerson参数缺失={}", text);
            return;
        }
        // 系统建店完成一定有门店编码？？？
        ShopInfoDO shopInfoDO = shopInfoDAO.selectByStoreNum(request.getStoreNum());
        if(shopInfoDO == null){
            log.info("门店编码对应的店铺信息不存在storeNum:{}", request.getStoreNum());
            return;
        }
        TempUserDetailDO checkTempUserDetailDO = tempUserDetailDAO.selectByIdCard(request.getIdCard());
        // 系统已建店,并且身份证号信息不存在
        if(checkTempUserDetailDO == null){
            StaffBaseInfoDTO staffBaseInfoDTO = xfsgEhrService.getUserInfoByCode(request.getJobnumber());
            log.info("培训人员主数据信息：staffBaseInfoDTO:{}", JSONObject.toJSONString(staffBaseInfoDTO));
            if(staffBaseInfoDTO != null){
//                TempUserDetailDO tempUserDetailDO = fillTempUserDetailDO(shopInfoDO, staffBaseInfoDTO);
//                tempUserDetailDAO.insertSelective(tempUserDetailDO);
            }
        }else if(checkTempUserDetailDO != null &&
                (checkTempUserDetailDO.getShopId() == 0L || checkTempUserDetailDO.getShopId() != shopInfoDO.getId())){
            // 已录入，但是没有店铺id
            checkTempUserDetailDO.setLineId(shopInfoDO.getLineId());
            checkTempUserDetailDO.setShopId(shopInfoDO.getId());
            checkTempUserDetailDO.setRegionId(shopInfoDO.getRegionId());
            tempUserDetailDAO.updateByPrimaryKeySelective(checkTempUserDetailDO);
        }else {
            log.info("培训人员身份证信息已存在idCard:{}", checkTempUserDetailDO.getIdCard());
            return;
        }

    }

    private TempUserDetailDO fillTempUserDetailDO(ShopInfoDO shopInfoDO, StaffBaseInfoDTO staffBaseInfoDTO) {
        TempUserDetailDO tempUserDetailDO = new TempUserDetailDO();
        tempUserDetailDO.setLineId(shopInfoDO.getLineId());
        tempUserDetailDO.setShopId(shopInfoDO.getId());
        tempUserDetailDO.setRegionId(shopInfoDO.getRegionId());
        tempUserDetailDO.setMobile(staffBaseInfoDTO.getPhone());
        tempUserDetailDO.setUsername(staffBaseInfoDTO.getName());
        tempUserDetailDO.setSex(staffBaseInfoDTO.getSex());
        if(StringUtils.isNotBlank(staffBaseInfoDTO.getAge())){
            tempUserDetailDO.setAge(Integer.valueOf(staffBaseInfoDTO.getAge()));
        }
        tempUserDetailDO.setIdCard(staffBaseInfoDTO.getIdCard());
        tempUserDetailDO.setStatus(1);
//        tempUserDetailDO.setEducational(fillEducational(staffBaseInfoDTO.getHighestDegree()));
        tempUserDetailDO.setRoleId(fillRoleId(staffBaseInfoDTO.getJobName()));
        tempUserDetailDO.setIdCardNegativeUrl(staffBaseInfoDTO.getEmblemPhoto());
        tempUserDetailDO.setIdCardPositiveUrl(staffBaseInfoDTO.getIdNumPhoto());
        tempUserDetailDO.setHealthCertificateUrl(staffBaseInfoDTO.getHealthCertificate());
        tempUserDetailDO.setRegisterTime(new Date());
        if(StringUtils.isNotBlank(staffBaseInfoDTO.getEntryDate())){
            tempUserDetailDO.setRegisterTime(DateUtils.parseDate(staffBaseInfoDTO.getEntryDate()));
        }
        tempUserDetailDO.setSubmitTime(new Date());
        tempUserDetailDO.setSource("sync");
        return tempUserDetailDO;
    }

    public void syncXfsgTrainingShopPerson(String text) {
        log.info("syncXfsgTrainingShopPerson, reqBody={}", text);
        ShopInfoDO shopInfoDO = JSONObject.parseObject(text, ShopInfoDO.class);
        if(StringUtils.isAnyBlank(shopInfoDO.getStoreNum())){
            log.info("syncXfsgTrainingShopPerson={}", text);
            return;
        }

        StoreDO storeDO = storeDao.getByStoreNum(shopInfoDO.getStoreNum());

        if(storeDO == null){
            log.info("syncXfsgTrainingShopPerson门店不存在={}", text);
            return;
        }

        RegionDO regionDO = regionDao.getRegionByStoreId(storeDO.getStoreId());

        if(regionDO == null){
            log.info("syncXfsgTrainingShopPerson区域不存在={}", text);
            return;
        }

        List<EnterpriseUserDO> enterpriseUserDOList = enterpriseUserDAO.getUserListByRegionId(regionDO.getId());

        enterpriseUserDOList.forEach(enterpriseUserDO -> {
            // 拉取培训人员
            SyncXfsgTrainingPersonInfoDTO syncXfsgTrainingPersonInfoDTO = SyncXfsgTrainingPersonInfoDTO.builder()
                    .jobnumber(enterpriseUserDO.getJobnumber())
                    .idCard(enterpriseUserDO.getThirdOaUniqueFlag())
                    .storeNum(storeDO.getStoreNum())
                    .build();
            this.syncXfsgTrainingPerson(JSONObject.toJSONString(syncXfsgTrainingPersonInfoDTO));
        });

    }

    // 学历 0-小学 1-初中 2-高中   3-中专  4-大专   5-本科   6-硕士  7-硕士以上
    private Integer fillEducational(String highestDegree) {
        if("小学".equals(highestDegree)){
            return 0;
        }else if("初中".equals(highestDegree)){
            return 1;
        }else if("高中".equals(highestDegree)){
            return 2;
        }else if("中专".equals(highestDegree)){
            return 3;
        }else if("大专".equals(highestDegree)){
            return 4;
        }else if("本科".equals(highestDegree)){
            return 5;
        }else if("硕士".equals(highestDegree)){
            return 6;
        }else if("硕士以上".equals(highestDegree)){
            return 7;
        }
        return null;
    }

    private Long fillRoleId(String jobName) {
        if(UserRoleEnum.XFSG_CLERK.getDesc().equals(jobName)){
            return UserRoleEnum.XFSG_CLERK.getCode();
        }else if(UserRoleEnum.XFSG_SHOPOWNER.getDesc().equals(jobName)){
            return UserRoleEnum.XFSG_SHOPOWNER.getCode();
        }
        return UserRoleEnum.XFSG_CLERK.getCode();
    }

}
