package com.casic.missiles.service.Impl.meter;

import cn.hutool.core.lang.Assert;
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.casic.missiles.core.application.service.AbstractDictService;
import com.casic.missiles.core.model.auth.AuthUser;
import com.casic.missiles.core.shiro.ShiroKit;
import com.casic.missiles.dto.BaseApprovalSubmitRequest;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.flowable.AllApproveDTO;
import com.casic.missiles.dto.flowable.ApprovalDeleteRequest;
import com.casic.missiles.dto.flowable.ToBeApprovedDTO;
import com.casic.missiles.dto.meter.FileApprovalListRequest;
import com.casic.missiles.dto.meter.FileApprovalListResponse;
import com.casic.missiles.dto.meter.FileListRequest;
import com.casic.missiles.dto.meter.FileSaveResponse;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
import com.casic.missiles.enums.meter.EffectiveStatusEnum;
import com.casic.missiles.enums.meter.MeterDictEnum;
import com.casic.missiles.enums.system.ApprovalStatusEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.meter.MeterFileMapper;
import com.casic.missiles.model.meter.MeterFile;
import com.casic.missiles.model.response.ResponseData;
import com.casic.missiles.service.IBaseApprovalService;
import com.casic.missiles.service.flowable.ApprovalOperateService;
import com.casic.missiles.service.meter.IMeterFileService;
import com.casic.missiles.utils.ConvertUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
import com.casic.missiles.utils.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 计量管理-计量文件-文件表 服务实现类
 * </p>
 *
 * @author wangpeng
 * @since 2022-11-22
 */
@Slf4j
@Service
public class MeterFileServiceImpl extends ServiceImpl<MeterFileMapper, MeterFile> implements IMeterFileService {
    @Resource
    private MeterFileMapper meterFileMapper;
    @Resource
    private AbstractDictService dictService;
    @Autowired
    private IBaseApprovalService baseApprovalService;
    @Autowired
    private ApprovalOperateService approvalOperateService;
    @Resource
    private TaskService taskService;
    @Resource
    private RuntimeService runtimeService;

    @Override
    public Page<MeterFile> listPage(Page<MeterFile> page, FileListRequest request) {
        QueryWrapper<MeterFile> wrapper = getWrapper(request);
        Page<MeterFile> meterFilePage = meterFileMapper.selectPage(page, wrapper);
        meterFilePage.getRecords().stream().forEach(result -> {
            result.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, result.getApprovalStatus()));
            result.setEffectiveStatusName(dictService.getDictNameByCode(MeterDictEnum.EFFECTIVE_STATUS, result.getEffectiveStatus()));
            result.setFileTypeName(dictService.getDictNameByCode(MeterDictEnum.FILE_TYPE, result.getFileType()));
        });
        return meterFilePage;
    }

    @Override
    public List<MeterFile> list(FileListRequest request) {
        QueryWrapper<MeterFile> wrapper = getWrapper(request);
        List<MeterFile> meterFiles = meterFileMapper.selectList(wrapper);
        meterFiles.forEach(result -> {
            result.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, result.getApprovalStatus()));
            result.setEffectiveStatusName(dictService.getDictNameByCode(MeterDictEnum.EFFECTIVE_STATUS, result.getEffectiveStatus()));
            result.setFileTypeName(dictService.getDictNameByCode(MeterDictEnum.FILE_TYPE, result.getFileType()));
        });
        return meterFiles;
    }

    @Override
    @Transactional
    public ReturnDTO<FileSaveResponse> saveFile(MeterFile file) {
        //生成文件编号
        Long maxNo = meterFileMapper.selectMaxFileNo();
        String fileNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.FILE_PREFIX, maxNo);
        file.setFileNo(fileNo);
        file.setApprovalStatus(ApprovalStatusEnum.DRAFT); //草稿箱状态
        Assert.isFalse(Objects.isNull(ShiroKit.getUser()), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        file.setCreateUserId(ShiroKit.getUser().getId()); //登录者用户id
        file.setCreateUser(ShiroKit.getUser().getName());
        int row = meterFileMapper.insert(file);

        if (row <= 0) {
            return ReturnUtil.failed("文件保存至草稿箱失败");
        }
        FileSaveResponse fileSaveResponse = new FileSaveResponse();
        fileSaveResponse.setId(file.getId());
        fileSaveResponse.setFileNo(fileNo);
        return ReturnUtil.success(fileSaveResponse);
    }

    @Override
    @Transactional
    public ReturnDTO submitFile(BaseApprovalSubmitRequest request) {
        //已取消后的提交需先删除原有实例
        if (StringUtils.isNotEmpty(request.getProcessId())){
            runtimeService.updateBusinessStatus(request.getProcessId(), ApprovalStatusEnum.DELETED);
            runtimeService.deleteProcessInstance(request.getProcessId(), "删除");
        }
        //1.根据表单id获取流程定义id
        //2.根据流程定义id启动流程实例
        String formId = request.getFormId();
        ReturnDTO returnDTO = baseApprovalService.processSubmit(formId, request.getId());
        if (ResponseData.DEFAULT_SUCCESS_CODE != returnDTO.getCode()) {
            return returnDTO;
        }
        ProcessInstance processInstance = (ProcessInstance) returnDTO.getData();

        MeterFile file = new MeterFile();
        file.setId(request.getId());
        file.setApprovalStatus(ApprovalStatusEnum.UN_DRAFT); //非草稿状态，保证数据从草稿中移除
        file.setProcessId(processInstance.getId());
        int row = meterFileMapper.updateById(file);

        if (row <= 0) {
            //保证flowable操作回滚，已验证成功
            throw new BusinessException(BusinessExceptionEnum.FILE_SUBMIT_FAILED.getCode(), BusinessExceptionEnum.FILE_SUBMIT_FAILED.getMessage());
        }
        return ReturnUtil.success();
    }

    @Override
    @Transactional
    public ReturnDTO draftUpdate(MeterFile file) {
        if (meterFileMapper.updateById(file) > 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    @Transactional
    public ReturnDTO updateFile(Long id) {
        //更新状态为已废止
        MeterFile file = new MeterFile();
        file.setId(id);
        file.setEffectiveStatus(EffectiveStatusEnum.REPEALED.getCode());
        if (meterFileMapper.updateById(file) > 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    @Transactional
    public ReturnDTO deleteFile(Long id) {
        if (meterFileMapper.deleteById(id) > 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    @Transactional
    public ReturnDTO deleteBatchFile(List<Long> ids) {
        if (meterFileMapper.deleteBatchIds(ids) >= 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public List<FileApprovalListResponse> approvalListPage(Page<FileApprovalListResponse> page, FileApprovalListRequest request) {
        //登录用户
        AuthUser user = ShiroKit.getUser();
        Assert.isFalse(Objects.isNull(user), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        request.setCreateUserId(user.getId());
        return handleApprovalStatus(page, request);
    }

    @Override
    @Transactional
    public ReturnDTO approvalDelete(ApprovalDeleteRequest request) {
        ReturnDTO returnDTO = approvalOperateService.delete(request);
        if (ResponseData.DEFAULT_SUCCESS_CODE == returnDTO.getCode()) {
            //本地删除
            if (meterFileMapper.deleteById(request.getId()) > 0) {
                return ReturnUtil.success();
            }
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    @Transactional
    public ReturnDTO failUpdate(MeterFile file) {
        AuthUser user = ShiroKit.getUser();
        Assert.isFalse(Objects.isNull(user), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        if (meterFileMapper.updateById(file) > 0) {
            baseApprovalService.failUpdate(file.getProcessId());
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    private List<FileApprovalListResponse> handleApprovalStatus(Page<FileApprovalListResponse> page, FileApprovalListRequest request) {
        List<FileApprovalListResponse> approvalList = new ArrayList<>();
        List<String> businessKeys = new ArrayList<>();
        List<MeterFile> list;
        //先查需要从flowable中查出的
        //状态维护放在flowable中比较好，保证flowable和业务中状态的一致性，否则更新业务状态有事务问题
        switch (request.getApprovalStatus()) {
            //草稿
            case ApprovalStatusEnum.DRAFT:
                list = meterFileMapper.selectDraftListForApproval(page, request);
                approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.DRAFT);
                break;
            //待审批，该状态维护在flowable中
            case ApprovalStatusEnum.TO_BE_APPROVED:
                List<ToBeApprovedDTO> toBeApprovedList = baseApprovalService.getToBeApprovedList(request.getFormId());
                if (!CollectionUtils.isEmpty(toBeApprovedList)) {
                    businessKeys = toBeApprovedList.stream().map(ToBeApprovedDTO::getBusinessKey).collect(Collectors.toList());
                }
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = meterFileMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.TO_BE_APPROVED);
                    //DTO根据业务主键补全taskId
                    approvalList.forEach(approval -> {
                        toBeApprovedList.forEach(toBeApprovedDTO -> {
                            if (String.valueOf(approval.getId()).equals(toBeApprovedDTO.getBusinessKey())) {
                                approval.setTaskId(toBeApprovedDTO.getTaskId());
                                //补全可选决策项
                                approval.setDecisionItem(toBeApprovedDTO.getDecisionItem());
                            }
                        });
                    });
                }
                break;
            //审批中，该状态维护在flowable中
            case ApprovalStatusEnum.IN_APPROVED:
                businessKeys = baseApprovalService.getInApprovedList(request.getFormId());
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = meterFileMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.IN_APPROVED);
                }
                break;
            //已通过，该状态维护在flowable
            case ApprovalStatusEnum.PASSED:
                businessKeys = baseApprovalService.getPassedList(request.getFormId());
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = meterFileMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.PASSED);
                }
                break;
            //未通过（包括拒绝、驳回，拒绝为直接删除实例，驳回为驳回到起点），该状态维护在flowable
            case ApprovalStatusEnum.FAILED:
                businessKeys = baseApprovalService.getFailedList(request.getFormId()); //未通过-拒绝
                List<String> rejectBusinessKey = baseApprovalService.getFailedRejectList(request.getFormId()); //未通过-驳回
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = meterFileMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.FAILED);
                }
                List<FileApprovalListResponse> rejectApprovalList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(rejectBusinessKey)) {
                    List<MeterFile> rejectList = meterFileMapper.selectBatchForApproval(page, request, rejectBusinessKey);
                    rejectApprovalList = handleApprovalListResponse(approvalList, rejectList, ApprovalStatusEnum.FAILED_REJECT);
                }
                //合并未通过-拒绝和未通过-驳回
                approvalList.addAll(rejectApprovalList);
                //分页处理
                if(!CollectionUtils.isEmpty(approvalList)) {
                    Page pages = PageUtil.getPages((int) page.getCurrent(), (int) page.getSize(), approvalList);
                    page.setTotal(approvalList.size());
                    approvalList = pages.getRecords();
                }
                break;
            //已取消，该状态维护在flowable
            case ApprovalStatusEnum.CANCELED:
                businessKeys = baseApprovalService.getCanceledList(request.getFormId());
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = meterFileMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.CANCELED);
                }
                break;
            //全部
            //区分管理员和普通用户
            //普通用户获取自己发起的(审批中、已通过、未通过、已取消)，管理员获取全部(审批中、已通过、未通过、已取消)
            case ApprovalStatusEnum.ALL:
                List<AllApproveDTO> AllApproveList = baseApprovalService.getAllList(request.getFormId());
                if (!CollectionUtils.isEmpty(AllApproveList)) {
                    businessKeys = AllApproveList.stream().map(AllApproveDTO::getBusinessKey).collect(Collectors.toList());
                }
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = meterFileMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleAllApprovalListResponse(approvalList, list, AllApproveList);
                }
                break;
        }
        return approvalList;
    }

    private List<FileApprovalListResponse> handleAllApprovalListResponse(List<FileApprovalListResponse> approvalList, List<MeterFile> list, List<AllApproveDTO> allApproveList) {
        Map<String, String> taskMap = new HashMap<>();
        approvalList = ConvertUtils.sourceToTarget(list, FileApprovalListResponse.class);
        allApproveList.forEach(allApprove -> {
            taskMap.put(allApprove.getBusinessKey(), allApprove.getStatus());
        });
        //状态补全
        approvalList.forEach(approval -> {
            approval.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, taskMap.get(String.valueOf(approval.getId()))));
            approval.setApprovalStatus(taskMap.get(String.valueOf(approval.getId())));
            approval.setEffectiveStatusName(dictService.getDictNameByCode(MeterDictEnum.EFFECTIVE_STATUS, approval.getEffectiveStatus()));
            approval.setFileTypeName(dictService.getDictNameByCode(MeterDictEnum.FILE_TYPE, approval.getFileType()));
        });
        //排序
        return approvalList.stream().sorted(Comparator.comparing(FileApprovalListResponse::getCreateTime).reversed()).collect(Collectors.toList());
    }

    private List<FileApprovalListResponse> handleApprovalListResponse(List<FileApprovalListResponse> approvalList, List<MeterFile> list, String status) {
        approvalList = ConvertUtils.sourceToTarget(list, FileApprovalListResponse.class);
        approvalList.stream().forEach(result -> {
            //审批状态两种获取方式：1、在此处设置，2、在flowable中设置业务状态，暂采取1
            result.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, status));
            result.setEffectiveStatusName(dictService.getDictNameByCode(MeterDictEnum.EFFECTIVE_STATUS, result.getEffectiveStatus()));
            result.setFileTypeName(dictService.getDictNameByCode(MeterDictEnum.FILE_TYPE, result.getFileType()));
        });
        return approvalList;
    }


    /***
     *查询文件为计量规程 和 已实施状态 的计量文件
     * @return
     */
    @Override
    public ReturnDTO querySelectList() {
        QueryWrapper<MeterFile> wrapper = new QueryWrapper<>();
        wrapper.eq("effective_status", "1");
        wrapper.eq("file_type", "10");
        return ReturnUtil.success(this.baseMapper.selectList(wrapper));
    }

    private QueryWrapper<MeterFile> getWrapper(FileListRequest request) {
        //flowable中已通过状态的业务id列表
        List<String> passedList = baseApprovalService.getPassedList(request.getFormId());

        QueryWrapper<MeterFile> wrapper = new QueryWrapper<>();
        //无审批通过则返回空数据
        if (CollectionUtils.isEmpty(passedList)) {
            wrapper.eq("id", 12344321);
            return wrapper;
        }
        wrapper.like(StringUtils.isNotBlank(request.getFileNo()), "file_no", request.getFileNo());
        wrapper.like(StringUtils.isNotBlank(request.getFileName()), "file_name", request.getFileName());
        wrapper.like(StringUtils.isNotBlank(request.getFileCode()), "file_code", request.getFileCode());
        wrapper.like(StringUtils.isNotBlank(request.getFileType()), "file_type", request.getFileType());
        wrapper.like(!Objects.isNull(request.getEffectiveStatus()), "effective_status", request.getEffectiveStatus());
        wrapper.apply(StringUtils.isNotBlank(request.getPublishStartTime()),//apply方法传入参数名不能为空
                "{0} <= DATE_FORMAT(publish_time,'%Y-%m-%d')", request.getPublishStartTime().split(" ")[0]);
        wrapper.apply(StringUtils.isNotBlank(request.getPublishEndTime()),
                "{0} >= DATE_FORMAT(publish_time,'%Y-%m-%d')", request.getPublishEndTime().split(" ")[0]);
        wrapper.apply(StringUtils.isNotBlank(request.getEffectiveStartTime()),
                "{0} <= DATE_FORMAT(effective_time,'%Y-%m-%d')", request.getEffectiveStartTime().split(" ")[0]);
        wrapper.apply(StringUtils.isNotBlank(request.getEffectiveEndTime()),
                "{0} >= DATE_FORMAT(effective_time,'%Y-%m-%d')", request.getEffectiveEndTime().split(" ")[0]);
        wrapper.in("id", passedList);
        wrapper.eq("is_del", 0);
        wrapper.orderByAsc("effective_status").orderByDesc("create_time");
        return wrapper;
    }


    @Override
    public List<MeterFile> list(List<Long> ids) {
        return this.baseMapper.selectBatchIds(ids);
    }
}
