package org.dromara.business.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.business.domain.bo.CaseBaseInfoBo;
import org.dromara.business.domain.vo.CaseBaseInfoVo;
import org.dromara.business.domain.vo.CaseBeatifyNotice;
import org.dromara.business.domain.vo.CaseUserVo;
import org.dromara.business.domain.vo.UserCaseInfoVo;
import org.dromara.business.service.ICaseBaseInfoService;
import org.dromara.business.utils.SmsUtils;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.constant.CaseConstants;
import org.dromara.common.core.constant.SmsConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.CacheUtils;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.system.domain.SysSmsConfig;
import org.dromara.system.domain.bo.CaseMessageBo;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.service.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 病例基础信息
 *
 * @author wuzhigang
 * @date 2023-11-27
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/business/caseBaseInfo")
public class CaseBaseInfoController extends BaseController {

    private final ICaseBaseInfoService caseBaseInfoService;
    private final ISysUserService userService;
    private final ICaseMessageService caseMessageService;
    private final ISysDictTypeService dictTypeService;
    private final ISysSmsConfigService caseSmsConfigService;
    private final ISysOssService sysOssService;

    /**
     * 查询病例基础信息列表
     */
    @GetMapping("/list")
    public TableDataInfo<CaseBaseInfoVo> list(CaseBaseInfoBo bo, PageQuery pageQuery) {

        return caseBaseInfoService.queryPageList(bo, pageQuery);

    }

    /**
     * 查询租户病例基础信息列表
     */
    @GetMapping("/tenantList")
    public TableDataInfo<CaseBaseInfoVo> tenantList(CaseBaseInfoBo bo, PageQuery pageQuery) {

        TableDataInfo<CaseBaseInfoVo> result = TenantHelper.ignore(() -> {
            return caseBaseInfoService.queryPageList(bo, pageQuery);
        });

        return result;
    }

    /**
     * 查询病例审核列表
     */
    @GetMapping("/checkList")
    public TableDataInfo<CaseBaseInfoVo> checkList(CaseBaseInfoBo bo, PageQuery pageQuery) {
        return caseBaseInfoService.queryCheckPageList(bo, pageQuery);
    }

    /**
     * 查询病例点评列表
     */
    @GetMapping("/commentList")
    public TableDataInfo<CaseBaseInfoVo> commentList(CaseBaseInfoBo bo, PageQuery pageQuery) {
        return caseBaseInfoService.queryCommentList(bo, pageQuery);
    }

    /**
     * 查询病例点评审核列表
     */
    @GetMapping("/commentAuditList")
    public TableDataInfo<CaseBaseInfoVo> commentAuditList(CaseBaseInfoBo bo, PageQuery pageQuery) {
        return caseBaseInfoService.queryCommentAuditList(bo, pageQuery);
    }

    /**
     * 病例解析审核列表查询
     */
    @GetMapping("/analysisList")
    public TableDataInfo<CaseBaseInfoVo> analysisList(CaseBaseInfoBo bo, PageQuery pageQuery) {
        return caseBaseInfoService.queryAnalysisList(bo, pageQuery);
    }

    /**
     * 获取用户病例信息列表
     */
    @GetMapping("/appList")
    public R<UserCaseInfoVo> caseListByUserId(@RequestParam(required = false) Long doctorUserId, @RequestParam(required = false) Long volunteerUserId) {
        return R.ok(caseBaseInfoService.selectCaseListByUserId(doctorUserId, volunteerUserId));
    }

    /**
     * 导出病例基础信息列表
     */
    //@SaCheckPermission("business:caseBaseInfo:export")
    @Log(title = "病例基础信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(CaseBaseInfoBo bo, HttpServletResponse response) {
        List<CaseBaseInfoVo> list = caseBaseInfoService.queryList(bo);
        ExcelUtil.exportExcel(list, "病例基础信息", CaseBaseInfoVo.class, response);
    }

    /**
     * 获取病例基础信息详细信息
     *
     * @param id 主键
     */
    //@SaCheckPermission("business:caseBaseInfo:query")
    @GetMapping("/{id}")
    public R<CaseBaseInfoVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        CaseBaseInfoVo vo = caseBaseInfoService.queryById(id);
        // 解析数据不为空
        if (vo.getAnalysisJson() != null) {
            // 解析json数据
            JSONObject analysisJson = vo.getAnalysisJson();

            // 影像学检查数据
            JSONArray imagingExamination = (JSONArray) analysisJson.getByPath("cases_of_data.0.patient_characteristics.imaging_examination");
            if (imagingExamination != null) {
                for (int i = 0; i < imagingExamination.size(); i++
                ) {
                    // 第一层picture
                    if (imagingExamination.getByPath(i + ".picture") != null) {
                        JSONArray picListLV1 = (JSONArray) imagingExamination.getByPath(i + ".picture");
                        for (int j = 0; j < picListLV1.size(); j++
                        ) {
                            // 第二层picture
                            if (picListLV1.getByPath(j + ".processed_picture") != null) {
                                JSONArray picListLV2 = (JSONArray) picListLV1.getByPath(j + ".processed_picture");
                                // 图片ossKey获取url并填充json
                                for (int k = 0; k < picListLV2.size(); k++) {
                                    String url = sysOssService.generateTempUrl(picListLV2.get(k).toString());
                                    picListLV2.put(k, url);
                                    log.info(url);
                                }
                            } else if (picListLV1.getByPath(j + ".picture") != null) {
                                JSONArray picListLV2 = (JSONArray) picListLV1.getByPath(j + ".picture");
                                // 图片ossKey获取url并填充json
                                for (int k = 0; k < picListLV2.size(); k++) {
                                    String url = sysOssService.generateTempUrl(picListLV2.get(k).toString());
                                    picListLV2.put(k, url);
                                    log.info(url);
                                }
                            }


                        }


                    }
                }
            }

            // 体格检查数据
            JSONArray physicalExamination = (JSONArray) analysisJson.getByPath("cases_of_data.0.patient_characteristics.physical_examination");
            if (physicalExamination != null) {
                for (int i = 0; i < physicalExamination.size(); i++
                ) {
                    // 第一层picture
                    if (physicalExamination.getByPath(i + ".picture") != null) {
                        JSONArray picListLV1 = (JSONArray) physicalExamination.getByPath(i + ".picture");
                        for (int j = 0; j < picListLV1.size(); j++
                        ) {
                            // 第二层picture
                            if (picListLV1.getByPath(j + ".processed_picture") != null) {
                                JSONArray picListLV2 = (JSONArray) picListLV1.getByPath(j + ".processed_picture");
                                // 图片ossKey获取url并填充json
                                for (int k = 0; k < picListLV2.size(); k++) {
                                    String url = sysOssService.generateTempUrl(picListLV2.get(k).toString());
                                    picListLV2.put(k, url);
                                    log.info(url);
                                }
                            } else if (picListLV1.getByPath(j + ".picture") != null) {
                                JSONArray picListLV2 = (JSONArray) picListLV1.getByPath(j + ".picture");
                                // 图片ossKey获取url并填充json
                                for (int k = 0; k < picListLV2.size(); k++) {
                                    String url = sysOssService.generateTempUrl(picListLV2.get(k).toString());
                                    picListLV2.put(k, url);
                                    log.info(url);
                                }


                            }


                        }
                    }
                }
            }

            // 实验室检查数据
            JSONArray laboratoryTests = (JSONArray) analysisJson.getByPath("cases_of_data.0.patient_characteristics.laboratory_tests");
            if (laboratoryTests != null) {
                for (int i = 0; i < laboratoryTests.size(); i++
                ) {
                    // 第一层picture
                    if (laboratoryTests.getByPath(i + ".picture") != null) {
                        JSONArray picListLV1 = (JSONArray) laboratoryTests.getByPath(i + ".picture");
                        for (int j = 0; j < picListLV1.size(); j++
                        ) {
                            // 第二层picture
                            if (picListLV1.getByPath(j + ".processed_picture") != null) {
                                JSONArray picListLV2 = (JSONArray) picListLV1.getByPath(j + ".processed_picture");
                                // 图片ossKey获取url并填充json
                                for (int k = 0; k < picListLV2.size(); k++) {
                                    String url = sysOssService.generateTempUrl(picListLV2.get(k).toString());
                                    picListLV2.put(k, url);
                                    log.info(url);
                                }
                            } else if (picListLV1.getByPath(j + ".picture") != null) {
                                JSONArray picListLV2 = (JSONArray) picListLV1.getByPath(j + ".picture");
                                // 图片ossKey获取url并填充json
                                for (int k = 0; k < picListLV2.size(); k++) {
                                    String url = sysOssService.generateTempUrl(picListLV2.get(k).toString());
                                    picListLV2.put(k, url);
                                    log.info(url);
                                }


                            }


                        }
                    }
                }
            }

            // 组织病理学检查数据
            JSONArray histopathologicalExamination = (JSONArray) analysisJson.getByPath("cases_of_data.0.patient_characteristics.histopathological_examination");
            if (histopathologicalExamination != null) {
                for (int i = 0; i < histopathologicalExamination.size(); i++
                ) {
                    // 第一层picture
                    if (histopathologicalExamination.getByPath(i + ".picture") != null) {
                        JSONArray picListLV1 = (JSONArray) histopathologicalExamination.getByPath(i + ".picture");
                        for (int j = 0; j < picListLV1.size(); j++
                        ) {
                            // 第二层picture
                            if (picListLV1.getByPath(j + ".processed_picture") != null) {
                                JSONArray picListLV2 = (JSONArray) picListLV1.getByPath(j + ".processed_picture");
                                // 图片ossKey获取url并填充json
                                for (int k = 0; k < picListLV2.size(); k++) {
                                    String url = sysOssService.generateTempUrl(picListLV2.get(k).toString());
                                    picListLV2.put(k, url);
                                    log.info(url);
                                }
                            } else if (picListLV1.getByPath(j + ".picture") != null) {
                                JSONArray picListLV2 = (JSONArray) picListLV1.getByPath(j + ".picture");
                                // 图片ossKey获取url并填充json
                                for (int k = 0; k < picListLV2.size(); k++) {
                                    String url = sysOssService.generateTempUrl(picListLV2.get(k).toString());
                                    picListLV2.put(k, url);
                                    log.info(url);
                                }


                            }


                        }
                    }
                }
            }

            // 治疗历程数据
            JSONArray treatmentProcess = (JSONArray) analysisJson.getByPath("cases_of_data.0.treatment_process");
            if (treatmentProcess != null) {
                for (int i = 0; i < treatmentProcess.size(); i++
                ) {
                    // effectiveness_evaluation
                    if (treatmentProcess.getByPath(i + ".effectiveness_evaluation") != null) {
                        JSONArray effectivenessEvaluation = (JSONArray) treatmentProcess.getByPath(i + ".effectiveness_evaluation");
                        for (int j = 0; j < effectivenessEvaluation.size(); j++
                        ) {
                            // 第一层picture
                            if (effectivenessEvaluation.getByPath(j + ".picture") != null) {
                                JSONArray picListLV1 = (JSONArray) effectivenessEvaluation.getByPath(j + ".picture");
                                // 图片ossKey获取url并填充json
                                for (int k = 0; k < picListLV1.size(); k++) {
                                    // 第一层picture
                                    if (picListLV1.getByPath(k + ".picture") != null) {
                                        JSONArray picListLV2 = (JSONArray) picListLV1.getByPath(k + ".picture");
                                        // 图片ossKey获取url并填充json
                                        for (int m = 0; m < picListLV2.size(); m++) {
                                            String url = sysOssService.generateTempUrl(picListLV2.get(m).toString());
                                            picListLV2.put(m, url);
                                            log.info(url);
                                        }
                                    }
                                }


                            }


                        }
                    }
                }
            }
        }
        return R.ok(vo);
    }

    /**
     * 新增病例基础信息
     */
    //@SaCheckPermission("business:caseBaseInfo:add")
    @Log(title = "病例基础信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CaseBaseInfoBo bo) {
        return toAjax(caseBaseInfoService.insertByBo(bo));
    }

    /**
     * 修改病例基础信息
     */
    @Log(title = "病例基础信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CaseBaseInfoBo bo) {
        // 更新结果
        boolean result = caseBaseInfoService.updateByBo(bo);
        if (result) {
            // 病例信息
            CaseBaseInfoVo vo = caseBaseInfoService.queryById(bo.getId());
            // 病例所属人信息
            SysUserVo sysUserVo = userService.selectUserById(vo.getUserId());
            // 审核通过
            if (StringUtils.isNotBlank(bo.getCheckStatus()) && bo.getCheckStatus().equals(CaseConstants.CASE_PASS)) {

                // 获取缓存SMS短信配置
                String json = CacheUtils.get(CacheNames.SYS_SMS_CONFIG, SmsConstants.CASE_REVIEW_PASSED);
                SysSmsConfig sysSmsConfig = JsonUtils.parseObject(json, SysSmsConfig.class);
                // 审核通过短信模版开启
                if (sysSmsConfig != null && sysSmsConfig.getStatus().equals(SmsConstants.SMS_ENABLE)) {
                    LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                    // 病例所属人短信通知
                    SmsResponse smsResponse = SmsUtils.sendAlibabaMessage(sysUserVo.getPhonenumber(), SmsConstants.CASE_REVIEW_PASSED, map);
                    if (!"OK".equals(smsResponse.getCode())) {
                        log.error("审核通过通知短信发送异常 => {}", smsResponse);
                        return R.fail(smsResponse.getMessage());
                    }
                }

                // 病例所属人消息
                CaseMessageBo userMessageBo = new CaseMessageBo();
                userMessageBo.setMessageContent(vo.getCaseName());
                userMessageBo.setMessageType("0");
                userMessageBo.setBusinessId(vo.getId());
                userMessageBo.setUserId(vo.getUserId());
                userMessageBo.setBusinessStatus("0");
                caseMessageService.insertByBo(userMessageBo);

                // 志愿者上传病例
                if (vo.getUploadUserId() != null && vo.getUserId().compareTo(vo.getUploadUserId()) != 0) {
                    // 病例上传人信息
                    SysUserVo uploadUserVo = userService.selectUserById(vo.getUploadUserId());

                    // 短信模版开启
                    if (sysSmsConfig != null && sysSmsConfig.getStatus().equals(SmsConstants.SMS_ENABLE)) {
                        LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                        // 上传志愿者短信通知
                        SmsResponse smsResponse = SmsUtils.sendAlibabaMessage(uploadUserVo.getPhonenumber(), SmsConstants.CASE_REVIEW_PASSED, map);
                        if (!"OK".equals(smsResponse.getCode())) {
                            log.error("审核通过通知短信发送异常 => {}", smsResponse);
                            return R.fail(smsResponse.getMessage());
                        }
                    }


                    // 病例上传人消息
                    CaseMessageBo uploadUserMessageBo = new CaseMessageBo();
                    uploadUserMessageBo.setMessageContent(vo.getCaseName());
                    uploadUserMessageBo.setMessageType("0");
                    uploadUserMessageBo.setBusinessId(vo.getId());
                    uploadUserMessageBo.setUserId(vo.getUploadUserId());
                    uploadUserMessageBo.setBusinessStatus("0");
                    caseMessageService.insertByBo(uploadUserMessageBo);
                }


            }

            // 审核未通过
            if (StringUtils.isNotBlank(bo.getCheckStatus()) && bo.getCheckStatus().equals(CaseConstants.CASE_NO_PASS)) {

                // 获取缓存SMS短信配置
                String json = CacheUtils.get(CacheNames.SYS_SMS_CONFIG, SmsConstants.CASE_REVIEW_FAILED);
                SysSmsConfig sysSmsConfig = JsonUtils.parseObject(json, SysSmsConfig.class);
                // 审核未通过短信模版开启
                if (sysSmsConfig != null && SmsConstants.SMS_ENABLE.equals(sysSmsConfig.getStatus())) {
                    LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                    String refusalReason = bo.getRejectReason();
                    // 拒绝原因过长处理
                    if (refusalReason.length() > 35) {
                        refusalReason = bo.getRejectReason().substring(0, 30) + "...";
                    }
                    // 审核拒绝原因
                    map.put("refusal_reason", refusalReason);
                    // 病例所属人短信通知
                    SmsResponse smsResponse = SmsUtils.sendAlibabaMessage(sysUserVo.getPhonenumber(), SmsConstants.CASE_REVIEW_FAILED, map);
                    if (!"OK".equals(smsResponse.getCode())) {
                        log.error("审核未通过通知短信发送异常 => {}", smsResponse);
                        return R.fail(smsResponse.getMessage());
                    }
                }

                // 病例所属人消息
                CaseMessageBo userMessageBo = new CaseMessageBo();
                userMessageBo.setMessageContent(vo.getCaseName());
                userMessageBo.setMessageType("0");
                userMessageBo.setBusinessId(vo.getId());
                userMessageBo.setUserId(vo.getUserId());
                userMessageBo.setBusinessStatus("1");
                caseMessageService.insertByBo(userMessageBo);

                // 志愿者上传病例
                if (vo.getUploadUserId() != null && vo.getUserId().compareTo(vo.getUploadUserId()) != 0) {
                    // 病例上传人信息
                    SysUserVo uploadUserVo = userService.selectUserById(vo.getUploadUserId());

                    // 审核未通过短信模版开启
                    if (sysSmsConfig != null && SmsConstants.SMS_ENABLE.equals(sysSmsConfig.getStatus())) {
                        LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                        String refusalReason = bo.getRejectReason();
                        // 拒绝原因过长处理
                        if (refusalReason.length() > 35) {
                            refusalReason = bo.getRejectReason().substring(0, 30) + "...";
                        }
                        // 审核拒绝原因
                        map.put("refusal_reason", refusalReason);
                        // 病例所属人短信通知
                        SmsResponse smsResponse = SmsUtils.sendAlibabaMessage(uploadUserVo.getPhonenumber(), SmsConstants.CASE_REVIEW_FAILED, map);
                        if (!"OK".equals(smsResponse.getCode())) {
                            log.error("审核未通过通知短信发送异常 => {}", smsResponse);
                            return R.fail(smsResponse.getMessage());
                        }
                    }
                    // 病例上传人消息
                    CaseMessageBo uploadUserMessageBo = new CaseMessageBo();
                    uploadUserMessageBo.setMessageContent(vo.getCaseName());
                    uploadUserMessageBo.setMessageType("0");
                    uploadUserMessageBo.setBusinessId(vo.getId());
                    uploadUserMessageBo.setUserId(vo.getUploadUserId());
                    uploadUserMessageBo.setBusinessStatus("1");
                    caseMessageService.insertByBo(uploadUserMessageBo);
                }
            }

            // 病例美化
            if (StringUtils.isNotBlank(bo.getBeautifyStatus()) && bo.getBeautifyStatus().equals(CaseConstants.BEAUTIFY_STATUS)) {

                // 获取缓存SMS短信配置
                String json = CacheUtils.get(CacheNames.SYS_SMS_CONFIG, SmsConstants.CASE_BEAUTIFICATION_UPLOAD);
                SysSmsConfig sysSmsConfig = JsonUtils.parseObject(json, SysSmsConfig.class);
                // 病例美化通知模板开启
                if (sysSmsConfig != null && SmsConstants.SMS_ENABLE.equals(sysSmsConfig.getStatus())) {
                    LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                    // 病例所属人短信通知
                    SmsResponse smsResponse = SmsUtils.sendAlibabaMessage(sysUserVo.getPhonenumber(), SmsConstants.CASE_BEAUTIFICATION_UPLOAD, map);
                    if (!"OK".equals(smsResponse.getCode())) {
                        log.error("病例审核通过通知短信发送异常 => {}", smsResponse);
                        return R.fail(smsResponse.getMessage());
                    }
                }

                // 病例所属人消息
                CaseMessageBo userMessageBo = new CaseMessageBo();
                userMessageBo.setMessageContent(vo.getCaseName());
                userMessageBo.setMessageType("0");
                userMessageBo.setBusinessId(vo.getId());
                userMessageBo.setUserId(vo.getUserId());
                userMessageBo.setBusinessStatus("2");
                caseMessageService.insertByBo(userMessageBo);

                // 志愿者上传病例
                if (vo.getUploadUserId() != null && vo.getUserId().compareTo(vo.getUploadUserId()) != 0) {
                    // 病例上传人信息
                    SysUserVo uploadUserVo = userService.selectUserById(vo.getUploadUserId());

                    // 病例美化通知模板开启
                    if (sysSmsConfig != null && SmsConstants.SMS_ENABLE.equals(sysSmsConfig.getStatus())) {
                        LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                        // 病例所属人短信通知
                        SmsResponse smsResponse = SmsUtils.sendAlibabaMessage(uploadUserVo.getPhonenumber(), SmsConstants.CASE_BEAUTIFICATION_UPLOAD, map);
                        if (!"OK".equals(smsResponse.getCode())) {
                            log.error("病例审核通过通知短信发送异常 => {}", smsResponse);
                            return R.fail(smsResponse.getMessage());
                        }
                    }

                    // 病例上传人消息
                    CaseMessageBo uploadUserMessageBo = new CaseMessageBo();
                    uploadUserMessageBo.setMessageContent(vo.getCaseName());
                    uploadUserMessageBo.setMessageType("0");
                    uploadUserMessageBo.setBusinessId(vo.getId());
                    uploadUserMessageBo.setUserId(vo.getUploadUserId());
                    uploadUserMessageBo.setBusinessStatus("2");
                    caseMessageService.insertByBo(uploadUserMessageBo);
                }
            }

        }
        return toAjax(caseBaseInfoService.updateByBo(bo));
    }

    /**
     * 变更病例状态
     */
    @Log(title = "变更病例状态", businessType = BusinessType.UPDATE)
    @PutMapping("/changeCaseStatus")
    public R<Void> changeCaseStatus(@Validated(EditGroup.class) @RequestBody CaseBaseInfoBo bo) {
        return toAjax(caseBaseInfoService.updateCaseStatus(bo));
    }

    /**
     * 删除病例基础信息
     *
     * @param ids 主键串
     */
    //@SaCheckPermission("business:caseBaseInfo:remove")
    @Log(title = "病例基础信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(caseBaseInfoService.deleteWithValidByIds(List.of(ids), true));
    }


    /**
     * 获取医生用户列表
     */
    @GetMapping("/doctorList")
    public R<List<CaseUserVo>> doctorList() {
        return R.ok(caseBaseInfoService.doctorList());
    }

    /**
     * 获取专家用户分配列表
     */
    @GetMapping("/expertList")
    public R<List<CaseUserVo>> expertList() {
        return R.ok(caseBaseInfoService.expertList());
    }

    /**
     * 获取专家用户下拉列表
     */
    @GetMapping("/expertSelectList")
    public R<List<CaseUserVo>> expertSelectList() {
        return R.ok(caseBaseInfoService.expertSelectList());
    }

    /**
     * 获取志愿者用户列表
     */
    @GetMapping("/volunteerList")
    public R<List<CaseUserVo>> volunteerList() {
        return R.ok(caseBaseInfoService.volunteerList());
    }


    /**
     * 查询数据中病例审核字典项
     */
    @GetMapping(value = "/type/caseReviewStatus")
    public R<List<SysDictDataVo>> caseReviewStatus() {
        // 全部字典数据
        List<SysDictDataVo> data = dictTypeService.selectDictDataByType("case_review_status");
        // 获取数据中的状态列表
        List<String> statusList = caseBaseInfoService.selectCaseReviewStatus();
        // 返回列表
        List<SysDictDataVo> result = new ArrayList<>();
        // 用户列表身份不为空
        if (statusList != null && statusList.size() > 0) {

            for (String status : statusList
            ) {
                for (SysDictDataVo vo : data
                ) {
                    if (vo.getDictValue().equals(status)) {
                        result.add(vo);
                    }
                }
            }
        }
        return R.ok(result);
    }

    /**
     * 查询数据中病例点评审核字典项
     */
    @GetMapping(value = "/type/commentAuditStatus")
    public R<List<SysDictDataVo>> commentAuditStatus() {
        // 全部字典数据
        List<SysDictDataVo> data = dictTypeService.selectDictDataByType("comment_audit_status");
        // 获取数据中的状态列表
        List<String> statusList = caseBaseInfoService.commentAuditStatus();
        // 返回列表
        List<SysDictDataVo> result = new ArrayList<>();
        // 列表不为空
        if (statusList != null && statusList.size() > 0) {

            for (String status : statusList
            ) {
                for (SysDictDataVo vo : data
                ) {
                    if (vo.getDictValue().equals(status)) {
                        result.add(vo);
                    }
                }
            }
        }
        return R.ok(result);
    }

    /**
     * 查询数据中病例解析审核字典项
     */
    @GetMapping(value = "/type/caseAnalysisStatus")
    public R<List<SysDictDataVo>> caseAnalysisStatus() {
        // 全部字典数据
        List<SysDictDataVo> data = dictTypeService.selectDictDataByType("case_analysis_status");
        // 获取数据中的状态列表
        List<String> statusList = caseBaseInfoService.caseAnalysisStatus();
        // 返回列表
        List<SysDictDataVo> result = new ArrayList<>();
        // 列表不为空
        if (statusList != null && statusList.size() > 0) {

            for (String status : statusList
            ) {
                for (SysDictDataVo vo : data
                ) {
                    if (vo.getDictValue().equals(status)) {
                        result.add(vo);
                    }
                }
            }
        }
        return R.ok(result);
    }

    /**
     * 查询数据中病例点评状态字典项
     */
    @GetMapping(value = "/type/commentStatus")
    public R<List<SysDictDataVo>> commentStatus() {
        // 全部字典数据
        List<SysDictDataVo> data = dictTypeService.selectDictDataByType("comment_status");
        // 获取数据中的状态列表
        List<String> statusList = caseBaseInfoService.commentStatus();
        // 返回列表
        List<SysDictDataVo> result = new ArrayList<>();
        // 列表不为空
        if (statusList != null && statusList.size() > 0) {

            for (String status : statusList
            ) {
                for (SysDictDataVo vo : data
                ) {
                    if (vo.getDictValue().equals(status)) {
                        result.add(vo);
                    }
                }
            }
        }
        return R.ok(result);
    }

    @Log(title = "点评专家分配", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/expertAllocation")
    public R<Void> expertAllocation(@Validated(EditGroup.class) @RequestBody CaseBaseInfoBo bo) {
        return toAjax(caseBaseInfoService.expertAllocation(bo));
    }

    @Log(title = "专家点评", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/comment")
    public R<Void> comment(@Validated(EditGroup.class) @RequestBody CaseBaseInfoBo bo) {
        boolean result = caseBaseInfoService.comment(bo);
        return toAjax(result);
    }

    @Log(title = "专家点评审核", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/commentAudit")
    public R<Void> commentAudit(@Validated(EditGroup.class) @RequestBody CaseBaseInfoBo bo) {
        boolean result = caseBaseInfoService.commentAudit(bo) > 0;
        // 点评审核通过
        if (result && bo.getCommentAuditStatus().equals(CaseConstants.COMMNET_PASS)) {
            // 病例信息
            CaseBaseInfoVo vo = caseBaseInfoService.queryById(bo.getId());
            // 病例所属人信息
            SysUserVo sysUserVo = userService.selectUserById(vo.getUserId());

            // 获取缓存SMS短信配置
            String json = CacheUtils.get(CacheNames.SYS_SMS_CONFIG, SmsConstants.CASE_COMMENT);
            SysSmsConfig sysSmsConfig = JsonUtils.parseObject(json, SysSmsConfig.class);
            // 病例点评模版开启
            if (sysSmsConfig != null && sysSmsConfig.getStatus().equals(SmsConstants.SMS_ENABLE)) {
                LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                // 病例所属人短信通知
                SmsResponse smsResponse = SmsUtils.sendAlibabaMessage(sysUserVo.getPhonenumber(), SmsConstants.CASE_COMMENT, map);
                if (!"OK".equals(smsResponse.getCode())) {
                    log.error("病例点评通知短信发送异常 => {}", smsResponse);
                    return R.fail(smsResponse.getMessage());
                }
            }

            // 病例所属人消息
            CaseMessageBo userMessageBo = new CaseMessageBo();
            userMessageBo.setMessageContent(vo.getCaseName());
            userMessageBo.setMessageType("0");
            userMessageBo.setBusinessId(vo.getId());
            userMessageBo.setUserId(vo.getUserId());
            userMessageBo.setBusinessStatus("5");
            caseMessageService.insertByBo(userMessageBo);

            // 志愿者上传病例
            if (vo.getUploadUserId() != null && vo.getUserId().compareTo(vo.getUploadUserId()) != 0) {
                // 病例上传人信息
                SysUserVo uploadUserVo = userService.selectUserById(vo.getUploadUserId());

                // 短信模版开启
                if (sysSmsConfig != null && sysSmsConfig.getStatus().equals(SmsConstants.SMS_ENABLE)) {
                    LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                    // 上传志愿者短信通知
                    SmsResponse smsResponse = SmsUtils.sendAlibabaMessage(uploadUserVo.getPhonenumber(), SmsConstants.CASE_COMMENT, map);
                    if (!"OK".equals(smsResponse.getCode())) {
                        log.error("病例点评通知短信发送异常 => {}", smsResponse);
                        return R.fail(smsResponse.getMessage());
                    }
                }


                // 病例上传人消息
                CaseMessageBo uploadUserMessageBo = new CaseMessageBo();
                uploadUserMessageBo.setMessageContent(vo.getCaseName());
                uploadUserMessageBo.setMessageType("0");
                uploadUserMessageBo.setBusinessId(vo.getId());
                uploadUserMessageBo.setUserId(vo.getUploadUserId());
                uploadUserMessageBo.setBusinessStatus("5");
                caseMessageService.insertByBo(uploadUserMessageBo);
            }
        }
        return toAjax(result);
    }

    @Log(title = "病例解析审核", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/analysisAudit")
    public R<Void> analysisAudit(@Validated(EditGroup.class) @RequestBody CaseBaseInfoBo bo) {
        boolean result = caseBaseInfoService.analysisAudit(bo) > 0;
        if (result) {
            // 解析审核未通过
            if (bo.getCaseAnalysisStatus().equals("1")) {
                // 病例信息
                CaseBaseInfoVo vo = caseBaseInfoService.queryById(bo.getId());
                // 病例所属人信息
                SysUserVo sysUserVo = userService.selectUserById(vo.getUserId());

                // 获取缓存SMS短信配置
                String json = CacheUtils.get(CacheNames.SYS_SMS_CONFIG, SmsConstants.CASE_STRUCTURED_APPLICATION_NOT_APPROVED);
                SysSmsConfig sysSmsConfig = JsonUtils.parseObject(json, SysSmsConfig.class);
                // 解析审核不通过模版开启
                if (sysSmsConfig != null && sysSmsConfig.getStatus().equals(SmsConstants.SMS_ENABLE)) {
                    LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                    // 病例所属人短信通知
                    SmsResponse smsResponse = SmsUtils.sendAlibabaMessage(sysUserVo.getPhonenumber(), SmsConstants.CASE_STRUCTURED_APPLICATION_NOT_APPROVED, map);
                    if (!"OK".equals(smsResponse.getCode())) {
                        log.error("课件解析申请不通过通知短信发送异常 => {}", smsResponse);
                        return R.fail(smsResponse.getMessage());
                    }
                }

                // 病例所属人消息
                CaseMessageBo userMessageBo = new CaseMessageBo();
                userMessageBo.setMessageContent(vo.getCaseName());
                userMessageBo.setMessageType("0");
                userMessageBo.setBusinessId(vo.getId());
                userMessageBo.setUserId(vo.getUserId());
                userMessageBo.setBusinessStatus("7");
                caseMessageService.insertByBo(userMessageBo);
            }

            // 解析审核通过
            if (bo.getCaseAnalysisStatus().equals("2")) {
                // 病例信息
                CaseBaseInfoVo vo = caseBaseInfoService.queryById(bo.getId());
                // 病例所属人信息
                SysUserVo sysUserVo = userService.selectUserById(vo.getUserId());

                // 获取缓存SMS短信配置
                String json = CacheUtils.get(CacheNames.SYS_SMS_CONFIG, SmsConstants.CASE_STRUCTURED_APPLICATION_APPROVED);
                SysSmsConfig sysSmsConfig = JsonUtils.parseObject(json, SysSmsConfig.class);
                // 解析审核通过模版开启
                if (sysSmsConfig != null && sysSmsConfig.getStatus().equals(SmsConstants.SMS_ENABLE)) {
                    LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                    // 病例所属人短信通知
                    SmsResponse smsResponse = SmsUtils.sendAlibabaMessage(sysUserVo.getPhonenumber(), SmsConstants.CASE_STRUCTURED_APPLICATION_APPROVED, map);
                    if (!"OK".equals(smsResponse.getCode())) {
                        log.error("课件解析申请通过通知短信发送异常 => {}", smsResponse);
                        return R.fail(smsResponse.getMessage());
                    }
                }

                // 病例所属人消息
                CaseMessageBo userMessageBo = new CaseMessageBo();
                userMessageBo.setMessageContent(vo.getCaseName());
                userMessageBo.setMessageType("0");
                userMessageBo.setBusinessId(vo.getId());
                userMessageBo.setUserId(vo.getUserId());
                userMessageBo.setBusinessStatus("6");
                caseMessageService.insertByBo(userMessageBo);
            }
        }
        return toAjax(result);
    }

    @Log(title = "下载病例美化文件状态记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/beautify/download")
    public R<Void> beautifyDownloadStatus(@Validated(EditGroup.class) @RequestBody CaseBaseInfoBo bo) {
        return toAjax(caseBaseInfoService.beautifyDownloadStatus(bo));
    }

    /**
     * 获取病例美化通知信息
     *
     * @param id 主键
     */
    @GetMapping("/notice/{id}")
    public R<CaseBeatifyNotice> caseBeatifyNotice(@NotNull(message = "主键不能为空")
                                                  @PathVariable Long id) {
        return R.ok(caseBaseInfoService.caseBeatifyNotice(id));
    }

}
