package cn.superdesk.uniorder.service.thirdpart.szhtxx.paperInvoice.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.superdesk.uniorder.common.enums.common.CommonSoftDeleteEnum;
import cn.superdesk.uniorder.common.enums.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceUsedEnum;
import cn.superdesk.uniorder.common.lamda.AnLamdaUtils;
import cn.superdesk.uniorder.common.numerical.AnBeanUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import cn.superdesk.uniorder.dao.entity.sys.SysUser;
import cn.superdesk.uniorder.dao.entity.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfo;
import cn.superdesk.uniorder.dao.entity.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoExample;
import cn.superdesk.uniorder.dao.mapper.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoMapper;
import cn.superdesk.uniorder.dao.mapper.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoMapperEx;
import cn.superdesk.uniorder.dto.param.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoParam;
import cn.superdesk.uniorder.dto.param.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoQueryCriteria;
import cn.superdesk.uniorder.dto.vo.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoListItemVo;
import cn.superdesk.uniorder.service.sys.SysUserService;
import cn.superdesk.uniorder.service.thirdpart.szhtxx.paperInvoice.SzhtxxPaperInvoiceRedTaxInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Description:
 * @Author: linjinyu
 * @Email linjinyu@avic-s.com
 * @CreateDate: 2022-05-25 18:50:54
 * @UpdateUser: linjinyu
 * @UpdateDate: 2022-05-25 18:50:54
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class SzhtxxPaperInvoiceRedTaxInfoServiceImpl implements SzhtxxPaperInvoiceRedTaxInfoService {

    @Autowired
    private SzhtxxPaperInvoiceRedTaxInfoMapper   szhtxxPaperInvoiceRedTaxInfoMapper;
    @Autowired
    private SzhtxxPaperInvoiceRedTaxInfoMapperEx szhtxxPaperInvoiceRedTaxInfoMapperEx;
    @Autowired
    private SysUserService                       sysUserService;


    /****************************************** extends BaseService 部分 start ******************************************/

    @Override
    public int insertSelective(SzhtxxPaperInvoiceRedTaxInfo entity) {
        return szhtxxPaperInvoiceRedTaxInfoMapper.insertSelective(entity);
    }

    @Override
    public int updateByPrimaryKeySelective(SzhtxxPaperInvoiceRedTaxInfo entity) {
        return szhtxxPaperInvoiceRedTaxInfoMapper.updateByPrimaryKeySelective(entity);
    }

    public int saveOrUpdateByRedTaxInfoSn(SzhtxxPaperInvoiceRedTaxInfo entity, DateTime now, LoginSysUser loginSysUser) {

        int ret = 0;

        if (ObjectUtil.isNull(now)) {
            now = DateTime.now();
        }

        SzhtxxPaperInvoiceRedTaxInfo existDb = findByRedTaxInfoSn(entity.getRedTaxInfoSn());

        if (ObjectUtil.isNull(existDb)) {

            entity.setCreateTime(now);
            entity.setCreateUserId(loginSysUser.getSysUserId());
            entity.setCreateUserName(loginSysUser.getFullName());

            entity.setUpdateTime(now);
            entity.setUpdateUserId(loginSysUser.getSysUserId());
            entity.setUpdateUserName(loginSysUser.getFullName());

            ret = insertSelective(entity);

        } else {

            entity.setId(existDb.getId());

            entity.setUpdateTime(now);
            entity.setUpdateUserId(loginSysUser.getSysUserId());
            entity.setUpdateUserName(loginSysUser.getFullName());

            ret = updateByPrimaryKeySelective(entity);
        }

        return ret;
    }

    public int saveOrUpdateByRedTaxInfoLshAndBatchId(SzhtxxPaperInvoiceRedTaxInfo entity, DateTime now, LoginSysUser loginSysUser) {

        int ret = 0;

        if (ObjectUtil.isNull(now)) {
            now = DateTime.now();
        }

        SzhtxxPaperInvoiceRedTaxInfo existDb = findByRedTaxInfoLshAndBatchId(entity.getRedTaxInfoLsh(), entity.getBatchId());

        if (ObjectUtil.isNull(existDb)) {

            entity.setCreateTime(now);
            entity.setCreateUserId(loginSysUser.getSysUserId());
            entity.setCreateUserName(loginSysUser.getFullName());

            entity.setUpdateTime(now);
            entity.setUpdateUserId(loginSysUser.getSysUserId());
            entity.setUpdateUserName(loginSysUser.getFullName());

            ret = insertSelective(entity);

        } else {

            entity.setId(existDb.getId());

            entity.setUpdateTime(now);
            entity.setUpdateUserId(loginSysUser.getSysUserId());
            entity.setUpdateUserName(loginSysUser.getFullName());

            ret = updateByPrimaryKeySelective(entity);
        }

        return ret;
    }

    @Override
    public int opUpdateLogicalTemp2Normal(String batchId, String redTaxInfoSn, LoginSysUser loginSysUser) {

        SzhtxxPaperInvoiceRedTaxInfoExample          example  = new SzhtxxPaperInvoiceRedTaxInfoExample();
        SzhtxxPaperInvoiceRedTaxInfoExample.Criteria criteria = example.createCriteria();

        criteria
                .andBatchIdEqualTo(batchId)
                .andRedTaxInfoSnEqualTo(redTaxInfoSn)
                .andDeletedEqualTo(CommonSoftDeleteEnum.临时.getKey());

        return szhtxxPaperInvoiceRedTaxInfoMapper.updateByExampleSelective(
                SzhtxxPaperInvoiceRedTaxInfo
                        .builder()
                        .deleted(CommonSoftDeleteEnum.正常.getKey())
                        .build(),
                example
        );

    }

    @Override
    public void deleteObj(Long id) {
    }

    @Override
    public SzhtxxPaperInvoiceRedTaxInfo findById(Long id) {
        return szhtxxPaperInvoiceRedTaxInfoMapper.selectByPrimaryKey(id);
    }

    /**
     * 软删除标志要求为 正常
     *
     * @param redTaxInfoSn
     * @return
     */
    @Override
    public SzhtxxPaperInvoiceRedTaxInfo findByRedTaxInfoSn(String redTaxInfoSn) {

        SzhtxxPaperInvoiceRedTaxInfoExample          example  = new SzhtxxPaperInvoiceRedTaxInfoExample();
        SzhtxxPaperInvoiceRedTaxInfoExample.Criteria criteria = example.createCriteria();

        criteria
                .andRedTaxInfoSnEqualTo(redTaxInfoSn)
                .andDeletedEqualTo(CommonSoftDeleteEnum.正常.getKey());

        List<SzhtxxPaperInvoiceRedTaxInfo> resultList = szhtxxPaperInvoiceRedTaxInfoMapper.selectByExample(example);

        if (CollUtil.isNotEmpty(resultList)) {
            return resultList.get(0);
        } else {
            return null;
        }
    }

    @Override
    public SzhtxxPaperInvoiceRedTaxInfo findByRedTaxInfoLshAndBatchId(String redTaxInfoLsh, String batchId) {

        SzhtxxPaperInvoiceRedTaxInfoExample          example  = new SzhtxxPaperInvoiceRedTaxInfoExample();
        SzhtxxPaperInvoiceRedTaxInfoExample.Criteria criteria = example.createCriteria();

        criteria
                .andRedTaxInfoLshEqualTo(redTaxInfoLsh)
                .andBatchIdEqualTo(batchId);

        List<SzhtxxPaperInvoiceRedTaxInfo> resultList = szhtxxPaperInvoiceRedTaxInfoMapper.selectByExample(example);

        if (CollUtil.isNotEmpty(resultList)) {
            return resultList.get(0);
        } else {
            return null;
        }
    }

    @Override
    public PageInfo<SzhtxxPaperInvoiceRedTaxInfo> findByPaging(Map<String, Object> conditions, Integer pageNun, Integer pageSize) {
        return null;
    }

    @Override
    public List<SzhtxxPaperInvoiceRedTaxInfo> findAll(Map<String, Object> queryMap) {
        return null;
    }

    /****************************************** extends BaseService 部分   end ******************************************/


    @Override
    public int addSzhtxxPaperInvoiceRedTaxInfo(SzhtxxPaperInvoiceRedTaxInfo entity) {
        return szhtxxPaperInvoiceRedTaxInfoMapper.insertSelective(entity);
    }

    @Override
    public int saveOrUpdateSzhtxxPaperInvoiceRedTaxInfoParam(SzhtxxPaperInvoiceRedTaxInfoParam param, LoginSysUser loginSysUser) {

        int      ret = 0;
        DateTime now = DateTime.now();

        SzhtxxPaperInvoiceRedTaxInfo existDb = findByRedTaxInfoSn(param.getRedTaxInfoSn());

        if (ObjectUtil.isNull(existDb)) {

            SzhtxxPaperInvoiceRedTaxInfo forInsert = AnBeanUtils.copy(param, SzhtxxPaperInvoiceRedTaxInfo.class);

            forInsert.setCreateTime(now);
            forInsert.setCreateUserId(loginSysUser.getSysUserId());
            forInsert.setCreateUserName(loginSysUser.getFullName());

            forInsert.setUpdateTime(now);
            forInsert.setUpdateUserId(loginSysUser.getSysUserId());
            forInsert.setUpdateUserName(loginSysUser.getFullName());

            ret = insertSelective(forInsert);

        } else {

            SzhtxxPaperInvoiceRedTaxInfo forUpdate = AnBeanUtils.copy(param, SzhtxxPaperInvoiceRedTaxInfo.class);

            forUpdate.setId(existDb.getId());

            forUpdate.setUpdateTime(now);
            forUpdate.setUpdateUserId(loginSysUser.getSysUserId());
            forUpdate.setUpdateUserName(loginSysUser.getFullName());

            ret = updateByPrimaryKeySelective(forUpdate);
        }

        return ret;
    }

    @Override
    public int updateSzhtxxPaperInvoiceRedTaxInfo(SzhtxxPaperInvoiceRedTaxInfo entity) {
        SzhtxxPaperInvoiceRedTaxInfo originEntity = szhtxxPaperInvoiceRedTaxInfoMapper.selectByPrimaryKey(entity.getId());
//		AssertUtil.notNull(originEntity);
        AnBeanUtils.copy(entity, originEntity);
        return szhtxxPaperInvoiceRedTaxInfoMapper.updateByPrimaryKey(originEntity);
    }

    @Override
    public int updateFieldUsedByRedTaxInfoSn(String redTaxInfoSn, SzhtxxPaperInvoiceUsedEnum szhtxxPaperInvoiceUsedEnum, LoginSysUser loginSysUser) {

        int      ret = 0;
        DateTime now = DateTime.now();

        SzhtxxPaperInvoiceRedTaxInfo forUpdate = findByRedTaxInfoSn(redTaxInfoSn);

        if (ObjectUtil.isNotNull(forUpdate)) {

            forUpdate.setId(forUpdate.getId());

            forUpdate.setUsed(szhtxxPaperInvoiceUsedEnum.getKey());

            forUpdate.setUpdateTime(now);
            forUpdate.setUpdateUserId(loginSysUser.getSysUserId());
            forUpdate.setUpdateUserName(loginSysUser.getFullName());

            ret = updateByPrimaryKeySelective(forUpdate);
        }

        return ret;
    }

    @Override
    public int deleteSzhtxxPaperInvoiceRedTaxInfo(Long id) {
        return szhtxxPaperInvoiceRedTaxInfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public SzhtxxPaperInvoiceRedTaxInfo findSzhtxxPaperInvoiceRedTaxInfoById(Long id) {
        SzhtxxPaperInvoiceRedTaxInfo entity = szhtxxPaperInvoiceRedTaxInfoMapper.selectByPrimaryKey(id);
//		AssertUtil.notNull(entity);
        return entity;
    }

    @Override
    public R<List<SzhtxxPaperInvoiceRedTaxInfo>> pageQuery(Map<String, Object> conditions, int pageNun, int pageSize) {

        SzhtxxPaperInvoiceRedTaxInfoExample          example  = new SzhtxxPaperInvoiceRedTaxInfoExample();
        SzhtxxPaperInvoiceRedTaxInfoExample.Criteria criteria = example.createCriteria();

        // TODO 喜欢用Map 还是 Bean 自己喜欢... 后期添加 转 SzhtxxPaperInvoiceRedTaxInfoExample.Criteria
        // SzhtxxPaperInvoiceRedTaxInfo szhtxxPaperInvoiceRedTaxInfoConditions = AnBeanUtils.mapToBean(conditions,SzhtxxPaperInvoiceRedTaxInfo.class);

        PageHelper.startPage(pageNun, pageSize);
        List<SzhtxxPaperInvoiceRedTaxInfo>     resultList = szhtxxPaperInvoiceRedTaxInfoMapper.selectByExample(example);
        PageInfo<SzhtxxPaperInvoiceRedTaxInfo> page       = new PageInfo<SzhtxxPaperInvoiceRedTaxInfo>(resultList);
        PageHelper.clearPage();

        return new R<List<SzhtxxPaperInvoiceRedTaxInfo>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), resultList);

    }

    public R<List<SzhtxxPaperInvoiceRedTaxInfoListItemVo>> pageQueryGenericParam(SzhtxxPaperInvoiceRedTaxInfoQueryCriteria queryCriteria) {


        PageHelper.startPage(queryCriteria.getPageNumber(), queryCriteria.getPageSize());
        List<SzhtxxPaperInvoiceRedTaxInfoListItemVo>     resultList = szhtxxPaperInvoiceRedTaxInfoMapperEx.pageQueryGenericParam(queryCriteria);
        PageInfo<SzhtxxPaperInvoiceRedTaxInfoListItemVo> page       = new PageInfo<SzhtxxPaperInvoiceRedTaxInfoListItemVo>(resultList);
        PageHelper.clearPage();

        additionalInfoQueryGenericParam(resultList);

        return new R<List<SzhtxxPaperInvoiceRedTaxInfoListItemVo>>(page.getPageNum(), page.getPageSize(), (int) page.getTotal(), resultList);

    }


    // 附加信息
    public void additionalInfoQueryGenericParam(List<SzhtxxPaperInvoiceRedTaxInfoListItemVo> result) {

        if (CollUtil.isEmpty(result)) {
            return;
        }

        List<Long> sysUserIds = new ArrayList<>();

        List<Long> createUserIds = result.stream().filter(o -> o.getCreateUserId() != null).filter(AnLamdaUtils.distinctByKey(o -> o.getCreateUserId())).map(o -> o.getCreateUserId()).collect(Collectors.toList());
        List<Long> updateUserIds = result.stream().filter(o -> o.getUpdateUserId() != null).filter(AnLamdaUtils.distinctByKey(o -> o.getUpdateUserId())).map(o -> o.getUpdateUserId()).collect(Collectors.toList());

        sysUserIds.addAll(createUserIds);
        sysUserIds.addAll(updateUserIds);

        sysUserIds = sysUserIds.stream().distinct().collect(Collectors.toList());

        log.info("\n{}", JSONUtil.toJsonStr(sysUserIds));

        Map<Long, SysUser> sysUserMap = sysUserService.convertSysUserIds2MapSysUserId2Entity(sysUserIds);

        for (SzhtxxPaperInvoiceRedTaxInfoListItemVo vo : result) {

            vo.setUsedName(SzhtxxPaperInvoiceUsedEnum.getDesc(vo.getUsed()));


            /**************************************** mark by linjinyu at 20220516 v2.3 start ****************************************/

//            // 补 订单类型-订单来源-引用enum CommonServiceNoEnum
//            if (ObjectUtil.isNotNull(vo.getServiceNo())) {
//                vo.setServiceNoName(CommonServiceNoEnum.getByServiceNo(vo.getServiceNo()).getServiceName());
//            } else {
//                vo.setServiceNoName(CommonServiceNoEnum.UNKNOW.getServiceName());
//            }
//            // 补 操作来源-引用enum CommonSourceFromEnum
//            if (ObjectUtil.isNotNull(vo.getSourceFrom())) {
//                vo.setSourceFromName(CommonSourceFromEnum.getBySourceFromCode(vo.getSourceFrom()).getSourceFromName());
//            } else {
//                vo.setSourceFromName(CommonSourceFromEnum.未知来源.getSourceFromName());
//            }

            /**************************************** mark by linjinyu at 20220516 v2.3 start ****************************************/

//            // 修人
//            if (sysUserMap.get(vo.getCreateUserId()) != null) {
//                vo.setCreateUserName(sysUserMap.get(vo.getCreateUserId()).getFullname());
//            } else if (vo.getCreateUserId().equals(1L)) {
//                vo.setCreateUserName("系统");
//            }
//
//            if (sysUserMap.get(vo.getUpdateUserId()) != null) {
//                vo.setUpdateUserName(sysUserMap.get(vo.getUpdateUserId()).getFullname());
//            } else if (vo.getCreateUserId().equals(1L)) {
//                vo.setUpdateUserName("系统");
//            }


        }

    }

}