package com.junmp.jyzb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junmp.jyzb.api.bean.dto.CabinetPoliceDto;
import com.junmp.jyzb.api.bean.query.PolicemanFingerReq;
import com.junmp.jyzb.api.bean.req.CabinetPolicemanReq;
import com.junmp.jyzb.api.bean.req.UpdatePoliceFingerReq;
import com.junmp.jyzb.entity.PoliceFinger;
import com.junmp.jyzb.api.exception.enums.PolicemanFingerExceptionEnum;
import com.junmp.jyzb.entity.Policeman;
import com.junmp.jyzb.entity.PubOrg;
import com.junmp.jyzb.service.PoliceFingerService;
import com.junmp.jyzb.service.PolicemanService;
import com.junmp.jyzb.service.PubOrgService;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.db.api.factory.PageFactory;
import com.junmp.v2.db.api.factory.PageResultFactory;
import com.junmp.v2.db.api.page.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.junmp.jyzb.mapper.PoliceFingerMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PoliceFingerServiceImpl extends ServiceImpl<PoliceFingerMapper, PoliceFinger> implements PoliceFingerService {

    @Resource
    private PolicemanService policemanService;

    @Resource
    private PubOrgService pubOrgService;


    //新增指纹信息
    @Override
    public Integer addFingerInfo(UpdatePoliceFingerReq req) {
        //判断警员是否存在
        policemanService.PoliceExist(req.getPoliceId());
        PoliceFinger policeFinger = getOne(new LambdaQueryWrapper<PoliceFinger>()
                .eq(ObjectUtil.isNotEmpty(req.getPoliceId()),PoliceFinger::getPoliceId,req.getPoliceId())
                .eq(ObjectUtil.isNotEmpty(req.getFingerInfo()),PoliceFinger::getFingerInfo,req.getFingerInfo()));
        //指纹信息存在抛出异常
        if (ObjectUtil.isNotNull(policeFinger)) {
            throw new ServiceException(PolicemanFingerExceptionEnum.POLICEMAN_FINGER_EXCEPTION_ENUM);
        }
        PoliceFinger policeFinger1=new PoliceFinger();
        BeanPlusUtil.copyProperties(req, policeFinger1);
        save(policeFinger1);
        return policeFinger1.getId();
    }

    //修改指纹信息
    @Override
    public boolean updateFingerInfo(UpdatePoliceFingerReq req) {
        PoliceFinger policeFinger = PolicemanFingerExist(req.getId(), req.getPoliceId());
        BeanPlusUtil.copyProperties(req,policeFinger);
        return updateById(policeFinger);
    }

    //查询指纹信息
    @Override
    public CabinetPoliceDto searchFingerInfo(PolicemanFingerReq req) {
        policemanService.PoliceExist(req.getPoliceId());
        LambdaQueryWrapper<PoliceFinger> wrapper = createWrapper(req);
        List<PoliceFinger> list = this.list(wrapper);
        CabinetPoliceDto cabinetPoliceDto = new CabinetPoliceDto();
        BeanPlusUtil.copyProperties(req,cabinetPoliceDto);
        List<UpdatePoliceFingerReq> collect = list.stream().map(policeFinger -> {
            UpdatePoliceFingerReq updatePoliceFingerReq = new UpdatePoliceFingerReq();
            BeanPlusUtil.copyProperties(updatePoliceFingerReq, policeFinger);
            return updatePoliceFingerReq;
        }).collect(Collectors.toList());
        cabinetPoliceDto.setFingerList(collect);
        return cabinetPoliceDto;
    }


    //    删除指纹信息
    @Override
    @Transactional
    public CabinetPoliceDto deleteFinger(CabinetPolicemanReq req) {
        //判断警员是否存在
        Policeman policeman = policemanService.PoliceExist(req.getStaffId());
        List<UpdatePoliceFingerReq> fingerList = req.getFingerList();
        removeBatchByIds(fingerList);
        PubOrg pubOrg = pubOrgService.PubOrgCodeExist(req.getOrgCode());
        policemanService.updateOrgAndSendMessage(pubOrg,req.getCabinetOrgCode(), req.getDevSn());
        CabinetPoliceDto cabinetPoliceDto = new CabinetPoliceDto();
        BeanPlusUtil.copyProperties(req,cabinetPoliceDto);
        return cabinetPoliceDto;
    }

    /**
     * 分页查询
     * @param req
     * @return
     */
    @Override
    public PageResult<PoliceFinger> findPage(PolicemanFingerReq req) {
        LambdaQueryWrapper<PoliceFinger> wrapper = createWrapper(req);
        Page<PoliceFinger> page = this.page(PageFactory.getDefaultPage(req.getPageNo(),req.getPageSize()), wrapper);
        return PageResultFactory.createPageResult(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertOrUpdateFingerInfo(UpdatePoliceFingerReq req) {
        List<UpdatePoliceFingerReq> fingerList = req.getFingerList();
        List<PoliceFinger> addList=new ArrayList<>();
        List<PoliceFinger> updateList=new ArrayList<>();
        //判断指纹信息是否存在，如果存在，则直接进行更新
        List<PoliceFinger> list = list(Wrappers.<PoliceFinger>lambdaQuery()
                .eq(PoliceFinger::getPoliceId, req.getPoliceId()));
        if (CollectionUtil.isNotEmpty(list)){//不为空直接遍历进行更新
            for (UpdatePoliceFingerReq fl:fingerList) {
                boolean flag=false;
                for (PoliceFinger pf:list) {
                    if (fl.getFingerNum().equals(pf.getFingerNum())){
                        flag=true;
                        pf.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                        updateList.add(pf);
                        break;
                    }
                }
                if (!flag){//表示该指纹是新的，需要进行添加
                    PoliceFinger finger = new PoliceFinger();
                    BeanPlusUtil.copyProperties(fl,finger);
                    finger.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                    finger.setCreateTime(DateTimeUtil.getCurrentDateTime());
                    finger.setName("指纹"+fl.getFingerNum());
                    addList.add(finger);
                }
            }
        }else {//如果为空，直接进行新增
            for (UpdatePoliceFingerReq fl:fingerList) {
                PoliceFinger finger = new PoliceFinger();
                BeanPlusUtil.copyProperties(fl,finger);
                finger.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                finger.setCreateTime(DateTimeUtil.getCurrentDateTime());
                finger.setName("指纹"+fl.getFingerNum());
                addList.add(finger);
            }
        }
        boolean a=true;
        if (CollectionUtil.isNotEmpty(addList)){
            a = saveBatch(addList);
        }
        boolean b=true;
        if (CollectionUtil.isNotEmpty(updateList)){
            b = updateBatchById(updateList);
        }
        return a && b;

    }

    @Override
    @Transactional
    public CabinetPoliceDto insertOrUpdateFingerInfoFromCab(CabinetPolicemanReq req) {
        List<UpdatePoliceFingerReq> fingerList = req.getFingerList();
        List<PoliceFinger> addList=new ArrayList<>();
        List<PoliceFinger> updateList=new ArrayList<>();
        //判断指纹信息是否存在，如果存在，则直接进行更新
        List<PoliceFinger> list = list(Wrappers.<PoliceFinger>lambdaQuery()
                .eq(PoliceFinger::getPoliceId, req.getStaffId()));
        if (CollectionUtil.isNotEmpty(list)){//不为空直接遍历进行更新
            for (UpdatePoliceFingerReq fl:fingerList) {
                boolean flag=false;
                for (PoliceFinger pf:list) {
                    if (ObjectUtil.isNotNull(fl.getId())){
                        flag=true;
                        BeanPlusUtil.copyProperties(fl,pf);
                        pf.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                        updateList.add(pf);
                        break;
                    }
                }
                if (!flag){//表示该指纹是新的，需要进行添加
                    PoliceFinger finger = new PoliceFinger();
                    BeanPlusUtil.copyProperties(fl,finger);
                    finger.setPoliceId(req.getStaffId());
                    finger.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                    finger.setCreateTime(DateTimeUtil.getCurrentDateTime());
                    addList.add(finger);
                }
            }
        }else {//如果为空，直接进行新增
            for (UpdatePoliceFingerReq fl:fingerList) {
                PoliceFinger finger = new PoliceFinger();
                BeanPlusUtil.copyProperties(fl,finger);
                finger.setPoliceId(req.getStaffId());
                finger.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                finger.setCreateTime(DateTimeUtil.getCurrentDateTime());
                addList.add(finger);
            }
        }
        if (CollectionUtil.isNotEmpty(addList)){
            saveBatch(addList);
        }
        if (CollectionUtil.isNotEmpty(updateList)){
            updateBatchById(updateList);
        }
        CabinetPoliceDto cabinetPoliceDto = new CabinetPoliceDto();
        BeanPlusUtil.copyProperties(req,cabinetPoliceDto);

        List<UpdatePoliceFingerReq> collect;
        if (addList.size()>0){
//            List<String> faceInfoList = req.getFingerList().stream().map(UpdatePoliceFingerReq::getFingerInfo).collect(Collectors.toList());
//            List<PoliceFinger> policeList = list(new LambdaQueryWrapper<PoliceFinger>().eq(PoliceFinger::getPoliceId, req.getPoliceId()).in(PoliceFinger::getFingerInfo, faceInfoList));
            collect = addList.stream().map(policeFinger -> {
                UpdatePoliceFingerReq updatePoliceFingerReq = new UpdatePoliceFingerReq();
                BeanPlusUtil.copyProperties(policeFinger, updatePoliceFingerReq);
                return updatePoliceFingerReq;
            }).collect(Collectors.toList());
        }else {
            collect = updateList.stream().map(policeFinger -> {
                UpdatePoliceFingerReq updatePoliceFingerReq = new UpdatePoliceFingerReq();
                BeanPlusUtil.copyProperties(policeFinger, updatePoliceFingerReq);
                return updatePoliceFingerReq;
            }).collect(Collectors.toList());
        }
        cabinetPoliceDto.setFingerList(collect);
        PubOrg pubOrg = pubOrgService.PubOrgCodeExist(req.getOrgCode());
        policemanService.updateOrgAndSendMessage(pubOrg,req.getCabinetOrgCode(),req.getDevSn());
        return cabinetPoliceDto;
    }


    //查询的各种条件信息
    private LambdaQueryWrapper<PoliceFinger> createWrapper(PolicemanFingerReq req) {
        LambdaQueryWrapper<PoliceFinger> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isEmpty(req)) {
            return wrapper;
        }
        //根据业务编码查询
        //警员id
        wrapper.eq(ObjectUtil.isNotEmpty(req.getPoliceId()), PoliceFinger::getPoliceId, req.getPoliceId());
        //根据企业名称模糊查询
        //指纹名称
        wrapper.like(ObjectUtil.isNotEmpty(req.getName()), PoliceFinger::getName, req.getName());
        //指纹信息
        wrapper.like(ObjectUtil.isNotEmpty(req.getFingerInfo()), PoliceFinger::getFingerInfo, req.getFingerInfo());
        wrapper.orderByDesc(PoliceFinger::getUpdateTime);
        return wrapper;
    }

    //判断指纹信息是否存在
    public PoliceFinger PolicemanFingerExist(Integer fingerId,String policeId){
        PoliceFinger one = getOne(new LambdaQueryWrapper<PoliceFinger>()
                .eq(PoliceFinger::getId,fingerId)
                .eq(PoliceFinger::getPoliceId, policeId));
        if (ObjectUtil.isNull(one)){
            throw new ServiceException(PolicemanFingerExceptionEnum.POLICEMAN_FINGER_NOTEXISTS);
        }
        return one;
    }
}
