package com.openhis.web.document.appservice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.common.core.domain.R;
import com.core.common.utils.SecurityUtils;
import com.openhis.common.enums.DocUseRangeEnum;
import com.openhis.common.utils.HisPageUtils;
import com.openhis.common.utils.HisQueryUtils;
import com.openhis.document.domain.DocTemplate;
import com.openhis.document.mapper.DocTemplateMapper;
import com.openhis.document.service.IDocTemplateService;
import com.openhis.web.document.appservice.IDocTemplateAppService;
import com.openhis.web.document.dto.DocTemplateDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/**
 * 文档模板 业务实现类
 */
@Slf4j
@Service
public class DocTemplateAppServiceImpl implements IDocTemplateAppService {

    @Resource
    private IDocTemplateService docTemplateService;
    @Resource
    private DocTemplateMapper docTemplateMapper;


    @Override
    public R<?> add(DocTemplateDto docTemplateDto) {

        String msg = initCheck(docTemplateDto);
        if (msg != null) {
            return R.fail(msg);
        }
        DocTemplate docTemplate = new DocTemplate();
        docTemplate.setName(docTemplateDto.getName());
        docTemplate.setDisplayOrder(docTemplateDto.getDisplayOrder());
        docTemplate.setContextJson(docTemplateDto.getContextJson());
        docTemplate.setDefinitionId(docTemplateDto.getDefinitionId());
        if (docTemplateDto.getUseRange() == null) {
            docTemplate.setUseRange(DocUseRangeEnum.ALL_HOSPITAL_USE.getValue());
        }
        if (docTemplateDto.getUseRange() == DocUseRangeEnum.DEPT_USE.getValue()) {
            docTemplateDto.setOrganizationId(SecurityUtils.getLoginUser().getOrgId());
        }
        if (docTemplateDto.getUseRange() == DocUseRangeEnum.USE_BY_SELF.getValue()) {
            docTemplateDto.setUserId(SecurityUtils.getLoginUser().getUserId());
        }
        docTemplate.setOrganizationId(docTemplateDto.getOrganizationId());
        docTemplate.setId(docTemplateDto.getUserId());
        docTemplate.setUseRange(docTemplateDto.getUseRange());
        docTemplate.setRemark(docTemplateDto.getRemark());
        docTemplateService.save(docTemplate);
        return R.ok(" 添加成功");
    }

    private String initCheck(DocTemplateDto docTemplateDto) {
        if (docTemplateDto == null) {
            return "参数不能为空";
        }
        if (docTemplateDto.getName().isEmpty()) {
            return "名称不能为空";
        }
        if (docTemplateDto.getContextJson().isEmpty()) {
            return "内容不能为空";
        }
        if (docTemplateDto.getDefinitionId() == null) {
            return "模板定义不能为空";
        }
        if (docTemplateDto.getUseRange() == null) {
            return "使用范围不能为空";
        }
        if (docTemplateDto.getId() == null) {
            //根据名称+定义查询模板是否存在
            LambdaQueryWrapper<DocTemplate> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DocTemplate::getName, docTemplateDto.getName());
            queryWrapper.eq(DocTemplate::getDefinitionId, docTemplateDto.getDefinitionId());
            DocTemplate docTemplate = docTemplateService.getOne(queryWrapper);
            if (docTemplate != null) {
                return "该模板已存在,请勿重复添加";
            }
        }
        return null;
    }

    @Override
    public R<?> delete(Long id) {
        if (id == null) {
            return R.fail("模板ID不能为空");
        }
        boolean result = docTemplateService.removeById(id);
        if (result) {
            return R.ok("删除成功");
        }
        return R.fail("模板不存在");
    }

    @Override
    public R<?> update(DocTemplateDto docTemplateDto) {
        String msg = initCheck(docTemplateDto);
        if (msg != null) {
            return R.fail(msg);
        }
        if (docTemplateDto.getId() == null) {
            return R.fail("模板ID不能为空");
        }
        DocTemplate docTemplate = docTemplateService.getById(docTemplateDto.getId());
        if (docTemplate == null) {
            return R.fail("模板不存在");
        }
        if (docTemplateDto.getUseRange() == DocUseRangeEnum.ALL_HOSPITAL_USE.getValue() || docTemplateDto.getUseRange() == DocUseRangeEnum.NO_IN_USE.getValue()) {
            docTemplateDto.setOrganizationId(null);
            docTemplateDto.setUserId(null);
        }
        if (docTemplateDto.getUseRange() == DocUseRangeEnum.DEPT_USE.getValue()) {
            docTemplateDto.setOrganizationId(SecurityUtils.getLoginUser().getOrgId());
            docTemplateDto.setUserId(null);
        }
        if (docTemplateDto.getUseRange() == DocUseRangeEnum.USE_BY_SELF.getValue()) {
            docTemplate.setUserId(SecurityUtils.getLoginUser().getUserId());
            docTemplateDto.setOrganizationId(null);
        }
        docTemplate.setName(docTemplateDto.getName());
        docTemplate.setDisplayOrder(docTemplateDto.getDisplayOrder());
        docTemplate.setContextJson(docTemplateDto.getContextJson());
        docTemplate.setDefinitionId(docTemplateDto.getDefinitionId());
        docTemplate.setUseRange(docTemplateDto.getUseRange());
        docTemplate.setOrganizationId(docTemplateDto.getOrganizationId());
        docTemplate.setUserId(docTemplateDto.getUserId());
        docTemplate.setRemark(docTemplateDto.getRemark());
        docTemplateService.save(docTemplate);
        return R.ok("更新成功");
    }

    @Override
    public R<?> getById(Long id) {
        if (id == null) {
            return R.fail("模板ID不能为空");
        }
        DocTemplateDto templateDto = new DocTemplateDto();
        DocTemplate result = docTemplateService.getById(id);
        BeanUtils.copyProperties(result, templateDto);
        return R.ok(templateDto);
    }

    @Override
    public R<?> getListByDefinitionId(Long definitionId) {
        if (definitionId == null) {
            return R.fail("模板定义ID不能为空");
        }
        LambdaQueryWrapper<DocTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DocTemplate::getDefinitionId, definitionId);
        queryWrapper.orderByAsc(DocTemplate::getDisplayOrder);
        List<DocTemplate> docTemplates = docTemplateService.list(queryWrapper);
        List<DocTemplateDto> templateDtos = new ArrayList<>();
        for (DocTemplate docTemplate : docTemplates) {
            DocTemplateDto templateDto = new DocTemplateDto();
            BeanUtils.copyProperties(docTemplate, templateDto);
            templateDtos.add(templateDto);
        }
        return R.ok(templateDtos);
    }

    @Override
    public R<?> getPageList(Integer pageNo, Integer pageSize, String searchKey, HttpServletRequest request) {
        // 构建查询条件（支持多字段搜索）
        QueryWrapper<DocTemplate> queryWrapper = HisQueryUtils.buildQueryWrapper(
                null, searchKey, new HashSet<>(Arrays.asList("name")), request);
        // 按记录时间倒序（最新记录在前）
        queryWrapper.lambda().orderByDesc(DocTemplate::getDisplayOrder);

        Page<DocTemplateDto> page = HisPageUtils.selectPage(
                docTemplateMapper, queryWrapper, pageNo, pageSize, DocTemplateDto.class);
        // 转换为分页结果
        return R.ok(page, "获取成功");
    }
}
