package com.eitc.patient.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eitc.common.annotation.Log;
import com.eitc.common.constant.HttpStatus;
import com.eitc.common.core.controller.BaseController;
import com.eitc.common.core.domain.AjaxResult;
import com.eitc.common.core.page.TableDataInfo;
import com.eitc.common.enums.BusinessType;
import com.eitc.common.utils.PatientBaseUtil;
import com.eitc.common.utils.poi.ExcelUtil;
import com.eitc.patient.domain.DiagnosisManage;
import com.eitc.patient.domain.DiagnosisTypeTemplate;
import com.eitc.patient.excel.DiagnosisManageTemplateExcel;
import com.eitc.patient.service.IDiagnosisManageService;
import com.eitc.patient.service.IDiagnosisTypeTemplateService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * DiagnosisManageController
 *
 * @author mtx
 * @date: 2024/05/17 15:51
 */
@Api(tags = "诊断管理")
@RestController
@RequestMapping("/diagnosis-manage")
public class DiagnosisManageController extends BaseController {

    @Resource
    private IDiagnosisManageService diagnosisManageService;
    @Resource
    private IDiagnosisTypeTemplateService diagnosisTypeTemplateService;

    /**
     * 查询诊断管理
     */
    @GetMapping("/page")
    @ApiOperation("查询诊断管理")
    public TableDataInfo page(@ApiParam(name = "diagnosisParam", value = "搜索条件")
                              @RequestParam(name = "diagnosisParam", required = false) String diagnosisParam) {
        startPage();
        LambdaQueryWrapper<DiagnosisManage> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(diagnosisParam)) {
            wrapper.like(DiagnosisManage::getDiagnosisName, diagnosisParam).or()
                    .like(DiagnosisManage::getDiagnosisCode, diagnosisParam).or()
                    .like(DiagnosisManage::getDiagnosisNamePinyin, diagnosisParam).or()
                    .like(DiagnosisManage::getDiagnosisNamePinyinFirstLetter, diagnosisParam);
        }
        wrapper.orderByDesc(DiagnosisManage::getCreateDate);
        List<DiagnosisManage> manageList = diagnosisManageService.list(wrapper);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("10087");
        rspData.setRows(manageList);
        rspData.setTotal(new PageInfo(manageList).getTotal());
        return rspData;
    }

    /**
     * 获取诊断管理详细信息
     */
    @GetMapping(value = "/detail")
    @ApiOperation("获取诊断管理详细信息")
    public AjaxResult detail(String id) {
        return success(diagnosisManageService.getById(id));
    }

    /**
     * 新增诊断管理
     */
    @Log(title = "新增诊断管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增诊断管理")
    public AjaxResult add(@Valid @RequestBody DiagnosisManage diagnosisManage) {
        checkSaveDiagnosisManage(diagnosisManage);
        // 首拼
        diagnosisManage.setDiagnosisNamePinyinFirstLetter(PatientBaseUtil.getPinYinFirstLetter(diagnosisManage.getDiagnosisName()));
        diagnosisManage.setDiagnosisNamePinyin(PatientBaseUtil.getPinyin(diagnosisManage.getDiagnosisName()));
        return toAjax(diagnosisManageService.save(diagnosisManage));
    }

    /**
     * 修改诊断管理
     */
    @Log(title = "修改诊断管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改诊断管理")
    public AjaxResult edit(@Valid @RequestBody DiagnosisManage diagnosisManage) {
        checkSaveDiagnosisManage(diagnosisManage);
        // 首拼
        diagnosisManage.setDiagnosisNamePinyinFirstLetter(PatientBaseUtil.getPinYinFirstLetter(diagnosisManage.getDiagnosisName()));
        diagnosisManage.setDiagnosisNamePinyin(PatientBaseUtil.getPinyin(diagnosisManage.getDiagnosisName()));
        return toAjax(diagnosisManageService.updateById(diagnosisManage));
    }

    /**
     * 导入诊断分类模板
     *
     * @param file 文件
     */
    @Log(title = "导入诊断分类模板", businessType = BusinessType.INSERT)
    @PostMapping("/importTemplate")
    @ApiOperation("导入诊断分类模板")
    public void importTemplate(@RequestParam("file") @ApiParam(name = "file", value = "上传文件") MultipartFile file, HttpServletResponse response) throws IOException {
        // 1.解析excel
        ExcelUtil<DiagnosisManageTemplateExcel> util = new ExcelUtil<>(DiagnosisManageTemplateExcel.class);
        List<DiagnosisManageTemplateExcel> list = util.importExcel(file.getInputStream());
        // 2.如果解析数据为空则返回错误信息
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException("上传数据为空，请填写");
        }
        // 解析模板
        List<DiagnosisManageTemplateExcel> diagnosisManageTemplateExcels = diagnosisManageService.importTemplate(list);
        // 导出错误模板
        if (CollectionUtils.isNotEmpty(diagnosisManageTemplateExcels)) {
            util.exportExcel(response, diagnosisManageTemplateExcels, "模板错误");
        }
    }

    /**
     * 删除诊断管理
     */
    @Log(title = "删除诊断管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove")
    @ApiOperation("删除诊断管理")
    public AjaxResult remove(String id) {
        checkDelDiagnosisManage(id);
        return toAjax(diagnosisManageService.removeById(id));
    }

    /**
     * 检查诊断管理对象的诊断编码和诊断名称是否重复
     * 此方法通过查询数据库中是否存在相同的诊断编码或诊断名称来确保数据的唯一性
     * 如果发现重复，将抛出IllegalArgumentException异常
     *
     * @param diagnosisManage 待检查的诊断管理对象
     * @throws IllegalArgumentException 如果诊断编码或诊断名称重复，则抛出此异常
     */
    private void checkSaveDiagnosisManage(DiagnosisManage diagnosisManage) {
        // 查询数据库中是否有与提供的诊断编码相同的记录
        long diagnosisCodeCount = diagnosisManageService.count(Wrappers.<DiagnosisManage>lambdaQuery()
                .ne(StringUtils.isNotBlank(diagnosisManage.getId()), DiagnosisManage::getId, diagnosisManage.getId())
                .eq(DiagnosisManage::getDiagnosisCode, diagnosisManage.getDiagnosisCode()));
        // 如果诊断编码重复，则抛出异常
        if (diagnosisCodeCount > 0) {
            throw new IllegalArgumentException("诊断编码重复");
        }
        // 查询数据库中是否有与提供的诊断名称相同的记录
        long diagnosisNameCount = diagnosisManageService.count(Wrappers.<DiagnosisManage>lambdaQuery()
                .ne(StringUtils.isNotBlank(diagnosisManage.getId()), DiagnosisManage::getId, diagnosisManage.getId())
                .eq(DiagnosisManage::getDiagnosisName, diagnosisManage.getDiagnosisName()));
        // 如果诊断名称重复，则抛出异常
        if (diagnosisNameCount > 0) {
            throw new IllegalArgumentException("诊断名称重复");
        }
    }

    /**
     * 检查并处理删除诊断管理信息前的准备工作
     *
     * @param id 待删除的诊断管理信息的ID
     * @throws IllegalArgumentException 如果id为空，则抛出此异常
     */
    private void checkDelDiagnosisManage(String id) {
        // 检查ID是否为空，如果为空则抛出异常，提示id不能为空
        if (StringUtils.isEmpty(id)) {
            throw new IllegalArgumentException("id不能为空");
        }
        long count = diagnosisTypeTemplateService.count(Wrappers.<DiagnosisTypeTemplate>lambdaQuery()
                .eq(DiagnosisTypeTemplate::getDiagnosisManageId, id));
        if (count > 0) {
            throw new IllegalArgumentException("该诊断管理已被使用，无法删除");
        }
    }

}
