package com.cool.store.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.RedisConstant;
import com.cool.store.context.PartnerUserHolder;
import com.cool.store.dao.HyPartnerClerkDAO;
import com.cool.store.dto.enterprise.SysDepartmentDTO;
import com.cool.store.dto.log.WantInfoUpdateDTO;
import com.cool.store.entity.HyPartnerClerkDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.OperateTypeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.request.PartnerClerkInfoRequest;
import com.cool.store.service.HyPartnerClerkService;
import com.cool.store.service.LogService;
import com.cool.store.utils.CoolDateUtils;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.utils.StringUtil;
import com.cool.store.vo.PartnerClerkVO;
import com.cool.store.vo.PartnerUserInfoVO;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author wxp
 * @Date 2023/6/14 21:37
 * @Version 1.0
 */
@Slf4j
@Service
public class HyPartnerClerkServiceImpl implements HyPartnerClerkService {

    @Resource
    HyPartnerClerkDAO hyPartnerClerkDAO;

    @Resource
    private RedisUtilPool redisUtilPool;

    @Autowired
    private LogService logService;

    @Override
    public List<PartnerClerkVO> getPartnerClerkList(Long lineId) {
        List<HyPartnerClerkDO> hyPartnerClerkList = hyPartnerClerkDAO.getHyPartnerClerkList(lineId);
        List<PartnerClerkVO> result= new ArrayList<>();
        hyPartnerClerkList.forEach(x->{
            PartnerClerkVO partnerClerkVO = new PartnerClerkVO();
            partnerClerkVO.setPartnerId(x.getPartnerId());
            partnerClerkVO.setPartnerLineId(x.getPartnerLineId());
            partnerClerkVO.setAge(x.getAge());
            partnerClerkVO.setChooseReason(x.getChooseReason());
            partnerClerkVO.setUsername(x.getUsername());
            partnerClerkVO.setRelationship(x.getRelationship());
            result.add(partnerClerkVO);
        });
        return result;
    }

    @Override
    public Boolean submitPartnerClerkInfo(PartnerClerkInfoRequest request) {
        log.info("HyPartnerClerkServiceImpl#submitPartnerClerkInfo request:{}", JSONObject.toJSONString(request));
        if (StringUtil.isBlank(request.getPartnerId()) || Objects.isNull(request.getPartnerLineId())){
            throw new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        String cacheKey = MessageFormat.format(RedisConstant.PARTNER_CLERKINFO_CACHE_KEY, request.getPartnerId(), request.getPartnerLineId());
        if(!request.getSubmitFlag()){
            // 自动保存时
            redisUtilPool.setString(cacheKey, JSONObject.toJSONString(request), RedisConstant.ONE_DAY_SECONDS);
            return Boolean.TRUE;
        }
        List<WantInfoUpdateDTO.ClerkUpdate> beforeClerkUpdate = Lists.newArrayList();
        List<WantInfoUpdateDTO.ClerkUpdate> afterClerkUpdate = Lists.newArrayList();
        List<HyPartnerClerkDO> beforClerkDOList = hyPartnerClerkDAO.listByPartnerIdAndLineId(request.getPartnerId(), request.getPartnerLineId());
        hyPartnerClerkDAO.deleteByPartnerIdAndLineId(request.getPartnerId(), request.getPartnerLineId());
        List<HyPartnerClerkDO> clerkDOList = new ArrayList<>();
        ListUtils.emptyIfNull(request.getPartnerClerkRequestList()).stream().forEach(x->{
            HyPartnerClerkDO clerkDO = new HyPartnerClerkDO();
            clerkDO.setPartnerLineId(request.getPartnerLineId());
            clerkDO.setPartnerId(request.getPartnerId());
            clerkDO.setUsername(x.getUsername());
            clerkDO.setRelationship(x.getRelationship());
            clerkDO.setAge(x.getAge());
            clerkDO.setChooseReason(x.getChooseReason());
            clerkDOList.add(clerkDO);
        });
        if (CollectionUtils.isNotEmpty(clerkDOList)){
            hyPartnerClerkDAO.batchInsert(clerkDOList);
            afterClerkUpdate =  JSONObject.parseArray(JSONObject.toJSONString(clerkDOList), WantInfoUpdateDTO.ClerkUpdate.class);
        }
        if (CollectionUtils.isNotEmpty(beforClerkDOList)){
            beforeClerkUpdate =  JSONObject.parseArray(JSONObject.toJSONString(beforClerkDOList), WantInfoUpdateDTO.ClerkUpdate.class);
        }
        redisUtilPool.delKey(cacheKey);
        //记录日志
        PartnerUserInfoVO operator = PartnerUserHolder.getUser();
        WantInfoUpdateDTO log = WantInfoUpdateDTO.builder().mobile(operator.getMobile()).operateUserId(operator.getPartnerId()).operateUsername(operator.getUsername())
                .operateTime(DateUtil.format(new Date(), CoolDateUtils.DATE_FORMAT_SEC))
                .beforeClerkUpdate(beforeClerkUpdate).afterClerkUpdate(afterClerkUpdate).build();
        logService.recordPartnerBizLog(operator, request.getPartnerLineId(), OperateTypeEnum.INTENT_INFO_UPDATE,log);
        return true;
    }

    @Override
    public List<PartnerClerkVO> queryPartnerClerkInfo(String partnerId, Long lineId) {
        String cacheKey = MessageFormat.format(RedisConstant.PARTNER_CLERKINFO_CACHE_KEY, partnerId, lineId);
        if (StringUtils.isNotBlank(redisUtilPool.getString(cacheKey))) {
            PartnerClerkInfoRequest partnerClerkInfoRequest = JSONObject.parseObject(redisUtilPool.getString(cacheKey), PartnerClerkInfoRequest.class);
            List<PartnerClerkVO> clerkVOList = ListUtils.emptyIfNull(partnerClerkInfoRequest.getPartnerClerkRequestList()).stream().map(clerkRequest -> {
                PartnerClerkVO clerkVO = new PartnerClerkVO();
                BeanUtil.copyProperties(clerkRequest, clerkVO);
                return clerkVO;
            }).collect(Collectors.toList());
            return clerkVOList;
        }
        List<HyPartnerClerkDO> clerkDOList = hyPartnerClerkDAO.listByPartnerIdAndLineId(partnerId, lineId);
        List<PartnerClerkVO> clerkVOList = ListUtils.emptyIfNull(clerkDOList).stream().map(clerkDO -> {
            PartnerClerkVO clerkVO = new PartnerClerkVO();
            BeanUtil.copyProperties(clerkDO, clerkVO);
            return clerkVO;
        }).collect(Collectors.toList());
        return clerkVOList;
    }

}
