package com.mortals.xhx.module.matter.service.impl;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.mortals.framework.common.Rest;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.ParamDto;
import com.mortals.framework.model.Result;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.EntityUtil;
import com.mortals.xhx.busiz.req.ComplexImplementationReq;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.busiz.rsp.ImplementEventInfo;
import com.mortals.xhx.busiz.rsp.RecordsItem;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import com.mortals.xhx.module.matter.model.ApplyMatterEntity;
import com.mortals.xhx.module.matter.model.EventImplementationQuery;
import com.mortals.xhx.module.matter.service.ApplyMatterService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.matter.dao.EventImplementationDao;
import com.mortals.xhx.module.matter.model.EventImplementationEntity;
import com.mortals.xhx.module.matter.service.EventImplementationService;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

import static com.mortals.xhx.common.key.Constant.HTTP_TIMEOUT;
import static com.mortals.xhx.common.key.RedisKey.KEY_COMPLEX_REQ;
import static com.mortals.xhx.common.key.RedisKey.KEY_EVENT_IMPLEMENTATION_RESP;

/**
* EventImplementationService
* 综窗事项列表 service实现
*
* @author zxfei
* @date 2024-06-20
*/
@Service("eventImplementationService")
@Slf4j
public class EventImplementationServiceImpl extends AbstractCRUDServiceImpl<EventImplementationDao, EventImplementationEntity, Long> implements EventImplementationService {

    @Autowired
    private ICacheService cacheService;
    @Autowired
    private ApplyMatterService applyMatterService;

    @Override
    public void syncEventImplementation() {
        log.info("开始执行综窗事项同步任务....");
        int currentPage = 1;
        int pageSize = 20;
        ComplexImplementationReq req = new ComplexImplementationReq();
        req.setUrlPath("eventImplementation/list");
        req.setPageSize(pageSize);
        req.setCurrentPage(currentPage);
        try {
            log.info("当前页码："+currentPage);
            req.setNonce(RandomUtil.randomNumbers(6));
            cacheService.lpush(KEY_COMPLEX_REQ, JSONObject.toJSONString(req));
            String rest = cacheService.blpop(KEY_EVENT_IMPLEMENTATION_RESP + req.getNonce(), HTTP_TIMEOUT, String.class);
            if (ObjectUtil.isEmpty(rest)) {
                throw new AppException("请求访问超时");
            }
            Rest<ImplementEventInfo> eventListRest = JSON.parseObject(rest, new TypeReference<Rest<ImplementEventInfo>>() {
            });
            if(eventListRest.getCode()==ApiRespCodeEnum.SUCCESS.getValue()){
                List<EventImplementationEntity> list = convertEventImplementation(eventListRest.getData().getRecords());
                this.saveOrUpdate(list);
                int total = eventListRest.getData().getTotal();
                int pages = total/pageSize + 1;
                log.info("总页数："+ pages);
                if(pages > 1){
                    while (currentPage < pages){
                        currentPage++;
                        req.setCurrentPage(currentPage);
                        log.info("当前页码："+currentPage);
                        req.setNonce(RandomUtil.randomNumbers(6));
                        cacheService.lpush(KEY_COMPLEX_REQ, JSONObject.toJSONString(req));
                        String restTemp = cacheService.blpop(KEY_EVENT_IMPLEMENTATION_RESP + req.getNonce(), HTTP_TIMEOUT, String.class);
                        if (ObjectUtil.isEmpty(restTemp)) {
                            throw new AppException("请求访问超时");
                        }
                        Rest<ImplementEventInfo> eventListTemp = JSON.parseObject(restTemp, new TypeReference<Rest<ImplementEventInfo>>() {
                        });
                        if(eventListTemp.getCode()==ApiRespCodeEnum.SUCCESS.getValue()){
                            List<EventImplementationEntity> listTemp = convertEventImplementation(eventListTemp.getData().getRecords());
                            this.saveOrUpdate(listTemp);
                        }else {
                            log.info("查询综窗事项列表失败");
                        }
                    }
                }
            }else {
                log.info("查询综窗事项列表失败");
            }
        } catch (Exception e) {
            log.error("同步数据失败", e);
        }
        log.info("综窗事项同步任务执行完成....");
    }

    @Override
    public void saveOrUpdate(List<EventImplementationEntity> list) {
        if(CollectionUtils.isNotEmpty(list)){
            List<EventImplementationEntity> saveList = new ArrayList<>();
            List<EventImplementationEntity> updateList = new ArrayList<>();
            for(EventImplementationEntity entity:list){
                EventImplementationEntity temp = this.selectOne(new EventImplementationQuery().eventId(entity.getEventId()));
                if(temp!=null){
                    entity.setId(temp.getId());
                    entity.setUpdateTime(new Date());
                    updateList.add(entity);
                }else {
                    entity.setCreateTime(new Date());
                    saveList.add(entity);
                }
            }

            if(CollectionUtils.isNotEmpty(saveList)){
                this.save(saveList);
            }
            if(CollectionUtils.isNotEmpty(updateList)){
                this.update(updateList);
            }
        }
    }

    @Override
    public Result<EventImplementationEntity> findSubList(EventImplementationEntity params, PageInfo pageInfo, Context context) throws AppException {
        EventImplementationEntity newParams = this.findBefore(params, pageInfo, context);
        Result<EventImplementationEntity> result = this.dao.getList(getQueryParam(newParams), pageInfo,"getSubList");
        this.findAfter(params, pageInfo, context, result.getList());
        return result;
    }

    protected ParamDto getQueryParam(EventImplementationEntity params) {
        ParamDto paramDto = new ParamDto();
        Map map = new HashMap();
        EntityUtil.entityToMap(params, map);
        paramDto.setCondition(map);
        paramDto.setOrderCol(params.getOrderCols());
        paramDto.setOrderColList(params.getOrderColList());
        paramDto.setData(params.getTabColMap());
        paramDto.setMatchMode(params.getMatchMode());
        paramDto.setColPickMode(params.getColPickMode());
        paramDto.setGroupList(params.getGroupList());
        return paramDto;
    }

    @Override
    public int addToApplyMatter(EventImplementationEntity entity,Context context) {
        int result = 0;
        if(CollectionUtils.isNotEmpty(entity.getIdList())){
            List<EventImplementationEntity> list = this.find(new EventImplementationQuery().idList(entity.getIdList()));
            if(CollectionUtils.isNotEmpty(list)){
                List<ApplyMatterEntity> applyMatterList = new ArrayList<>();
                Long userId = null;
                if(context!=null && context.getUser()!=null){
                    userId = context.getUser().getId();
                }
                for (EventImplementationEntity item:list){
                    ApplyMatterEntity applyMatterEntity = new ApplyMatterEntity();
                    applyMatterEntity.initAttrValue();
                    BeanUtils.copyProperties(item, applyMatterEntity);
//                    applyMatterEntity.setEventId(item.getEventId());
//                    applyMatterEntity.setEventObjectType(item.getEventObjectType());
//                    applyMatterEntity.setEventType(item.getEventType());
//                    applyMatterEntity.setHandlingItemCode(item.getHandlingItemCode());
//                    applyMatterEntity.setImplementName(item.getImplementName());
//                    applyMatterEntity.setImplementCoding(item.getImplementCoding());
//                    applyMatterEntity.setCrossFlag(item.getCrossFlag());
//                    applyMatterEntity.setDeptId(item.getDeptId());
//                    applyMatterEntity.setDeptName(item.getDeptName());
                    applyMatterEntity.setApplyType(entity.getApplyType());
                    applyMatterEntity.setCreateTime(new Date());
                    applyMatterEntity.setCreateUserId(userId);
                    applyMatterList.add(applyMatterEntity);
                }
                if(CollectionUtils.isNotEmpty(applyMatterList)){
                    applyMatterService.save(applyMatterList);
                }
            }
        }
        return result;
    }

    private List<EventImplementationEntity> convertEventImplementation(List<RecordsItem> records){
        List<EventImplementationEntity> list = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(records)){
            for (RecordsItem item:records){
                EventImplementationEntity entity = new EventImplementationEntity();
                entity.initAttrValue();
                BeanUtils.copyProperties(item, entity);
//                entity.setEventId(item.getEventId());
//                entity.setEventObjectType(item.getEventObjectType());
//                entity.setEventType(item.getEventType());
//                entity.setHandlingItemCode(item.getHandlingItemCode());
//                entity.setImplementName(item.getImplementName());
//                entity.setImplementCoding(item.getImplementCoding());
//                entity.setCrossFlag(item.getCrossFlag());
//                entity.setDeptId(item.getDeptId());
//                entity.setDeptName(item.getDeptName());
                list.add(entity);
            }
        }
        return list;
    }
}