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.*;
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.meter.MeterStaffMapper;
import com.casic.missiles.mapper.meter.MeterTrainPlanMapper;
import com.casic.missiles.mapper.meter.MeterTrainStaffMapper;
import com.casic.missiles.model.meter.MeterStaff;
import com.casic.missiles.model.meter.MeterTrainPlan;
import com.casic.missiles.model.meter.MeterTrainStaff;
import com.casic.missiles.model.response.ResponseData;
import com.casic.missiles.modular.system.model.Dept;
import com.casic.missiles.modular.system.service.IDeptService;
import com.casic.missiles.service.IBaseApprovalService;
import com.casic.missiles.service.flowable.ApprovalOperateService;
import com.casic.missiles.service.meter.IMeterTrainPlanService;
import com.casic.missiles.service.meter.IMeterTrainStaffService;
import com.casic.missiles.utils.ConvertUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
import com.casic.missiles.utils.PageUtil;
import com.casic.missiles.utils.QRCodeUtil;
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-23
 */
@Service
public class MeterTrainPlanServiceImpl extends ServiceImpl<MeterTrainPlanMapper, MeterTrainPlan> implements IMeterTrainPlanService {
    @Autowired
    private MeterTrainPlanMapper trainPlanMapper;
    @Autowired
    private MeterTrainStaffMapper trainStaffMapper;
    @Autowired
    private IMeterTrainStaffService trainStaffService;
    @Resource
    private AbstractDictService dictService;
    @Resource
    private IDeptService deptService;
    @Autowired
    private IBaseApprovalService baseApprovalService;
    @Autowired
    private ApprovalOperateService approvalOperateService;
    @Resource
    private TaskService taskService;
    @Resource
    private RuntimeService runtimeService;
    @Autowired
    private MeterStaffMapper staffMapper;

    @Override
    public Page<MeterTrainPlan> listPage(Page<MeterTrainPlan> page, TrainPlanListRequest request) {
        QueryWrapper<MeterTrainPlan> wrapper = getWrapper(request);
        Page<MeterTrainPlan> trainPlanPage = trainPlanMapper.selectPage(page, wrapper);
        trainPlanPage.getRecords().stream().forEach(result -> {
//            result.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, result.getApprovalStatus()));
            Dept dept = deptService.getById(result.getDeptId());
            if(!Objects.isNull(dept)){
                result.setDeptName(dept.getSimpleName());
            }
        });
        return trainPlanPage;
    }

    @Override
    @Transactional
    public ReturnDTO<TrainPlanSaveResponse> saveTrainPlan(MeterTrainPlan trainPlan) {
        //生成编号
        Long maxNo = trainPlanMapper.selectMaxTrainPlanNo();
        String planNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.TRAIN_PLAN_PREFIX, maxNo);
        trainPlan.setPlanNo(planNo);
        trainPlan.setApprovalStatus(ApprovalStatusEnum.DRAFT); //草稿箱状态
        Assert.isFalse(Objects.isNull(ShiroKit.getUser()), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        trainPlan.setCreateUserId(ShiroKit.getUser().getId()); //登录者用户id
        int row = trainPlanMapper.insert(trainPlan);
        Assert.isFalse(row <= 0, () -> {
            throw new BusinessException(BusinessExceptionEnum.TRAIN_PLAN_SAVE_FAILED);
        });
        //存储培训人员信息
        boolean saveBatchFlag = true;
        List<MeterTrainStaff> trainPlanStaffList = trainPlan.getTrainStaffList();
        if(!CollectionUtils.isEmpty(trainPlanStaffList)){
            trainPlanStaffList.forEach(person -> {
                person.setPlanId(trainPlan.getId());
            });
            saveBatchFlag = trainStaffService.saveBatch(trainPlanStaffList);
        }
        Assert.isFalse(!saveBatchFlag, () -> {
            throw new BusinessException(BusinessExceptionEnum.TRAIN_PLAN_SAVE_FAILED);
        });
        TrainPlanSaveResponse planSaveResponse = new TrainPlanSaveResponse();
        planSaveResponse.setId(trainPlan.getId());
        planSaveResponse.setPlanNo(planNo);
        return ReturnUtil.success(planSaveResponse);
    }

    @Override
    public List<MeterTrainPlan> planList(TrainPlanListRequest request) {
        QueryWrapper<MeterTrainPlan> wrapper = getWrapper(request);
        List<MeterTrainPlan> trainPlans = trainPlanMapper.selectList(wrapper);
        trainPlans.stream().forEach(result -> {
//            result.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, result.getApprovalStatus()));
            Dept dept = deptService.getById(result.getDeptId());
            if(!Objects.isNull(dept)){
                result.setDeptName(dept.getSimpleName());
            }
        });
        return trainPlans;
    }

    @Override
    @Transactional
    public ReturnDTO draftUpdate(MeterTrainPlan trainPlan) {
        int updateFlag = trainPlanMapper.updateById(trainPlan);
        QueryWrapper<MeterTrainStaff> wrapper = new QueryWrapper<>();
        wrapper.eq("plan_id", trainPlan.getId());
        //培训计划中人员肯定不空，且详情中返回无id，保证逻辑删除和添加主键不冲突
        //先删除再增加
        boolean removeFlag = trainStaffService.remove(wrapper);
        boolean saveFlag = trainStaffService.saveBatch(trainPlan.getTrainStaffList());
        if(updateFlag > 0 && removeFlag && saveFlag){
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public List<TrainPlanApprovalListResponse> approvalListPage(Page<TrainPlanApprovalListResponse> page, TrainPlanApprovalListRequest 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
    public ReturnDTO approvalDelete(ApprovalDeleteRequest request) {
        ReturnDTO returnDTO = approvalOperateService.delete(request);
        if(ResponseData.DEFAULT_SUCCESS_CODE == returnDTO.getCode()){
            //本地删除
            if(trainPlanMapper.deleteById(request.getId()) > 0){
                return ReturnUtil.success();
            }
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

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

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

        MeterTrainPlan trainPlan = new MeterTrainPlan();
        trainPlan.setId(request.getId());
        trainPlan.setApprovalStatus(ApprovalStatusEnum.UN_DRAFT); //非草稿状态
        trainPlan.setProcessId(processInstance.getId());
        int row = trainPlanMapper.updateById(trainPlan);
        if (row <= 0) {
            throw new BusinessException(BusinessExceptionEnum.TRAIN_PLAN_SUBMIT_FAILED.getCode(), BusinessExceptionEnum.TRAIN_PLAN_SUBMIT_FAILED.getMessage());
        }
        return ReturnUtil.success();
    }

    @Override
    @Transactional
    public ReturnDTO updateTrainPlan(MeterTrainPlan meterTrainPlan) {
//        int updateFlag = trainPlanMapper.updateById(meterTrainPlan);
//        boolean saveOrUpdateFlag = trainStaffService.saveOrUpdateBatch(meterTrainPlan.getTrainStaffList());
//        if(updateFlag > 0 && saveOrUpdateFlag){
//            return ReturnUtil.success();
//        }
//        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
        return null;
    }

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

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

    @Override
    public ReturnDTO<TrainPlanDetailResponse> trainPlanDetail(Long id) {
        TrainPlanDetailResponse planResponse = trainPlanMapper.selectTrainPlanById(id);
        return ReturnUtil.success(planResponse);
    }

    @Override
    public ReturnDTO<TrainPlanDetailResponse> planQrCode(Long id) {
        String base64QRCode = QRCodeUtil.getBase64QRCode(String.valueOf(id));
        return ReturnUtil.success(base64QRCode);
    }

    @Override
    public ReturnDTO<TrainPlanDetailResponse> signIn(TrainPlanSignInRequest request) {
        AuthUser user = ShiroKit.getUser();
        Assert.isFalse(Objects.isNull(user), () -> {
            throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED);
        });
        //登录用户id获取转换计量人员id，实验室检测信息中存储的是计量人员id
        MeterStaff meterStaff = getMeterStaffInfo(user);
        if(Objects.isNull(meterStaff)) throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_NOT_STAFF);
        Long userId = meterStaff.getId();
        request.setStaffId(userId);
        //更新培训计划员工考核结果
        int updateFlag = trainStaffMapper.updateStaffForSignIn(request);
        if(updateFlag > 0){
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    private List<TrainPlanApprovalListResponse> handleApprovalStatus(Page<TrainPlanApprovalListResponse> page, TrainPlanApprovalListRequest request) {
        List<TrainPlanApprovalListResponse> approvalList = new ArrayList<>();
        List<String> businessKeys = new ArrayList<>();
        List<MeterTrainPlan> list;
        //先查需要从flowable中查出的
        //状态维护放在flowable中比较好，保证flowable和业务中状态的一致性，否则更新业务状态有事务问题
        switch (request.getApprovalStatus()) {
            //草稿
            case ApprovalStatusEnum.DRAFT:
                list = trainPlanMapper.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 = trainPlanMapper.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 = trainPlanMapper.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 = trainPlanMapper.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 = trainPlanMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleApprovalListResponse(approvalList, list, ApprovalStatusEnum.FAILED);
                }
                List<TrainPlanApprovalListResponse> rejectApprovalList = new ArrayList<>();
                if(!CollectionUtils.isEmpty(rejectBusinessKey)){
                    List<MeterTrainPlan> rejectList = trainPlanMapper.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 = trainPlanMapper.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 = trainPlanMapper.selectBatchForApproval(page, request, businessKeys);
                    approvalList = handleAllApprovalListResponse(approvalList, list, AllApproveList);
                }
                break;
        }
        return approvalList;
    }

    private List<TrainPlanApprovalListResponse> handleAllApprovalListResponse(List<TrainPlanApprovalListResponse> approvalList, List<MeterTrainPlan> list, List<AllApproveDTO> allApproveList) {
        Map<String,String> taskMap = new HashMap<>();
        approvalList = ConvertUtils.sourceToTarget(list, TrainPlanApprovalListResponse.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())));
            Dept dept = deptService.getById(approval.getDeptId());
            if(!Objects.isNull(dept)){
                approval.setDeptName(dept.getSimpleName());
            }
        });
        //排序
        return approvalList.stream().sorted(Comparator.comparing(TrainPlanApprovalListResponse::getCreateTime).reversed()).collect(Collectors.toList());
    }

    private List<TrainPlanApprovalListResponse> handleApprovalListResponse(List<TrainPlanApprovalListResponse> approvalList, List<MeterTrainPlan> list, String status){
        approvalList = ConvertUtils.sourceToTarget(list, TrainPlanApprovalListResponse.class);
        approvalList.stream().forEach(result -> {
            //审批状态两种获取方式：1、在此处设置，2、在flowable中设置业务状态，暂采取1
            result.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, status));
            Dept dept = deptService.getById(result.getDeptId());
            if(!Objects.isNull(dept)){
                result.setDeptName(dept.getSimpleName());
            }
        });
        return approvalList;
    }

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

        QueryWrapper<MeterTrainPlan> wrapper = new QueryWrapper<>();
        //无审批通过则返回空数据
        if (CollectionUtils.isEmpty(passedList)) {
            wrapper.eq("id", 12344321);
            return wrapper;
        }
        wrapper.like(StringUtils.isNotBlank(request.getPlanNo()), "plan_no", request.getPlanNo());
        wrapper.like(StringUtils.isNotBlank(request.getPlanName()), "plan_name", request.getPlanName());
        wrapper.like(StringUtils.isNotBlank(request.getDirector()), "director", request.getDirector());
        wrapper.like(StringUtils.isNotBlank(request.getEffectiveCompany()), "effective_company", request.getEffectiveCompany());
        wrapper.eq(Objects.nonNull(request.getDeptId()), "dept_id", request.getDeptId());
        wrapper.apply(StringUtils.isNotBlank(request.getTrainStartTime()),//apply方法传入参数名不能为空
                "{0} <= DATE_FORMAT(train_time,'%Y-%m-%d')", request.getTrainStartTime().split(" ")[0]);
        wrapper.apply(StringUtils.isNotBlank(request.getTrainEndTime()),
                "{0} >= DATE_FORMAT(train_time,'%Y-%m-%d')", request.getTrainEndTime().split(" ")[0]);
        wrapper.apply(StringUtils.isNotBlank(request.getCreateStartTime()),
                "{0} <= DATE_FORMAT(create_time,'%Y-%m-%d')", request.getCreateStartTime().split(" ")[0]);
        wrapper.apply(StringUtils.isNotBlank(request.getCreateEndTime()),
                "{0} >= DATE_FORMAT(create_time,'%Y-%m-%d')", request.getCreateEndTime().split(" ")[0]);
        wrapper.in("id", passedList);
        wrapper.eq("is_del", 0);
        wrapper.orderByDesc("train_time").orderByDesc("create_time");
        return wrapper;
    }

    private MeterStaff getMeterStaffInfo(AuthUser user) {
        String account = user.getAccount();
        QueryWrapper<MeterStaff> wrapper = new QueryWrapper<>();
        wrapper.eq("account", account);
        return staffMapper.selectOne(wrapper);
    }
}
