package com.ruoyi.zzb.hybz.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.service.BaseService;
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.hybz.domain.HybzApplyInfo;
import com.ruoyi.zzb.hybz.domain.HybzFileSetDTO;
import com.ruoyi.zzb.hybz.mapper.HybzApplyInfoMapper;
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 HybzService {

    @Autowired
    private HybzApplyInfoMapper hybzApplyInfoMapper;
    @Autowired
    private BaseFileInfoMapper baseFileInfoMapper;
    @Autowired
    private BaseApproveInfoMapper baseApproveInfoMapper;
    @Autowired
    private BaseService baseService;

    /**
     * 完成【会员保障】模块需进行文件上传字段项的上传处理逻辑，并组装批量插入这些记录到相关数据表的参数
     *
     * @param
     */
    public List<BaseFileInfo> processUploadAndBuildParams(HybzFileSetDTO hybzFileSetDTO, String moduleCode, String moduleName, String applyFormId, String fileStoragePath) throws IOException {
        List<BaseFileInfo> dataList = new ArrayList<>();
        MultipartFile[] ckhyspbFiles = hybzFileSetDTO.getCkhyspbFiles();
        List<BaseFileInfo> ckhyspbRowDataList = baseService.doProcessUploadAndBuildParams(ckhyspbFiles, moduleCode, moduleName, applyFormId, "持卡会员审批表", "ckhyspb", fileStoragePath);
        if (ckhyspbRowDataList.size() > 0) {
            dataList.addAll(ckhyspbRowDataList);
        }
        MultipartFile[] sfzfyjFiles = hybzFileSetDTO.getSfzfyjFiles();
        List<BaseFileInfo> sfzfyjRowDataList = baseService.doProcessUploadAndBuildParams(sfzfyjFiles, moduleCode, moduleName, applyFormId, "身份证复印件", "sfzfyj", fileStoragePath);
        if (sfzfyjRowDataList.size() > 0) {
            dataList.addAll(sfzfyjRowDataList);
        }
        MultipartFile[] hykfyjFiles = hybzFileSetDTO.getHykfyjFiles();
        List<BaseFileInfo> hykfyjRowDataList = baseService.doProcessUploadAndBuildParams(hykfyjFiles, moduleCode, moduleName, applyFormId, "会员卡复印件", "hykfyj", fileStoragePath);
        if (hykfyjRowDataList.size() > 0) {
            dataList.addAll(hykfyjRowDataList);
        }
        MultipartFile[] zdzmyjFiles = hybzFileSetDTO.getZdzmyjFiles();
        List<BaseFileInfo> zdzmyjRowDataList = baseService.doProcessUploadAndBuildParams(zdzmyjFiles, moduleCode, moduleName, applyFormId, "诊断证明原件", "zdzmyj", fileStoragePath);
        if (zdzmyjRowDataList.size() > 0) {
            dataList.addAll(zdzmyjRowDataList);
        }
        MultipartFile[] basyfyjFiles = hybzFileSetDTO.getBasyfyjFiles();
        List<BaseFileInfo> basyfyjRowDataList = baseService.doProcessUploadAndBuildParams(basyfyjFiles, moduleCode, moduleName, applyFormId, "病案首页复印件", "basyfyj", fileStoragePath);
        if (basyfyjRowDataList.size() > 0) {
            dataList.addAll(basyfyjRowDataList);
        }
        MultipartFile[] ryjlfyjFiles = hybzFileSetDTO.getRyjlfyjFiles();
        List<BaseFileInfo> ryjlfyjRowDataList = baseService.doProcessUploadAndBuildParams(ryjlfyjFiles, moduleCode, moduleName, applyFormId, "入院记录复印件", "ryjlfyj", fileStoragePath);
        if (ryjlfyjRowDataList.size() > 0) {
            dataList.addAll(ryjlfyjRowDataList);
        }
        MultipartFile[] ssjlfyjFiles = hybzFileSetDTO.getSsjlfyjFiles();
        List<BaseFileInfo> ssjlfyjRowDataList = baseService.doProcessUploadAndBuildParams(ssjlfyjFiles, moduleCode, moduleName, applyFormId, "手术记录复印件", "ssjlfyj", fileStoragePath);
        if (ssjlfyjRowDataList.size() > 0) {
            dataList.addAll(ssjlfyjRowDataList);
        }
        MultipartFile[] cyjlfyjFiles = hybzFileSetDTO.getCyjlfyjFiles();
        List<BaseFileInfo> cyjlfyjRowDataList = baseService.doProcessUploadAndBuildParams(cyjlfyjFiles, moduleCode, moduleName, applyFormId, "出院记录复印件", "cyjlfyj", fileStoragePath);
        if (cyjlfyjRowDataList.size() > 0) {
            dataList.addAll(cyjlfyjRowDataList);
        }
        MultipartFile[] blbgfyjFiles = hybzFileSetDTO.getBlbgfyjFiles();
        List<BaseFileInfo> blbgfyjRowDataList = baseService.doProcessUploadAndBuildParams(blbgfyjFiles, moduleCode, moduleName, applyFormId, "病理报告复印件", "blbgfyj", fileStoragePath);
        if (blbgfyjRowDataList.size() > 0) {
            dataList.addAll(blbgfyjRowDataList);
        }
        MultipartFile[] jcbgfyjFiles = hybzFileSetDTO.getJcbgfyjFiles();
        List<BaseFileInfo> jcbgfyjRowDataList = baseService.doProcessUploadAndBuildParams(jcbgfyjFiles, moduleCode, moduleName, applyFormId, "检查报告复印件", "jcbgfyj", fileStoragePath);
        if (jcbgfyjRowDataList.size() > 0) {
            dataList.addAll(jcbgfyjRowDataList);
        }
        return dataList;
    }

    /**
     * 保存/修改一条【会员保障】申请信息并且批量插入/修改与【会员保障】申请信息相关联的文件信息
     *
     * @return
     */
    @Transactional
    public void saveOrUpdateHybzApplyInfoAndBaseFileInfos(HybzApplyInfo hybzApplyInfo, SysUser user, String applyFormId, List<BaseFileInfo> baseFileInfoList) {
        // 如果当前申请信息对象hybzApproveInfo的申请单ID为空，代表是新增操作
        if (StringUtils.isBlank(hybzApplyInfo.getApplyFormId())) {
            hybzApplyInfo.setCreateUserId(String.valueOf(user.getUserId()));
            hybzApplyInfo.setCreateUserName(user.getNickName());
            hybzApplyInfo.setCreateUserPoliceNo(user.getPoliceNo());
            hybzApplyInfo.setApplyFormId(applyFormId);
            int insertRows = hybzApplyInfoMapper.insert(hybzApplyInfo);
            if (insertRows > 0) {
                // 批量插入和申请信息关联的文件信息
                baseFileInfoMapper.batchInsertBaseFileInfos(baseFileInfoList);
                log.info("【会员保障】申请信息、文件信息均保存成功  申请单ID：{}", applyFormId);
            } else {
                throw new RuntimeException("数据库【会员保障】申请信息记录未插入  申请单ID：" + applyFormId);
            }
        } else {   // 修改操作
            // 根据申请单ID和hybzApplyInfo对象中的当前属性值去修改当前申请记录
            String applyFormIdExist = hybzApplyInfo.getApplyFormId();
            UpdateWrapper<HybzApplyInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("APPLY_FORM_ID", applyFormIdExist);
            int updateRows = hybzApplyInfoMapper.update(hybzApplyInfo, 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<HybzApplyInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("APPLY_FORM_ID", applyFormId);
        HybzApplyInfo hybzApplyInfoDTO = new HybzApplyInfo();
        hybzApplyInfoDTO.setApproveStatusCode(optFlag);
        String optDesc = "1".equals(optFlag) ? "同意" : "驳回";
        hybzApplyInfoDTO.setApproveStatusName(optDesc);
//        hybzApplyInfoDTO.setUpdateTime(new Date());
        int updateRows = hybzApplyInfoMapper.update(hybzApplyInfoDTO, updateWrapper);
        if (updateRows > 0) {
            log.info("【住院慰问】申请信息已审批  申请单ID：{}，审批操作描述：{}", applyFormId, optDesc);
            // 插入一条审批记录
            BaseApproveInfo baseApproveInfo = new BaseApproveInfo();
            baseApproveInfo.setModuleCode("hybz");
            baseApproveInfo.setApplyFormId(applyFormId);
            QueryWrapper<HybzApplyInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("APPLY_FORM_ID", applyFormId);
            HybzApplyInfo hybzApplyInfo = hybzApplyInfoMapper.selectOne(queryWrapper);
            baseApproveInfo.setCreateUserId(hybzApplyInfo.getCreateUserId());
            baseApproveInfo.setCreateUserName(hybzApplyInfo.getCreateUserName());
            baseApproveInfo.setCreateUserPoliceNo(hybzApplyInfo.getCreateUserPoliceNo());
            baseApproveInfo.setCreateTime(hybzApplyInfo.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<HybzApplyInfo> 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<HybzApplyInfo> 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<HybzApplyInfo> page = new Page<>(pageIndex, pageSize);
        return hybzApplyInfoMapper.selectPage(page, queryWrapper);
    }


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


}
