/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.policy.info.modular.sqrEnterpriseApply.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.unis.auth.core.pojo.SaBaseLoginUser;
import com.unis.auth.core.util.StpClientUtil;
import com.unis.auth.modular.login.entity.UserCollectLogin;
import com.unis.basic.info.modular.grainPriceCollect.param.GrainPriceCollectPageParam;
import com.unis.basic.info.modular.grainPriceCollectCitySum.entity.GrainPriceCollectCitySum;
import com.unis.basic.info.modular.unitInfo.entity.UnitInfo;
import com.unis.basic.info.modular.unitInfo.service.UnitInfoService;
import com.unis.policy.info.modular.auditRecord.entity.AuditRecord;
import com.unis.policy.info.modular.auditRecord.service.AuditRecordService;
import com.unis.policy.info.modular.auditRequest.entity.AuditRequest;
import com.unis.policy.info.modular.auditRequest.service.AuditRequestService;
import com.unis.policy.info.modular.sqrEnterprise.entity.SqrEnterprise;
import com.unis.policy.info.modular.sqrEnterprise.mapper.SqrEnterpriseMapper;
import com.unis.policy.info.modular.sqrEnterprise.service.SqrEnterpriseService;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;
import com.unis.policy.info.modular.sqrEnterpriseApply.entity.SqrEnterpriseApply;
import com.unis.policy.info.modular.sqrEnterpriseApply.mapper.SqrEnterpriseApplyMapper;
import com.unis.policy.info.modular.sqrEnterpriseApply.param.SqrEnterpriseApplyAddParam;
import com.unis.policy.info.modular.sqrEnterpriseApply.param.SqrEnterpriseApplyEditParam;
import com.unis.policy.info.modular.sqrEnterpriseApply.param.SqrEnterpriseApplyIdParam;
import com.unis.policy.info.modular.sqrEnterpriseApply.param.SqrEnterpriseApplyPageParam;
import com.unis.policy.info.modular.sqrEnterpriseApply.service.SqrEnterpriseApplyService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 承储资格认定-承储资格申请Service接口实现类
 *
 * @author hjc
 * @date  2024/04/28 15:45
 **/
@Service
public class SqrEnterpriseApplyServiceImpl extends ServiceImpl<SqrEnterpriseApplyMapper, SqrEnterpriseApply> implements SqrEnterpriseApplyService {

    @Resource
    private SqrEnterpriseService sqrEnterpriseService;

    @Resource
    private SqrEnterpriseMapper sqrEnterpriseMapper;

    @Resource
    private AuditRequestService auditRequestService;

    @Resource
    private AuditRecordService auditRecordService;

    @Resource
    private SqrEnterpriseApplyMapper sqrEnterpriseApplyMapper;

    @Override
    public Page<SqrEnterpriseApply> page(SqrEnterpriseApplyPageParam sqrEnterpriseApplyPageParam) {
        QueryWrapper<SqrEnterpriseApply> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(sqrEnterpriseApplyPageParam.getSortField(), sqrEnterpriseApplyPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(sqrEnterpriseApplyPageParam.getSortOrder());
            queryWrapper.orderBy(true, sqrEnterpriseApplyPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(sqrEnterpriseApplyPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(SqrEnterpriseApply::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(SqrEnterpriseApplyAddParam sqrEnterpriseApplyAddParam) {
        SqrEnterpriseApply sqrEnterpriseApply = BeanUtil.toBean(sqrEnterpriseApplyAddParam, SqrEnterpriseApply.class);
        this.save(sqrEnterpriseApply);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(SqrEnterpriseApplyEditParam sqrEnterpriseApplyEditParam) {
        SqrEnterpriseApply sqrEnterpriseApply =new SqrEnterpriseApply();

        if(sqrEnterpriseApplyEditParam.getId()!=null){
             sqrEnterpriseApply  = this.queryEntity(sqrEnterpriseApplyEditParam.getId());
            BeanUtil.copyProperties(sqrEnterpriseApplyEditParam, sqrEnterpriseApply);
            this.updateById(sqrEnterpriseApply);
        }else{

            BeanUtil.copyProperties(sqrEnterpriseApplyEditParam, sqrEnterpriseApply);
            this.save(sqrEnterpriseApply);
       }

        //保存和提交
        if(sqrEnterpriseApplyEditParam.getApplyStatus()==1){//提交
            AuditRequest auditRequest =new AuditRequest();
            auditRequest.setRequestId(sqrEnterpriseApply.getId()+"");
            auditRequest.setType(3);
            auditRequest.setStep(1);
            auditRequest.setAuditStatus(0);
            auditRequest.setCreateTime(new Date());
            auditRequest.setUpdateTime(new Date());
            auditRequestService.save(auditRequest);
            String id = auditRequest.getId();
            AuditRecord auditRecord = new AuditRecord();
            auditRecord.setAuditRequestId(id);
            auditRecord.setRequestId(sqrEnterpriseApply.getId()+"");
            auditRecord.setType(3);
            auditRecord.setStep(1);
            auditRecord.setAuditStatus(0);
            auditRecord.setCreateTime(new Date());
            auditRecord.setUpdateTime(new Date());
            auditRecordService.save(auditRecord);
        }


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<SqrEnterpriseApplyIdParam> sqrEnterpriseApplyIdParamList) {
        // 执行删除
        sqrEnterpriseService.removeById(sqrEnterpriseApplyIdParamList.get(0).getUnitInfoId());
        this.removeByIds(CollStreamUtil.toList(sqrEnterpriseApplyIdParamList, SqrEnterpriseApplyIdParam::getId));
    }

    @Override
    public SqrEnterpriseApply detail(SqrEnterpriseApplyIdParam sqrEnterpriseApplyIdParam) {
        QueryWrapper<SqrEnterpriseApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bgqa.id",sqrEnterpriseApplyIdParam.getId());
        //queryWrapper.eq("bui.id",sqrEnterpriseApplyIdParam.getUnitInfoId());
        queryWrapper.eq("bgqa.apply_type",sqrEnterpriseApplyIdParam.getApplyType());
        return  sqrEnterpriseApplyMapper.findById(sqrEnterpriseApplyIdParam.getUnitInfoId(),queryWrapper);
    }

    @Override
    public SqrEnterpriseApply queryEntity(String id) {
        SqrEnterpriseApply sqrEnterpriseApply = this.getById(id);
        if(ObjectUtil.isEmpty(sqrEnterpriseApply)) {
            throw new CommonException("承储资格证书补发申请不存在，id值为：{}", id);
        }
        return sqrEnterpriseApply;
    }

    @Override
    public IPage<Map<String, Object>> findByPage(SqrEnterpriseApplyPageParam sqrEnterpriseApplyPageParam) {
        //条形查询器
        QueryWrapper<SqrEnterpriseApply> queryWrapper = new QueryWrapper<>();
        //分页相关
        if(StringUtils.isNotBlank(sqrEnterpriseApplyPageParam.getDwmc())){
            queryWrapper.like("bui.dwmc",sqrEnterpriseApplyPageParam.getDwmc());
        }
            queryWrapper.eq("bgqa.apply_type",3);

        Page<SqrEnterpriseApply> p =new Page<>(sqrEnterpriseApplyPageParam.getCurrent(),sqrEnterpriseApplyPageParam.getSize());


        IPage<Map<String,Object>> page = sqrEnterpriseApplyMapper.selectMyMapsPage(p,queryWrapper);
        return page;
    }

    @Override
    public void updateStatus() {
        QueryWrapper<SqrEnterprise> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt("storage_expire_time", new Date());
        //查询
        List<SqrEnterprise> resultList = sqrEnterpriseMapper.selectList(queryWrapper);
        List<String> idsToUpdate = resultList.stream()
                                            .map(SqrEnterprise::getId)
                                            .collect(Collectors.toList());

        UpdateWrapper<SqrEnterprise> updateWrapper = new UpdateWrapper<>();
        // 设置要更新的状态字段
        updateWrapper.in("id", idsToUpdate).set("status", 3);

        // 执行批量更新
        sqrEnterpriseMapper.update(null, updateWrapper);

    }

}
