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

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.business.outsource.OutsourcerApprovalListRequest;
import com.casic.missiles.dto.business.outsource.OutsourcerApprovalListResponse;
import com.casic.missiles.dto.business.outsource.OutsourcerListRequest;
import com.casic.missiles.dto.business.outsource.OutsourcerSaveResponse;
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.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
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.business.BusinessOutsourcerInfoMapper;
import com.casic.missiles.model.business.BusinessOutsourcerInfo;
import com.casic.missiles.model.response.ResponseData;
import com.casic.missiles.service.IBaseApprovalService;
import com.casic.missiles.service.business.IBusinessOutsourcerInfoService;
import com.casic.missiles.service.flowable.ApprovalOperateService;
import com.casic.missiles.utils.ConvertUtils;
import com.casic.missiles.utils.DictCodeUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
import com.casic.missiles.utils.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.RuntimeService;
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 javax.validation.ConstraintViolation;
import javax.validation.Validation;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 分包方 服务实现类
 * </p>
 *
 * @author wangpeng
 * @since 2023-03-23
 */
@Service
public class BusinessOutsourcerInfoServiceImpl extends ServiceImpl<BusinessOutsourcerInfoMapper, BusinessOutsourcerInfo> implements IBusinessOutsourcerInfoService {
    @Autowired
    private IBaseApprovalService baseApprovalService;
    @Autowired
    private BusinessOutsourcerInfoMapper outsourcerInfoMapper;
    @Resource
    private AbstractDictService dictService;
    @Resource
    private RuntimeService runtimeService;
    @Autowired
    private ApprovalOperateService approvalOperateService;

    @Override
    public Page<BusinessOutsourcerInfo> listPage(Page<BusinessOutsourcerInfo> page, OutsourcerListRequest request) throws Exception {
        QueryWrapper<BusinessOutsourcerInfo> wrapper = getWrapper(request);
        Page<BusinessOutsourcerInfo> infoPage = outsourcerInfoMapper.selectPage(page, wrapper);
        if(Objects.isNull(infoPage) || CollectionUtils.isEmpty(infoPage.getRecords())){
            return new Page<>();
        }
        for (BusinessOutsourcerInfo record : infoPage.getRecords()) {
            DictCodeUtils.convertDictCodeToName(record);
        }
        return infoPage;
    }

    @Override
    public List<BusinessOutsourcerInfo> list(OutsourcerListRequest request) {
        QueryWrapper<BusinessOutsourcerInfo> wrapper = getWrapper(request);
        return outsourcerInfoMapper.selectList(wrapper);
    }

    @Override
    public List<OutsourcerApprovalListResponse> outsourcerApprovalListPage(OutsourcerApprovalListRequest request, Page<OutsourcerApprovalListResponse> page) throws Exception {
        AuthUser user = ShiroKit.getUser();
        Assert.isFalse(Objects.isNull(user), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        request.setCreateUserId(user.getId());
        List<OutsourcerApprovalListResponse> responseList = handleApprovalStatus(page, request);
        if(CollectionUtils.isEmpty(responseList)){
            return new ArrayList<>();
        }
        for (OutsourcerApprovalListResponse response : responseList) {
            DictCodeUtils.convertDictCodeToName(response);
        }
        return responseList;
    }

    @Override
    @Transactional
    public ReturnDTO addBusinessOutsourcerList(List<BusinessOutsourcerInfo> list) throws Exception {
        //用于存储验证后的错误信息
        Long maxNo = outsourcerInfoMapper.selectMaxOutsourcerNo();
        for (BusinessOutsourcerInfo item : list) {
            Set<ConstraintViolation<BusinessOutsourcerInfo>> validate = Validation.buildDefaultValidatorFactory().getValidator().validate(item);
            if (!CollectionUtils.isEmpty(validate)) {
                return ReturnUtil.failed(validate.iterator().next().getMessage());
            }
            DictCodeUtils.validDictCode(item);
            //生成编号
            String outsourcerNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.OUTSOURCER_PREFIX, maxNo);
            item.setOutsourcerNo(outsourcerNo);
            maxNo++;
        }
        super.saveBatch(list);
        return ReturnUtil.success();
    }

    @Override
    @Transactional
    public ReturnDTO<OutsourcerSaveResponse> saveOutsourcer(BusinessOutsourcerInfo outsourcerInfo) {
        //生成编号
        Long maxNo = outsourcerInfoMapper.selectMaxOutsourcerNo();
        String outsourcerNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.OUTSOURCER_PREFIX, maxNo);
        outsourcerInfo.setOutsourcerNo(outsourcerNo);
        outsourcerInfo.setApprovalStatus(ApprovalStatusEnum.DRAFT); //草稿箱状态
        Assert.isFalse(Objects.isNull(ShiroKit.getUser()), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        outsourcerInfo.setCreateUser(ShiroKit.getUser().getId()); //登录者用户id
        int insertFlag = outsourcerInfoMapper.insert(outsourcerInfo);
        Assert.isFalse(insertFlag <= 0, () -> {
            throw new BusinessException(BusinessExceptionEnum.OUTSOURCER_SAVE_FAILED);
        });
        OutsourcerSaveResponse saveResponse = new OutsourcerSaveResponse();
        saveResponse.setId(outsourcerInfo.getId());
        saveResponse.setOutsourcerNo(outsourcerNo);
        return ReturnUtil.success(saveResponse);
    }

    @Override
    @Transactional
    public ReturnDTO draftUpdate(BusinessOutsourcerInfo outsourcerInfo) {
        int updateFlag = outsourcerInfoMapper.updateById(outsourcerInfo);
        if (updateFlag > 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    @Transactional
    public ReturnDTO submitOutsourcer(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();

        BusinessOutsourcerInfo outsourcerInfo = new BusinessOutsourcerInfo();
        outsourcerInfo.setId(request.getId());
        outsourcerInfo.setApprovalStatus(ApprovalStatusEnum.UN_DRAFT); //非草稿状态
        outsourcerInfo.setProcessId(processInstance.getId());
        int row = outsourcerInfoMapper.updateById(outsourcerInfo);
        if (row <= 0) {
            throw new BusinessException(BusinessExceptionEnum.OUTSOURCER_SUBMIT_FAILED);
        }
        return ReturnUtil.success();
    }

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

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

    @Override
    public ReturnDTO<BusinessOutsourcerInfo> outsourcerDetail(Long id) throws Exception {
        BusinessOutsourcerInfo detailResponse = outsourcerInfoMapper.selectById(id);
        if(Objects.isNull(detailResponse)){
            return ReturnUtil.success();
        }
        DictCodeUtils.convertDictCodeToName(detailResponse);
        return ReturnUtil.success(detailResponse);
    }

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

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

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

        QueryWrapper<BusinessOutsourcerInfo> wrapper = new QueryWrapper<>();
        //无审批通过则返回空数据
        if (CollectionUtils.isEmpty(passedList)) {
            //保证批量导入的可以查询到
            passedList.add("xxx");
        }
        wrapper.like(StringUtils.isNotBlank(request.getOutsourcerNo()), "outsourcer_no", request.getOutsourcerNo());
        wrapper.like(StringUtils.isNotBlank(request.getOutsourcerName()), "outsourcer_name", request.getOutsourcerName());
        wrapper.like(StringUtils.isNotBlank(request.getBusinessSize()), "business_size", request.getBusinessSize());
        wrapper.like(StringUtils.isNotBlank(request.getGrade()), "grade", request.getGrade());
        wrapper.and(QueryWrapper -> QueryWrapper.in("id", passedList).or().isNull("approval_status"));
        wrapper.eq("is_del", 0);
        wrapper.orderByDesc("create_time");
        return wrapper;
    }

    private List<OutsourcerApprovalListResponse> handleApprovalStatus(Page<OutsourcerApprovalListResponse> page, OutsourcerApprovalListRequest request) {
        List<OutsourcerApprovalListResponse> approvalList = new ArrayList<>();
        List<String> businessKeys = new ArrayList<>();
        List<BusinessOutsourcerInfo> list;
        switch (request.getApprovalStatus()) {
            //草稿
            case ApprovalStatusEnum.DRAFT:
                list = outsourcerInfoMapper.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).distinct().collect(Collectors.toList());
                }
                if (!CollectionUtils.isEmpty(businessKeys)) {
                    list = outsourcerInfoMapper.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 = outsourcerInfoMapper.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 = outsourcerInfoMapper.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 = outsourcerInfoMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.FAILED);
                }
                List<OutsourcerApprovalListResponse> rejectApprovalList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(rejectBusinessKey)) {
                    List<BusinessOutsourcerInfo> rejectList = outsourcerInfoMapper.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 = outsourcerInfoMapper.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 = outsourcerInfoMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleAllApprovalListResponse(approvalList, list, AllApproveList);
                }
                break;
        }
        return approvalList;
    }

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

    private List<OutsourcerApprovalListResponse> handleAllApprovalListResponse(List<OutsourcerApprovalListResponse> approvalList, List<BusinessOutsourcerInfo> list, List<AllApproveDTO> allApproveList) {
        Map<String, String> taskMap = new HashMap<>();
        approvalList = ConvertUtils.sourceToTarget(list, OutsourcerApprovalListResponse.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())));
        });
        //排序
        return approvalList.stream().sorted(Comparator.comparing(OutsourcerApprovalListResponse::getCreateTime).reversed()).collect(Collectors.toList());
    }
}
