package com.ruoyi.zzb.dbjz.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.zzb.common.domain.BaseApproveInfo;
import com.ruoyi.zzb.common.domain.BaseFileInfo;
import com.ruoyi.zzb.common.mapper.BaseApproveInfoMapper;
import com.ruoyi.zzb.common.mapper.BaseFileInfoMapper;
import com.ruoyi.zzb.common.service.BaseService;
import com.ruoyi.zzb.dbjz.domain.DbjzApplyInfo;
import com.ruoyi.zzb.dbjz.domain.DbjzFileSetDTO;
import com.ruoyi.zzb.dbjz.mapper.DbjzApplyInfoMapper;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@DataSource(value = DataSourceType.SLAVE)
public class DbjzService {

    @Autowired
    private DbjzApplyInfoMapper dbjzApplyInfoMapper;
    @Autowired
    private BaseFileInfoMapper baseFileInfoMapper;
    @Autowired
    private BaseApproveInfoMapper baseApproveInfoMapper;
    @Autowired
    private BaseService baseService;

    /**
     * 完成【大病救助】模块需进行文件上传字段项的上传处理逻辑，并组装批量插入这些记录到相关数据表的参数
     * @param
     */
    public List<BaseFileInfo> processUploadAndBuildParams(DbjzFileSetDTO dbjzFileSetDTO, String moduleCode, String moduleName, String applyFormId, String fileStoragePath) throws IOException {
        List<BaseFileInfo> dataList = new ArrayList<>();
        MultipartFile[] dbjzsqbFiles = dbjzFileSetDTO.getDbjzsqbFiles();
        List<BaseFileInfo> dbjzsqbRowDataList = baseService.doProcessUploadAndBuildParams(dbjzsqbFiles, moduleCode, moduleName, applyFormId, "大病救助申请表", "dbjzsqb", fileStoragePath);
        if(dbjzsqbRowDataList.size() > 0){
            dataList.addAll(dbjzsqbRowDataList);
        }
        MultipartFile[] dbjlqzmFiles = dbjzFileSetDTO.getDbjlqzmFiles();
        List<BaseFileInfo> dbjlqzmRowDataList = baseService.doProcessUploadAndBuildParams(dbjlqzmFiles, moduleCode, moduleName, applyFormId, "低保金领取证明", "dbjlqzm", fileStoragePath);
        if(dbjlqzmRowDataList.size() > 0){
            dataList.addAll(dbjlqzmRowDataList);
        }
        MultipartFile[] yyfyjnmxzmFiles = dbjzFileSetDTO.getYyfyjnmxzmFiles();
        List<BaseFileInfo> yyfyjnmxzmRowDataList = baseService.doProcessUploadAndBuildParams(yyfyjnmxzmFiles, moduleCode, moduleName, applyFormId, "医药费用缴纳明细证明", "yyfyjnmxzm", fileStoragePath);
        if(yyfyjnmxzmRowDataList.size() > 0){
            dataList.addAll(yyfyjnmxzmRowDataList);
        }
        MultipartFile[] zdzmfyjFiles = dbjzFileSetDTO.getZdzmfyjFiles();
        List<BaseFileInfo> zdzmfyjRowDataList = baseService.doProcessUploadAndBuildParams(zdzmfyjFiles, moduleCode, moduleName, applyFormId, "诊断证明复印件", "zdzmfyj", fileStoragePath);
        if(zdzmfyjRowDataList.size() > 0){
            dataList.addAll(zdzmfyjRowDataList);
        }
        MultipartFile[] basyfyjFiles = dbjzFileSetDTO.getBasyfyjFiles();
        List<BaseFileInfo> basyfyjRowDataList = baseService.doProcessUploadAndBuildParams(basyfyjFiles, moduleCode, moduleName, applyFormId, "病案首页复印件", "basyfyj", fileStoragePath);
        if(basyfyjRowDataList.size() > 0){
            dataList.addAll(basyfyjRowDataList);
        }
        MultipartFile[] sfzfyjFiles = dbjzFileSetDTO.getSfzfyjFiles();
        List<BaseFileInfo> sfzfyjRowDataList = baseService.doProcessUploadAndBuildParams(sfzfyjFiles, moduleCode, moduleName, applyFormId, "身份证复印件", "sfzfyj", fileStoragePath);
        if(sfzfyjRowDataList.size() > 0){
            dataList.addAll(sfzfyjRowDataList);
        }
        MultipartFile[] ryjlfyjFiles = dbjzFileSetDTO.getRyjlfyjFiles();
        List<BaseFileInfo> ryjlfyjRowDataList = baseService.doProcessUploadAndBuildParams(ryjlfyjFiles, moduleCode, moduleName, applyFormId, "入院记录复印件", "ryjlfyj", fileStoragePath);
        if(ryjlfyjRowDataList.size() > 0){
            dataList.addAll(ryjlfyjRowDataList);
        }
        MultipartFile[] cyjlfyjFiles = dbjzFileSetDTO.getCyjlfyjFiles();
        List<BaseFileInfo> cyjlfyjRowDataList = baseService.doProcessUploadAndBuildParams(cyjlfyjFiles, moduleCode, moduleName, applyFormId, "出院记录复印件", "cyjlfyj", fileStoragePath);
        if(cyjlfyjRowDataList.size() > 0){
            dataList.addAll(cyjlfyjRowDataList);
        }
        MultipartFile[] gsFiles = dbjzFileSetDTO.getGsFiles();
        List<BaseFileInfo> gsRowDataList = baseService.doProcessUploadAndBuildParams(gsFiles, moduleCode, moduleName, applyFormId, "公示", "gs", fileStoragePath);
        if(gsRowDataList.size() > 0){
            dataList.addAll(gsRowDataList);
        }
        return dataList;
    }

    /**
     * 保存/修改一条【大病救助】申请信息并且批量插入/修改与【大病救助】申请信息相关联的文件信息
     * @return
     */
    @Transactional
    public void saveOrUpdateDbjzApplyInfoAndBaseFileInfos(DbjzApplyInfo dbjzApplyInfo, SysUser user, String applyFormId, List<BaseFileInfo> baseFileInfoList){
        // 如果当前申请信息对象dbjzApplyInfo的申请单ID为空，代表是新增操作
        if(StringUtils.isBlank(dbjzApplyInfo.getApplyFormId())){
            dbjzApplyInfo.setCreateUserId(String.valueOf(user.getUserId()));
            dbjzApplyInfo.setCreateUserName(user.getNickName());
            dbjzApplyInfo.setCreateUserPoliceNo(user.getPoliceNo());
            dbjzApplyInfo.setApplyFormId(applyFormId);
            int insertRows = dbjzApplyInfoMapper.insert(dbjzApplyInfo);
            if(insertRows > 0){
                // 批量插入和申请信息关联的文件信息
                baseFileInfoMapper.batchInsertBaseFileInfos(baseFileInfoList);
                log.info("【大病救助】申请信息、文件信息均保存成功  申请单ID：{}", applyFormId);
            } else {
                throw new RuntimeException("数据库【大病救助】申请信息记录未插入  申请单ID：" + applyFormId);
            }
        } else {   // 修改操作
            // 根据申请单ID和dbjzApplyInfo对象中的当前属性值去修改当前申请记录
            String applyFormIdExist = dbjzApplyInfo.getApplyFormId();
            UpdateWrapper<DbjzApplyInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("APPLY_FORM_ID", applyFormIdExist);
            int updateRows = dbjzApplyInfoMapper.update(dbjzApplyInfo, updateWrapper);
            if(updateRows > 0){
                // 批量修改和申请信息关联的文件信息
                // 1.先删除与当前申请记录相关联的全部原始文件记录
                baseService.delBaseFileInfosByApplyFormId(applyFormIdExist);
                // 2.再根据当前申请记录，批量插入新的文件记录，即可完成对文件信息的批量修改
                baseFileInfoMapper.batchInsertBaseFileInfos(baseFileInfoList);
                log.info("【大病救助】申请信息、文件信息均修改成功  申请单ID：{}", applyFormIdExist);
            } else {
                throw new RuntimeException("数据库【大病救助】申请信息记录未修改  申请单ID：" + applyFormIdExist);
            }
        }
    }


    /**
     * 审批一条【大病救助】申请信息，并插入一条审批记录
     * @return
     */
    @Transactional
    public boolean approveAndSaveApproveInfo(String applyFormId, String optFlag, SysUser user){
        // 审批一条【大病救助】申请信息
        UpdateWrapper<DbjzApplyInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("APPLY_FORM_ID", applyFormId);
        DbjzApplyInfo dbjzApplyInfoDTO = new DbjzApplyInfo();
        dbjzApplyInfoDTO.setApproveStatusCode(optFlag);
        String optDesc = "1".equals(optFlag)? "同意":"驳回";
        dbjzApplyInfoDTO.setApproveStatusName(optDesc);
//        dbjzApplyInfoDTO.setUpdateTime(new Date());
        int updateRows = dbjzApplyInfoMapper.update(dbjzApplyInfoDTO, updateWrapper);
        if(updateRows > 0){
            log.info("【大病救助】申请信息已审批  申请单ID：{}，审批操作描述：{}", applyFormId, optDesc);
            // 插入一条审批记录
            BaseApproveInfo baseApproveInfo = new BaseApproveInfo();
            baseApproveInfo.setModuleCode("dbjz");
            baseApproveInfo.setApplyFormId(applyFormId);
            QueryWrapper<DbjzApplyInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("APPLY_FORM_ID", applyFormId);
            DbjzApplyInfo dbjzApplyInfo = dbjzApplyInfoMapper.selectOne(queryWrapper);
            baseApproveInfo.setCreateUserId(dbjzApplyInfo.getCreateUserId());
            baseApproveInfo.setCreateUserName(dbjzApplyInfo.getCreateUserName());
            baseApproveInfo.setCreateUserPoliceNo(dbjzApplyInfo.getCreateUserPoliceNo());
            baseApproveInfo.setCreateTime(dbjzApplyInfo.getCreateTime());
            baseApproveInfo.setApproveUserId(String.valueOf(user.getUserId()));
            baseApproveInfo.setApproveUserName(user.getNickName());
            baseApproveInfo.setApproveUserPoliceNo(user.getPoliceNo());
            baseApproveInfo.setApproveResultCode(optFlag);
            baseApproveInfo.setApproveResultDesc(optDesc);
            int insertRows = baseApproveInfoMapper.insert(baseApproveInfo);
            if(insertRows > 0){
                log.info("【大病救助】审批信息保存成功  申请单ID：{}，审批人警号：{}，审批结果说明：{}", applyFormId, user.getPoliceNo(), optDesc);
                return true;
            }else {
                throw new RuntimeException("数据库【大病救助】审批信息记录未插入");
            }
        }else {
            throw new RuntimeException("数据库【大病救助】申请信息记录未更新或不存在");
        }

    }


    /**
     * 根据 审批状态 分页查询【大病救助】申请信息
     * @param
     * @return
     */
    public Page<DbjzApplyInfo> getDataByPage(Integer approveStatus, String type, JSONObject reqBody){
        Integer pageIndex = reqBody.getInteger("pageIndex") == null? 1:reqBody.getInteger("pageIndex");
        Integer pageSize = reqBody.getInteger("pageSize") == null? 10:reqBody.getInteger("pageSize");
        String applyFormId = reqBody.getString("applyFormId");
        // 构造查询条件，支持多条件查询
        QueryWrapper<DbjzApplyInfo> queryWrapper = new QueryWrapper<>();
        // 1.查询当前用户能看到的整个系统中的全量"待审批"的记录，暂不考虑用户所属具体部门的因素
        if (approveStatus != null && approveStatus == 0 && "approve".equals(type)){
            // 匹配列表中的一条，对"待审批"的申请信息做数据回显及提供审批功能
            if(StringUtils.isNotBlank(applyFormId)){
                queryWrapper.eq("APPLY_FORM_ID", applyFormId);
            }
            queryWrapper.eq("APPROVE_STATUS_CODE", 0);
        }
        // 2.查询当前用户提交的全量"审批中"的申请记录（包含待审批记录、审批驳回记录）
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (approveStatus != null && approveStatus == 3 && "apply".equals(type)){
            // 匹配列表中的一条，对"审批中"的申请信息做数据回显及提供修改功能
            if(StringUtils.isNotBlank(applyFormId)){
                queryWrapper.eq("APPLY_FORM_ID", applyFormId);
            }
            queryWrapper.eq("CREATE_USER_POLICE_NO", user.getPoliceNo());
            // 待审批和审批驳回（允许修改后继续提交）
            queryWrapper.and(qw -> qw.eq("APPROVE_STATUS_CODE", 0).or().eq("APPROVE_STATUS_CODE", 2));
        }
        // 3.查询当前用户提交的全量"已审批"的申请记录（只包含审批通过记录）
        if (approveStatus != null && approveStatus == 1 && "apply".equals(type)){
            // 匹配列表中的一条，对"已审批"的申请信息做数据回显
            if(StringUtils.isNotBlank(applyFormId)){
                queryWrapper.eq("APPLY_FORM_ID", applyFormId);
            }
            queryWrapper.eq("CREATE_USER_POLICE_NO", user.getPoliceNo());
            queryWrapper.eq("APPROVE_STATUS_CODE", 1);
        }
        queryWrapper.orderByDesc("CREATE_TIME");
        Page<DbjzApplyInfo> page = new Page<>(pageIndex, pageSize);
        return dbjzApplyInfoMapper.selectPage(page, queryWrapper);
    }


    /**
     * 保存/修改一条【大病救助】申请信息
     * @return
     */
    @Transactional
    public boolean saveOrUpdateDbjzApplyInfo(DbjzApplyInfo dbjzApplyInfo, SysUser user){
        String applyFormId = dbjzApplyInfo.getApplyFormId();
        QueryWrapper<DbjzApplyInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("APPLY_FORM_ID", applyFormId);
        DbjzApplyInfo dbDbjzApplyInfo = dbjzApplyInfoMapper.selectOne(queryWrapper);
        // 如果当前申请信息对象dbjzApplyInfo的申请单ID在数据库中不存在（前端生成），代表是新增操作
        if(dbDbjzApplyInfo == null){
            // 设置当前登录的用户信息
            dbjzApplyInfo.setCreateUserId(String.valueOf(user.getUserId()));
            dbjzApplyInfo.setCreateUserName(user.getNickName());
            dbjzApplyInfo.setCreateUserPoliceNo(user.getPoliceNo());
            // 插入申请信息
            dbjzApplyInfo.setApplyFormId(applyFormId);
            int insertRows = dbjzApplyInfoMapper.insert(dbjzApplyInfo);
            if(insertRows > 0){
                log.info("【大病救助】申请信息保存成功  申请单ID：{}", applyFormId);
                return true;
            } else {
                throw new RuntimeException("数据库【大病救助】申请信息记录未插入  申请单ID：" + applyFormId);
            }
        } else {   // 修改操作
            if("1".equals(dbDbjzApplyInfo.getApproveStatusCode())){
                throw new RuntimeException("数据库【大病救助】申请信息记录已通过审批，不支持修改  申请单ID：" + applyFormId);
            }
            // 根据申请单ID和dbjzApplyInfo对象中的当前属性值去修改当前申请记录
            UpdateWrapper<DbjzApplyInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("APPLY_FORM_ID", applyFormId);
            int updateRows = dbjzApplyInfoMapper.update(dbjzApplyInfo, updateWrapper);
            if(updateRows > 0){
                log.info("【大病救助】申请信息修改成功  申请单ID：{}", applyFormId);
                return true;
            } else {
                throw new RuntimeException("数据库【大病救助】申请信息记录未修改  申请单ID：" + applyFormId);
            }
        }
    }


}
