/*
 * 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.circulateMonitor.modular.easeEnterprise.service.impl;

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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.circulateMonitor.modular.goodEnterprise.entity.GoodEnterprise;
import com.unis.policy.info.modular.auditRecord.entity.AuditRecord;
import com.unis.policy.info.modular.auditRecord.mapper.AuditRecordMapper;
import com.unis.policy.info.modular.auditRequest.entity.AuditRequest;
import com.unis.policy.info.modular.auditRequest.mapper.AuditRequestMapper;
import org.apache.commons.lang3.StringUtils;
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.circulateMonitor.modular.easeEnterprise.entity.EaseEnterprise;
import com.unis.circulateMonitor.modular.easeEnterprise.mapper.EaseEnterpriseMapper;
import com.unis.circulateMonitor.modular.easeEnterprise.param.EaseEnterpriseAddParam;
import com.unis.circulateMonitor.modular.easeEnterprise.param.EaseEnterpriseEditParam;
import com.unis.circulateMonitor.modular.easeEnterprise.param.EaseEnterpriseIdParam;
import com.unis.circulateMonitor.modular.easeEnterprise.param.EaseEnterprisePageParam;
import com.unis.circulateMonitor.modular.easeEnterprise.service.EaseEnterpriseService;

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

/**
 * 放心粮油企业管理Service接口实现类
 *
 * @author QSHan
 * @date  2024/06/18 10:06
 **/
@Service
public class EaseEnterpriseServiceImpl extends ServiceImpl<EaseEnterpriseMapper, EaseEnterprise> implements EaseEnterpriseService {
    @Resource
    private EaseEnterpriseMapper easeEnterpriseMapper;
    @Resource
    private AuditRecordMapper auditRecordMapper;
    @Resource
    private AuditRequestMapper auditRequestMapper;

    @Override
    public Page<EaseEnterprise> page(EaseEnterprisePageParam easeEnterprisePageParam) {
        QueryWrapper<EaseEnterprise> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(easeEnterprisePageParam.getSortField(), easeEnterprisePageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(easeEnterprisePageParam.getSortOrder());
            queryWrapper.orderBy(true, easeEnterprisePageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(easeEnterprisePageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(EaseEnterprise::getId);
        }
        // 搜索条件
        if (StringUtils.isNotEmpty(easeEnterprisePageParam.getEnterpriseName())) {
            queryWrapper.like("gee.enterprise_name", easeEnterprisePageParam.getEnterpriseName());
        }
        if (StringUtils.isNotEmpty(easeEnterprisePageParam.getAdministrativeArea())) {
            queryWrapper.like("dd.DICT_LABEL", easeEnterprisePageParam.getAdministrativeArea())
                    .or().like("dd1.DICT_LABEL", easeEnterprisePageParam.getAdministrativeArea())
                    .or().like("dd2.DICT_LABEL", easeEnterprisePageParam.getAdministrativeArea())
                    .or().like("gee.enterprise_address", easeEnterprisePageParam.getAdministrativeArea());
        }
        return easeEnterpriseMapper.pageList(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(EaseEnterpriseAddParam easeEnterpriseAddParam) {
        EaseEnterprise easeEnterprise = BeanUtil.toBean(easeEnterpriseAddParam, EaseEnterprise.class);
        this.save(easeEnterprise);
        // 审批流程
        this.setAuditTable(easeEnterprise);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(EaseEnterpriseEditParam easeEnterpriseEditParam) {
        EaseEnterprise easeEnterprise = this.queryEntity(easeEnterpriseEditParam.getId());
        BeanUtil.copyProperties(easeEnterpriseEditParam, easeEnterprise);
        this.updateById(easeEnterprise);
        // 审批流程
        this.setAuditTable(easeEnterprise);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<EaseEnterpriseIdParam> easeEnterpriseIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(easeEnterpriseIdParamList, EaseEnterpriseIdParam::getId));
    }

    @Override
    public EaseEnterprise detail(EaseEnterpriseIdParam easeEnterpriseIdParam) {
        return this.queryEntity(easeEnterpriseIdParam.getId());
    }

    @SuppressWarnings("all")
    private void setAuditTable(EaseEnterprise easeEnterprise) {
        // 审批流程(状态->0:保存状态;1:提交(申请中);2:驳回;3:审核通过)
        if (0 != easeEnterprise.getStatus()) {
            QueryWrapper<AuditRequest> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(AuditRequest::getRequestId, easeEnterprise.getId());
            // 审批状态
            AuditRequest request = new AuditRequest();
            // 管理审批状态
            request.setRequestId(easeEnterprise.getId());
            // 好粮油标记
            request.setType(10);
            request.setStep(10);
            request.setAuditUserId(easeEnterprise.getCreateUser());
            // 状态 0:待审核;1:已审核;2:驳回
            if (1 == easeEnterprise.getStatus()) {
                request.setAuditStatus(0);
                request.setAuditAdvice("待审核");
                // 判断驳回再次提交
                AuditRequest request1 = auditRequestMapper.selectOne(wrapper);
                if (ObjectUtil.isNotEmpty(request1))
                    auditRequestMapper.update(request, wrapper);
                else
                    auditRequestMapper.insert(request);
            } else if (3 == easeEnterprise.getStatus()) {
                request.setAuditStatus(1);
                request.setAuditAdvice("审核通过");
                auditRequestMapper.update(request, wrapper);
            } else if (2 == easeEnterprise.getStatus()) {
                request.setAuditStatus(2);
                request.setAuditAdvice("驳回");
                auditRequestMapper.update(request, wrapper);
            }

            // 审批记录
            AuditRecord record = new AuditRecord();
            record.setRequestId(easeEnterprise.getId());
            record.setAuditStatus(request.getAuditStatus());
            record.setAuditRequestId(easeEnterprise.getId());
            record.setType(10);
            record.setStep(10);
            record.setAuditAdvice(request.getAuditAdvice());
            record.setAuditUserId(easeEnterprise.getCreateUser());
            auditRecordMapper.insert(record);
        }
    }

    @Override
    public EaseEnterprise queryEntity(String id) {
        EaseEnterprise easeEnterprise = this.getById(id);
        if(ObjectUtil.isEmpty(easeEnterprise)) {
            throw new CommonException("放心粮油企业管理不存在，id值为：{}", id);
        }
        return easeEnterprise;
    }

    @Override
    public List<Map<String, Object>> getEnterpriseList() {
        return easeEnterpriseMapper.getEnterpriseList();
    }

    @Override
    public Map<String, Object> getCountNumber() {
        return easeEnterpriseMapper.getCountNumber();
    }
}
