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.core.controller.BaseController;
import com.eitc.common.core.domain.AjaxResult;
import com.eitc.common.enums.BusinessType;
import com.eitc.common.utils.bean.BeanUtils;
import com.eitc.common.utils.poi.ExcelUtil;
import com.eitc.patient.domain.DiagnosisType;
import com.eitc.patient.domain.DiagnosisTypeTemplate;
import com.eitc.patient.dto.DiagnosisTypeTemplateDto;
import com.eitc.patient.enums.DiagnosisTypeTemplateReviewStatusEnum;
import com.eitc.patient.enums.MedicalHistoryDiseaseTypeEnum;
import com.eitc.patient.excel.DiagnosisTypeTemplateExcel;
import com.eitc.patient.service.IDiagnosisTypeService;
import com.eitc.patient.service.IDiagnosisTypeTemplateService;
import com.eitc.patient.service.IMedicalHistoryService;
import com.eitc.patient.vo.DiagnosisTypeTemplateSaveVO;
import com.eitc.patient.vo.DiagnosisTypeTemplateVO;
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.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * DiagnosisTypeTemplateController
 *
 * @author mtx
 * @date: 2024/05/17 15:52
 */
@Api(tags = "诊断分类模板")
@RestController
@RequestMapping("/system/diagnosis-type-template")
public class DiagnosisTypeTemplateController extends BaseController {

    @Resource
    private IDiagnosisTypeTemplateService diagnosisTypeTemplateService;
    @Resource
    private IDiagnosisTypeService diagnosisTypeService;
    @Resource
    private IMedicalHistoryService medicalHistoryService;

    /**
     * 查询诊断分类模板
     */
    @GetMapping("/list")
    @ApiOperation("查询诊断分类模板")
    public AjaxResult list(DiagnosisTypeTemplate diagnosisTypeTemplate) {
        LambdaQueryWrapper<DiagnosisTypeTemplate> eq = Wrappers.<DiagnosisTypeTemplate>lambdaQuery()
                .like(Objects.nonNull(diagnosisTypeTemplate.getDiagnosisTypeId()), DiagnosisTypeTemplate::getDiagnosisTypeId, diagnosisTypeTemplate.getDiagnosisTypeId())
                .like(StringUtils.isNotBlank(diagnosisTypeTemplate.getTemplateName()), DiagnosisTypeTemplate::getTemplateName, diagnosisTypeTemplate.getTemplateName())
                .like(StringUtils.isNotBlank(diagnosisTypeTemplate.getTemplateExample()), DiagnosisTypeTemplate::getTemplateExample, diagnosisTypeTemplate.getTemplateExample())
                .orderByAsc(DiagnosisTypeTemplate::getOrderNum);

        return success(diagnosisTypeTemplateService.list(eq));
    }


    @GetMapping("/listToPatientId")
    @ApiOperation("查询诊断分类模板")
    public AjaxResult listToPatientId(String patientId, String diagnosisTypeId) {
        LambdaQueryWrapper<DiagnosisTypeTemplate> eq = Wrappers.<DiagnosisTypeTemplate>lambdaQuery()
                .eq(DiagnosisTypeTemplate::getDiagnosisTypeId, diagnosisTypeId)
                .orderByAsc(DiagnosisTypeTemplate::getOrderNum);

        List<DiagnosisTypeTemplate> list = diagnosisTypeTemplateService.list(eq);
        if (CollectionUtils.isEmpty(list)) {
            return error("请先配置诊断分类模板");
        }
        // 封装模板信息
        List<DiagnosisTypeTemplateDto> collect = list.stream().map(li -> {
            DiagnosisTypeTemplateDto dto = new DiagnosisTypeTemplateDto();
            BeanUtils.copyProperties(li, dto);
            dto.setTemplateExample2(dto.getTemplateExample());
            if (MedicalHistoryDiseaseTypeEnum.ALLERGY_HISTORY.getInfo().equals(li.getTemplateName())) {
                medicalHistoryService.findMedicalHistory(patientId, MedicalHistoryDiseaseTypeEnum.ALLERGY_HISTORY.getCode(), dto);
            }
            if (MedicalHistoryDiseaseTypeEnum.PAST_HISTORY.getInfo().equals(li.getTemplateName())) {
                medicalHistoryService.findMedicalHistory(patientId, MedicalHistoryDiseaseTypeEnum.PAST_HISTORY.getCode(), dto);
            }
            if (MedicalHistoryDiseaseTypeEnum.FAMILY_HISTORY.getInfo().equals(li.getTemplateName())) {
                medicalHistoryService.findMedicalHistory(patientId, MedicalHistoryDiseaseTypeEnum.FAMILY_HISTORY.getCode(), dto);
            }
            return dto;
        }).collect(Collectors.toList());
        return success(collect);
    }

    /**
     * 获取诊断分类模板详细信息
     */
    @GetMapping(value = "/detail")
    @ApiOperation("获取诊断分类模板详细信息")
    public AjaxResult detail(String id) {
        return success(diagnosisTypeTemplateService.getById(id));
    }

    /**
     * 新增诊断分类模板
     */
    @Log(title = "新增诊断分类模板", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增诊断分类模板")
    public AjaxResult add(@ApiParam(value = "entry") @Valid @RequestBody DiagnosisTypeTemplateSaveVO entry) {
        List<DiagnosisTypeTemplateVO> diagnosisTypeTemplateList = entry.getDiagnosisTypeTemplateList();
        if (CollectionUtils.isEmpty(diagnosisTypeTemplateList)) {
            return error("诊断模板为空");
        }
        String diagnosisTypeId = entry.getDiagnosisTypeId();
        if (StringUtils.isBlank(diagnosisTypeId)) {
            return error("必填项不能为空");
        }
        long typeCount = diagnosisTypeService.count(Wrappers.<DiagnosisType>lambdaQuery().eq(DiagnosisType::getParentId, diagnosisTypeId));
        if (typeCount > 0) {
            return error("存在子类型，不允许添加模板");
        }
        diagnosisTypeTemplateService.remove(Wrappers.<DiagnosisTypeTemplate>lambdaQuery().eq(DiagnosisTypeTemplate::getDiagnosisTypeId, diagnosisTypeId));
        return toAjax(diagnosisTypeTemplateService.add(entry));
    }

    /**
     * 导入诊断分类模板
     *
     * @param file            文件
     * @param diagnosisTypeId 诊断分类id
     */
    @Log(title = "导入诊断分类模板", businessType = BusinessType.INSERT)
    @PostMapping("/importTemplate")
    @ApiOperation("导入诊断分类模板")
    public void importTemplate(@RequestParam("file") @ApiParam(name = "file", value = "上传文件") MultipartFile file, String diagnosisTypeId, HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(diagnosisTypeId)) {
            throw new IllegalArgumentException("必填项不能为空");
        }
        long typeCount = diagnosisTypeService.count(Wrappers.<DiagnosisType>lambdaQuery().eq(DiagnosisType::getParentId, diagnosisTypeId));
        if (typeCount > 0) {
            throw new IllegalArgumentException("存在子类型，不允许添加模板");
        }
        // 解析模板
        List<DiagnosisTypeTemplateExcel> diagnosisTypeTemplateExcels = diagnosisTypeTemplateService.importTemplate(file, diagnosisTypeId);
        // 导出错误模板
        if (CollectionUtils.isNotEmpty(diagnosisTypeTemplateExcels)) {
            ExcelUtil<DiagnosisTypeTemplateExcel> util = new ExcelUtil<>(DiagnosisTypeTemplateExcel.class);
            util.exportExcel(response, diagnosisTypeTemplateExcels, "模板错误");
        }
    }

    /**
     * 修改诊断分类模板
     */
    @Log(title = "修改诊断分类模板", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改诊断分类模板")
    public AjaxResult edit(@Valid @RequestBody DiagnosisTypeTemplate diagnosisTypeTemplate) {
        String templateExample = diagnosisTypeTemplate.getTemplateExample();
        if (StringUtils.isNotBlank(templateExample)) {
            diagnosisTypeTemplate.setTemplateOption(diagnosisTypeTemplateService.findTemplateOptionJson(templateExample));
            diagnosisTypeTemplate.setTemplateInfo(diagnosisTypeTemplateService.findTemplateInfo(templateExample));
        }
        diagnosisTypeTemplate.setReviewStatus(DiagnosisTypeTemplateReviewStatusEnum.ALREADY_AUDITING.getCode());
        return toAjax(diagnosisTypeTemplateService.updateById(diagnosisTypeTemplate));
    }

    /**
     * 删除诊断分类模板
     */
    @Log(title = "删除诊断分类模板", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove")
    @ApiOperation("删除诊断分类模板")
    public AjaxResult remove(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        return toAjax(diagnosisTypeTemplateService.removeBatchByIds(idList));
    }

}
