package com.mosty.qwzx.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.model.dto.qwzx.TbQwCjbsSaveDTO;
import com.mosty.base.model.dto.qwzx.TbQwCjbsUpdateDTO;
import com.mosty.base.model.entity.qwzx.TbQwCjbs;
import com.mosty.base.model.entity.qwzx.TbQwxfbbDk;
import com.mosty.base.model.query.qwzx.TbQwCjbsQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.utils.*;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.qwzx.mapper.TbQwCjbsMapper;
import com.mosty.qwzx.remote.TbBaseAdaptRemoteService;
import com.mosty.qwzx.service.TbQwCjbsService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 勤务管理处警报送表Service实现类
 */
@Service
@AllArgsConstructor
public class TbQwCjbsServiceImpl extends ServiceImpl<TbQwCjbsMapper, TbQwCjbs> implements TbQwCjbsService {

    /**
     * 调用部门信息远程适配层
     */
    TbBaseAdaptRemoteService tbBaseAdaptRemoteService;

    @Override
    public TbQwCjbs selectById(String id) {
        if(StringUtils.isBlank(id)){
            return null;
        }
        return this.baseMapper.selectOne(new QueryWrapper<TbQwCjbs>()
                .eq(TbQwCjbs.ID_FIELD, id)
                .eq("xt_sjzt", "1")
                .eq("xt_scbz", "0")
        );
    }

    @Override
    public Integer selectCountToday(String ssbmdm, String isChild) {
        String ssbm = this.tbBaseAdaptRemoteService.getSsbm(ssbmdm, isChild);
        QueryWrapper<TbQwCjbs> qw = new QueryWrapper<>();
        qw.likeRight("ssbmdm", ssbm);
        qw.ge("xt_cjsj", DateUtils.strToDate(DateUtils.getNowDate() + " 00:00:00", "02"));
        qw.le("xt_cjsj", DateUtils.strToDate(DateUtils.getNowDate() + " 23:59:59", "02"));
        return this.baseMapper.selectCount(qw);
    }

    @Override
    public IPage<TbQwCjbs> selectPage(TbQwCjbsQuery query) {
        IPage<TbQwCjbs> page = PageUtils.buildPage(query.getPageSize(), query.getPageCurrent());
        QueryWrapper<TbQwCjbs> qw = new QueryWrapper<>();

        //组装查询参数
        this.buildListSelectQueryWrapper(qw, query);

        return this.baseMapper.selectPage(page, qw);
    }

    @Override
    public List<TbQwCjbs> selectList(TbQwCjbsQuery query) {
        QueryWrapper<TbQwCjbs> qw = new QueryWrapper<>();

        //组装查询参数
        this.buildListSelectQueryWrapper(qw, query);

        return this.baseMapper.selectList(qw);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveEntity(TbQwCjbsSaveDTO dto) {
        //复制参数至实体
        TbQwCjbs entity = BeanUtil.copyProperties(dto, TbQwCjbs.class);

        //组装参数
        entity.setId(UUIDGenerator.getUUID());
        entity.setXtSjly("1");
        UserInfo user = UserInfoManager.get();
        this.buildRyInfo(user, entity);
        this.buildSsbmInfo(user, entity);

        //保存实体
        int resultInt = this.baseMapper.insert(entity);
        if(resultInt > 0){
            return entity.getId();
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateEntity(TbQwCjbsUpdateDTO dto) {
        //复制参数至实体
        TbQwCjbs entity = BeanUtil.copyProperties(dto, TbQwCjbs.class);

        //组装参数
        UserInfo user = UserInfoManager.get();
        this.buildSsbmInfo(user, entity);

        //修改实体
        int resultInt = this.baseMapper.updateById(entity);
        if(resultInt > 0){
            return entity.getId();
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelEntity(TbQwCjbs entity) {
        //先修改系统字段
        TbQwCjbs cancelEntity = new TbQwCjbs();
        cancelEntity.setId(entity.getId());
        this.baseMapper.updateById(cancelEntity);
        //再注销
        return this.baseMapper.deleteById(entity.getId());
    }

    /**
     * 组装查询参数
     * @param qw QueryWrapper
     * @param query 查询对象
     */
    private void buildListSelectQueryWrapper(QueryWrapper<TbQwCjbs> qw, TbQwCjbsQuery query){
        //组装排序方式
        QueryWrapperUtils.buildQueryWrapperOrder(qw, query.getSort(), query.getOrder());
        //未注销数据
        qw.eq("xt_sjzt", "1").eq("xt_scbz", "0");
        //组装权限查询
        if(StringUtils.isBlank(query.getSsbmdm())){
            UserInfo user = UserInfoManager.get();
            query.setSsbmdm(user.getDeptCode());
        }
        if(StringUtils.isBlank(query.getIsChild())){
            query.setIsChild(Constant.DICT_ITEM_D_BZ_SF_YES);
        }
        qw.likeRight(TbQwCjbs.SSBMDM_FIELD, tbBaseAdaptRemoteService.getSsbm(query.getSsbmdm(), query.getIsChild()));

        //处警上报类型
        if(StringUtils.isNotBlank(query.getCjsbLx())){
            qw.in(TbQwCjbs.CJSB_LX_FIELD, Arrays.stream(query.getCjsbLx().split(",")).filter(StringUtils::isNotBlank).collect(Collectors.toList()));
        }

        //处警上报人员姓名
        qw.like(StringUtils.isNotBlank(query.getCjsbRyXm()), TbQwCjbs.CJSB_RY_XM_FIELD, query.getCjsbRyXm());
        //处警上报人员身份证号
        qw.eq(StringUtils.isNotBlank(query.getCjsbRySfzh()), TbQwCjbs.CJSB_RY_SFZH_FIELD, query.getCjsbRySfzh());
    }

    /**
     * 组装人员信息
     * @param user 登陆人信息
     * @param entity 实体信息
     */
    public void buildRyInfo(UserInfo user, TbQwCjbs entity){
        if(ObjectUtils.isEmpty(user) || ObjectUtils.isEmpty(entity)){
            return;
        }
        entity.setCjsbRyXm(user.getUserName());
        entity.setCjsbRySfzh(user.getIdEntityCard());
    }

    /**
     * 组装部门信息
     * @param user 登陆人信息
     * @param entity 实体信息
     */
    public void buildSsbmInfo(UserInfo user, TbQwCjbs entity){
        if(ObjectUtils.isEmpty(user) || ObjectUtils.isEmpty(entity)){
            return;
        }
        if(StringUtils.isBlank(entity.getSsbmdm())){
            entity.setSsbmdm(user.getDeptCode());
        }

        DeptInfoVo deptInfoVo = tbBaseAdaptRemoteService.getOrgByOrgcode(entity.getSsbmdm());
        if(ObjectUtils.isNotEmpty(deptInfoVo)){
            entity.setSsbm(deptInfoVo.getDeptname());
            entity.setSsbmdm(deptInfoVo.getDeptcode());
            entity.setSsxgaj(deptInfoVo.getFxjname());
            entity.setSsxgajdm(deptInfoVo.getFxjcode());
            entity.setSssgaj(deptInfoVo.getDszname());
            entity.setSssgajdm(deptInfoVo.getDszcode());
        }
    }

}
