package com.xxfc.platform.vehicle.biz;


import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.universal.dto.SendMsgDTO;
import com.xxfc.platform.universal.feign.MQSenderFeign;
import com.xxfc.platform.vehicle.entity.CompanyInfo;
import com.xxfc.platform.vehicle.mapper.CompanyInfoMapper;
import com.xxfc.platform.vehicle.pojo.dto.CompanyInfoFindDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

import static com.github.wxiaoqi.security.common.config.rabbit.RabbitConstant.*;


@Service
@Slf4j
public class CompanyInfoBiz extends BaseBiz<CompanyInfoMapper, CompanyInfo>{

    @Autowired
    MQSenderFeign mqSenderFeign;



    public ObjectRestResponse addOrUpd(CompanyInfo companyInfo){
        Long id = companyInfo.getId() == null ? 0L :companyInfo.getId();
        if (id > 0L){
             updateSelectiveById(companyInfo);
        }else {
             insertSelective(companyInfo);
        }
        sendQueue(companyInfo);
        return  ObjectRestResponse.succ();
    }

    public List<CompanyInfo> getList(CompanyInfoFindDTO companyInfoFindDTO){
        Example example=new Example(CompanyInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDel",0);
        if (StringUtils.isNotBlank(companyInfoFindDTO.getName()) ){
            criteria.andLike("name","%" + companyInfoFindDTO.getName() + "%");
        }
        if (companyInfoFindDTO.getIds() != null && companyInfoFindDTO.getIds().size() > 0){
            criteria.andIn("id",companyInfoFindDTO.getIds());
        }
        example.setOrderByClause("crt_time desc ");

        return  selectByExample(example);
    }

    public ObjectRestResponse selectList(CompanyInfoFindDTO companyInfoFindDTO){
        PageHelper.startPage(companyInfoFindDTO.getPage(), companyInfoFindDTO.getLimit());
        PageInfo<CompanyInfo> pageInfo = new PageInfo<>(getList(companyInfoFindDTO));
        return ObjectRestResponse.succ(PageDataVO.pageInfo(pageInfo));
    }

    private void sendQueue(CompanyInfo companyInfo) {
        try {

            SendMsgDTO sendMsgDTO = new SendMsgDTO() {{
                setExchange(VEHICLE_TOPIC);
            }};
            sendMsgDTO.setJson(JSONUtil.toJsonStr(companyInfo));
            sendMsgDTO.setRoutKey(KEY_CORPORATION_UPD);
            mqSenderFeign.postSendMessage(sendMsgDTO);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


}
