/*
 * 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.alPolicyFileReport.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.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.unis.auth.core.pojo.SaBaseLoginUser;
import com.unis.auth.core.util.StpClientUtil;
import com.unis.auth.core.util.StpLoginUserUtil;
import com.unis.auth.modular.login.entity.UserCollectLogin;
import com.unis.basic.info.modular.grainPriceCollect.entity.GrainPriceCollect;
import com.unis.basic.info.modular.grainPriceCollect.param.GrainPriceCollectPageParam;
import com.unis.basic.info.modular.grainPriceCollectCitySum.entity.GrainPriceCollectCitySum;
import com.unis.policy.info.modular.alPolicyFileReport.enums.AlPolicyFileReportStatusEnum;
import com.unis.policy.info.modular.auditRequest.entity.AuditRequest;
import com.unis.policy.info.modular.auditRequest.service.AuditRequestService;
import com.unis.sys.modular.org.entity.SysOrg;
import com.unis.sys.modular.org.service.SysOrgService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.alPolicyFileReport.entity.AlPolicyFileReport;
import com.unis.policy.info.modular.alPolicyFileReport.mapper.AlPolicyFileReportMapper;
import com.unis.policy.info.modular.alPolicyFileReport.param.AlPolicyFileReportAddParam;
import com.unis.policy.info.modular.alPolicyFileReport.param.AlPolicyFileReportEditParam;
import com.unis.policy.info.modular.alPolicyFileReport.param.AlPolicyFileReportIdParam;
import com.unis.policy.info.modular.alPolicyFileReport.param.AlPolicyFileReportPageParam;
import com.unis.policy.info.modular.alPolicyFileReport.service.AlPolicyFileReportService;

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

/**
 * 行政法规管理-政策规范性文件申报Service接口实现类
 *
 * @author TS
 * @date  2024/04/18 15:02
 **/
@Service
public class AlPolicyFileReportServiceImpl extends ServiceImpl<AlPolicyFileReportMapper, AlPolicyFileReport> implements AlPolicyFileReportService {

    @Resource
    private AlPolicyFileReportMapper alPolicyFileReportMapper;

    @Autowired
    private SysOrgService sysOrgService;

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

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(AlPolicyFileReportAddParam alPolicyFileReportAddParam) {
        AlPolicyFileReport alPolicyFileReport = BeanUtil.toBean(alPolicyFileReportAddParam, AlPolicyFileReport.class);
        this.save(alPolicyFileReport);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(AlPolicyFileReportEditParam alPolicyFileReportEditParam) {
        AlPolicyFileReport alPolicyFileReport = this.getById(alPolicyFileReportEditParam.getId());
        if(ObjectUtil.isEmpty(alPolicyFileReport)) {
            throw new CommonException("政策规范性文件不存在，id值为：{}", alPolicyFileReport.getId());
        }
        //表示已发起流程
        if(alPolicyFileReport.getStatus() == 1 ) {
            throw new CommonException("政策规范性文件已发起流程，id值为：{}", alPolicyFileReport.getId());
        }
        BeanUtil.copyProperties(alPolicyFileReportEditParam, alPolicyFileReport);
        this.updateById(alPolicyFileReport);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(AlPolicyFileReportIdParam alPolicyFileReportIdParam) {
        AlPolicyFileReport alPolicyFileReport = this.queryEntity(alPolicyFileReportIdParam.getId());
        if(ObjectUtil.isEmpty(alPolicyFileReport)) {
            throw new CommonException("政策规范性文件不存在，id值为：{}", alPolicyFileReport.getId());
        }
        //表示已发起流程
        if(alPolicyFileReport.getStatus() == 1 ) {
            throw new CommonException("政策规范性文件已发起流程，id值为：{}", alPolicyFileReport.getId());
        }
        // 执行删除
        this.removeById(alPolicyFileReportIdParam.getId());
    }

    @Override
    public AlPolicyFileReport detail(AlPolicyFileReportIdParam alPolicyFileReportIdParam) {
        return this.queryEntity(alPolicyFileReportIdParam.getId());
    }

    @Override
    public AlPolicyFileReport queryEntity(String id) {
        AlPolicyFileReport alPolicyFileReport = this.getById(id);
        if(ObjectUtil.isEmpty(alPolicyFileReport)) {
            throw new CommonException("行政法规管理-政策规范性文件申报不存在，id值为：{}", id);
        }
        //设置申请部门名称
        SysOrg sysOrg = sysOrgService.queryEntity(alPolicyFileReport.getSysOrgId());
        alPolicyFileReport.setSysOrgName(sysOrg.getName());
        return alPolicyFileReport;
    }

    /**
     * 获取行政法规管理-政策规范性文件申报自定义分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<Map<String, Object>> findPage(AlPolicyFileReportPageParam pageParam) {
        //条形查询器
        QueryWrapper<AlPolicyFileReport> queryWrapper = new QueryWrapper<>();


        //分页相关



        if(StringUtils.isNotBlank(pageParam.getReporter())){
            queryWrapper.like("a.reporter",pageParam.getReporter() );
        }
        if(StringUtils.isNotBlank(pageParam.getSysOrgName())){
            queryWrapper.like("b.name",pageParam.getSysOrgName() );
        }
        //1合法性审核 ；2:过会审核：3:行政文件申报；
        if (StringUtils.isNotBlank(pageParam.getPolicyType())){
            if (StringUtils.equals("1",pageParam.getPolicyType())){
                queryWrapper.eq("a.status","1" ); //表示申报发起流程
                if (StringUtils.isNotBlank(pageParam.getAuditTime()) ) {
                    queryWrapper.apply("  DATE_FORMAT(ifnull(c.audit_time,NOW()),'%Y-%m-%d') =  '" + pageParam.getAuditTime()+"'" );
                }
            }else if(StringUtils.equals("2",pageParam.getPolicyType())){
                queryWrapper.eq("a.status","1" ); //表示申报发起流程
                if (StringUtils.isNotBlank(pageParam.getAuditTime()) ) {
                    queryWrapper.apply("  DATE_FORMAT(ifnull(d.audit_time,NOW()),'%Y-%m-%d') =  '" + pageParam.getAuditTime()+"'" );
                }

            }
        }else {
            pageParam.setPolicyType("3");
        }
        if (StringUtils.isNotBlank(pageParam.getReportDate()) ) {
            queryWrapper.apply("  DATE_FORMAT(ifnull(a.report_date,NOW()),'%Y-%m-%d') =  '" + pageParam.getReportDate()+"'" );
        }


        Page<GrainPriceCollectCitySum> p =new Page<>(pageParam.getCurrent(),pageParam.getSize());
        IPage<Map<String,Object>> page = alPolicyFileReportMapper.selectMyMapsPage(p,queryWrapper,Integer.parseInt(pageParam.getPolicyType()));
        return page;
    }

    /**
     * 发起行政法规管理-政策规范性文件申报流程
     *
     * @param alPolicyFileReportIdParam
     * @return
     */
    @Override
    public String startFlow(AlPolicyFileReportIdParam alPolicyFileReportIdParam) {
        AlPolicyFileReport alPolicyFileReport = this.queryEntity(alPolicyFileReportIdParam.getId());
        if(ObjectUtil.isEmpty(alPolicyFileReport)) {
            throw new CommonException("政策规范性文件不存在，id值为：{}", alPolicyFileReport.getId());
        }
        //表示已发起流程
        if(alPolicyFileReport.getStatus() == 1 ) {
            throw new CommonException("政策规范性文件已发起流程，id值为：{}", alPolicyFileReport.getId());
        }
        //启动合法性审核流程
        alPolicyFileReport.setStatus(Integer.parseInt(AlPolicyFileReportStatusEnum.Start.getValue()));
        alPolicyFileReport.setLaunchTime(new Date()); //设置发起时间
        return this.updateById(alPolicyFileReport)?"启动成功":"启动失败";
    }

    /**
     * 获取行政法规管理-政策规范性文件申报部门
     * @return
     */
    @Override
    public List<SysOrg> getReportDepts() {
        LambdaQueryWrapper<SysOrg> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(SysOrg::getParentId,"1774729858638458882"); //青海省
        lambdaQuery.eq(SysOrg::getCategory,"DEPT"); //部门
        return sysOrgService.list(lambdaQuery);
    }

    /**
     * 获取行政法规管理-政策规范性文件申报下拉列表数据
     *
     * @return
     */
    @Override
    public List<Map<String,Object>> getReportsByCurUser() {
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        //条形查询器
        QueryWrapper<AlPolicyFileReport> queryWrapper = new QueryWrapper<>();

        if(loginUserDataScope.size() > 0){
            queryWrapper.in("a.sys_org_id",loginUserDataScope );
        }
        return alPolicyFileReportMapper.getReportsByCurUser(queryWrapper);
    }

}
