package com.mosty.base.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.manager.remote.TbBaseAdaptRemoteService;
import com.mosty.base.model.dto.qwzx.AppSearchQuery;
import com.mosty.base.model.entity.jcgl.TbJcglJyqx;
import com.mosty.base.model.entity.jcgl.TbJcglXfcl;
import com.mosty.base.model.query.jcgl.TbJcglXfclQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.jcgl.TbJcglSbdwVo;
import com.mosty.base.utils.Constant;
import com.mosty.base.utils.DateUtils;
import com.mosty.base.utils.Kit;
import com.mosty.base.utils.UUIDGenerator;
import com.mosty.base.manager.mapper.TbJcglXfclMapper;
import com.mosty.base.manager.service.TbJcglXfclService;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.redis.service.RedisService;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.common.util.PermissionsUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

@AllArgsConstructor
@Service
public class TbJcglXfclServiceImpl extends ServiceImpl<TbJcglXfclMapper, TbJcglXfcl>
        implements TbJcglXfclService {

    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    private final RedisService redisService;

    @Override
    public IPage<TbJcglXfcl> getXfclList(TbJcglXfclQuery dto) {
        IPage<TbJcglXfcl> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        QueryWrapper<TbJcglXfcl> qw = new QueryWrapper<>();
//        UserInfo userInfo = UserInfoManager.get();
//        PermissionsUtil.queryWrapperUtil(qw, userInfo);
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
        qw.lambda().likeRight(StringUtils.isNotBlank(dto.getSsbmdm()), TbJcglXfcl::getSsbmdm, dto.getSsbmdm())
                .like(StringUtils.isNotBlank(dto.getCph()), TbJcglXfcl::getCph, dto.getCph())
                .like(StringUtils.isNotBlank(dto.getClpp()), TbJcglXfcl::getClpp, dto.getClpp())
                .orderByDesc(TbJcglXfcl::getXtCjsj)
        ;
        return this.baseMapper.selectPage(page, qw);
    }

    @Override
    public void addXfcl(TbJcglXfcl cl) {
        List<TbJcglXfcl> tbJcglXfcls = this.baseMapper.selectList(
                new QueryWrapper<TbJcglXfcl>()
                        .eq("cph", cl.getCph())
                        .eq("xt_scbz", 0)
        );
        if (tbJcglXfcls.size() > 0) {
            throw new BusinessException("车牌号重复");
        } else {
            cl.setCId(UUIDGenerator.getUUID());
            if (StringUtils.isNotBlank(cl.getSsbmdm())) {
                DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(cl.getSsbmdm());
//                cl.setSsbm(dept.getDeptname());
                cl.setSsbm(dept.getOrgJc());
                cl.setSsbmid(dept.getDeptid());
                cl.setSsbmdm(dept.getDeptcode());
                cl.setSsxgajdm(dept.getFxjcode());
                cl.setSsxgajid(dept.getFxjid());
                cl.setSsxgaj(dept.getFxjname());
                cl.setSssgaj(dept.getDszname());
                cl.setSssgajdm(dept.getDszcode());
                cl.setSssgajid(dept.getDszid());
            }
            this.baseMapper.insert(cl);
            if(StringUtils.isNotEmpty(cl.getGpsId())){
                TbJcglSbdwVo vo = new TbJcglSbdwVo();
                BeanUtils.copyProperties(cl, vo);
                vo.setSbbh(cl.getGpsId());
                vo.setSbmc(cl.getCph());
                vo.setScode("05");
                redisService.setCacheObject(Constant.PGIS_SB + vo.getSbbh(), vo);
            }
        }
    }

    @Override
    public void updateXfcl(TbJcglXfcl cl) {
        if (StringUtils.isEmpty(cl.getSsbmdm())) throw new BusinessException("请选择所属部门！！");
        List<TbJcglXfcl> tbJcglXfcls = this.baseMapper.selectList(
                new QueryWrapper<TbJcglXfcl>()
                        .eq("cph", cl.getCph())
                        .eq("xt_scbz", 0)
                        .ne("c_id", cl.getCId())
        );
        if (tbJcglXfcls.size() > 0) throw new BusinessException("车牌号重复");
        if (StringUtils.isNotBlank(cl.getSsbmdm())) {
            DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(cl.getSsbmdm());
//            cl.setSsbm(dept.getDeptname());
            cl.setSsbm(dept.getOrgJc());
            cl.setSsbmid(dept.getDeptid());
            cl.setSsbmdm(dept.getDeptcode());
            cl.setSsxgajdm(dept.getFxjcode());
            cl.setSsxgajid(dept.getFxjid());
            cl.setSsxgaj(dept.getFxjname());
            cl.setSssgaj(dept.getDszname());
            cl.setSssgajdm(dept.getDszcode());
            cl.setSssgajid(dept.getDszid());
        }
        cl.setXtSjly("1");
        this.baseMapper.updateById(cl);
        if(StringUtils.isNotEmpty(cl.getGpsId())){
            cl.setJyqx(null);
            TbJcglSbdwVo vo = new TbJcglSbdwVo();
            BeanUtils.copyProperties(cl, vo);
            vo.setSbbh(cl.getGpsId());
            vo.setSbmc(cl.getCph());
            vo.setScode("05");
            redisService.setCacheObject(Constant.PGIS_SB + vo.getSbbh(), vo);
        }
    }

    @Override
    public boolean deleteXfcl(List<String> id) {
        //批量注销
        TbJcglXfcl tbJcglXfcl = new TbJcglXfcl();
        tbJcglXfcl.setXtScbz("1");
        if (id.size() > 0) {
            this.baseMapper.deleteZb(id);
        }
        return true;
    }

    @Override
    public TbJcglXfcl selectClxq(String id) {
        return this.baseMapper.selectOne(new QueryWrapper<TbJcglXfcl>().eq("c_id", id));
    }

    @Override
    public String importData(List<TbJcglXfcl> xfclList, boolean updateSupport) {
        if (CollectionUtils.isEmpty(xfclList)) {
            throw new BusinessException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TbJcglXfcl xfcl : xfclList) {
            try {
                if (StringUtils.isEmpty(xfcl.getSsbmdm())
                        || StringUtils.isEmpty(xfcl.getCph())
                        || StringUtils.isEmpty(xfcl.getCplx())
                        || ObjectUtils.isEmpty(xfcl.getGmrq())
                        || ObjectUtils.isEmpty(xfcl.getBfrq())
                ) {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、车辆: " + xfcl.getCph() + " 信息不全,请仔细核查！");
                    continue;
                }
                TbJcglXfcl cl = this.baseMapper.selectOne(
                        new QueryWrapper<TbJcglXfcl>()
                                .eq("cph", xfcl.getCph())
                                .eq("cplx", xfcl.getCplx())
                                .last(" limit 1")
                );

                DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(xfcl.getSsbmdm());
                if (ObjectUtils.isNotEmpty(dept)) {
                    xfcl.setSsbm(dept.getDeptname());
                    xfcl.setSsbmid(dept.getDeptid());
                    xfcl.setSsbmdm(dept.getDeptcode());
                    xfcl.setSsxgajdm(dept.getFxjcode());
                    xfcl.setSsxgajid(dept.getFxjid());
                    xfcl.setSsxgaj(dept.getFxjname());
                    xfcl.setSssgaj(dept.getDszname());
                    xfcl.setSssgajdm(dept.getDszcode());
                    xfcl.setSssgajid(dept.getDszid());
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、所属部门编码不存在 " + xfcl.getSsbmdm() + " 信息不全,请仔细核查！");
                    continue;
                }
                xfcl.setXtSjzt("1");
                xfcl.setXtScbz("0");
                xfcl.setZbzt("1");
            if (ObjectUtils.isEmpty(cl)) {
                if (StringUtils.isEmpty(xfcl.getClnk())) {
                    xfcl.setClnk(DateUtils.getSystemYearString());
                }
                xfcl.setCId(UUIDGenerator.getUUID());
                this.baseMapper.insert(xfcl);
                if(StringUtils.isNotEmpty(xfcl.getGpsId())){
                    TbJcglSbdwVo vo = new TbJcglSbdwVo();
                    BeanUtils.copyProperties(xfcl, vo);
                    vo.setSbbh(xfcl.getGpsId());
                    vo.setSbmc(xfcl.getCph());
                    vo.setScode("05");
                    redisService.setCacheObject(Constant.PGIS_SB + vo.getSbbh(), vo);
                }
                successNum++;
                successMsg.append("<br/>" + successNum + "、车辆 " + xfcl.getCph() + " 导入成功");
            }else if (updateSupport) {
                xfcl.setCId(cl.getCId());
                this.baseMapper.updateById(xfcl);
                if(StringUtils.isNotEmpty(xfcl.getGpsId())){
                    xfcl.setJyqx(null);
                    TbJcglSbdwVo vo = new TbJcglSbdwVo();
                    BeanUtils.copyProperties(xfcl, vo);
                    vo.setSbbh(xfcl.getGpsId());
                    vo.setSbmc(xfcl.getCph());
                    vo.setScode("05");
                    redisService.setCacheObject(Constant.PGIS_SB + vo.getSbbh(), vo);
                }
                successNum++;
                successMsg.append("<br/>" + successNum + "、车辆 " + xfcl.getCph() + " 更新成功");
            }else {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、车辆 " + xfcl.getCph() + " 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、车辆 " + xfcl.getCph() + " 导入失败：";
            failureMsg.append(msg + e.getMessage());
            log.error(msg, e);
        }

        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public Page<TbJcglXfcl> selectXfclList(AppSearchQuery dto) {
        UserInfo user = UserInfoManager.get();
        LambdaQueryWrapper<TbJcglXfcl> wrapper = new LambdaQueryWrapper<TbJcglXfcl>().eq(TbJcglXfcl::getXtSjzt, "1");
        //本部门
        if ("1".equals(dto.getType())) {
            wrapper.like(StringUtils.isNotBlank(dto.getKeyword()), TbJcglXfcl::getCph, dto.getKeyword())
//                    .eq(TbJcglXfcl::getSsbmdm, user.getDeptCode())
                    .likeRight(TbJcglXfcl::getSsbmdm, user.getDeptCode().substring(0, 6))
            ;
        } else {
            String ssbmdm = tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null);
            wrapper.likeRight(StringUtils.isNotBlank(ssbmdm), TbJcglXfcl::getSsbmdm, ssbmdm)
                    .and(StringUtils.isNotBlank(dto.getKeyword()),
                            it -> it.like(TbJcglXfcl::getCph, dto.getKeyword())
                                    .or()
                                    .like(TbJcglXfcl::getSsbm, dto.getKeyword())
                    );
        }
        return this.baseMapper.selectPage(new Page<>(dto.getPageCurrent(), dto.getPageSize()), wrapper);
    }
}

