package thyyxxk.webserver.service.dictionary.diagnoseReqTemplate;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.dictionary.diagnoseReqTemplate.DiagnoseReqTemplateDao;
import thyyxxk.webserver.dao.his.dictionary.diagnoseReqTemplate.DiagnoseTemplateDao;
import thyyxxk.webserver.dao.his.dictionary.diagnoseReqTemplate.DiagnoseToReqDao;
import thyyxxk.webserver.entity.CodeName;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.dictionary.diagnoseReqTemplate.data.DiagnoseReqTemplate;
import thyyxxk.webserver.entity.dictionary.diagnoseReqTemplate.data.DiagnoseToReq;
import thyyxxk.webserver.entity.dictionary.diagnoseReqTemplate.req.CreatePatientJyJcReq;
import thyyxxk.webserver.entity.dictionary.diagnoseReqTemplate.req.ReqTemplateReq;
import thyyxxk.webserver.entity.dictionary.diagnoseReqTemplate.req.SelectByDiagnose;
import thyyxxk.webserver.entity.dictionary.diagnoseReqTemplate.vo.DiagnoseReqTemplateVo;
import thyyxxk.webserver.entity.dictionary.diagnoseReqTemplate.vo.DiagnoseTemplateContent;
import thyyxxk.webserver.entity.dictionary.diagnoseReqTemplate.vo.DiagnoseToReqVo;
import thyyxxk.webserver.entity.zhuyuanyisheng.jianyanjiancha.TianJiaJianChaJianYan;
import thyyxxk.webserver.entity.zhuyuanyisheng.jianyanjiancha.YshYjReq;
import thyyxxk.webserver.service.zhuyuanyisheng.JianYanJianChaShenQingService;
import thyyxxk.webserver.utils.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Service
@RequiredArgsConstructor
@Slf4j
public class DiagnoseReqTemplateService {
    private final DiagnoseReqTemplateDao diagnoseReqTemplateDao;
    private final DiagnoseTemplateDao diagnoseTemplateDao;
    private final DiagnoseToReqDao dao;
    private final JianYanJianChaShenQingService jianYanJianChaShenQingService;

    public ResultVo<Page<DiagnoseToReqVo>> getDiagnoseReqTemplateList(ReqTemplateReq value) {
        Page<DiagnoseToReq> selectPage = new Page<>(value.getCurrentPage(), value.getPageSize(), value.getTotal() == 0);

        LambdaQueryWrapper<DiagnoseToReq> eq = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(value.getSearchId())) {
            eq.eq(DiagnoseToReq::getId, value.getSearchId());
        } else {
            if (StrUtil.isNotBlank(value.getSearchValue())) {
                eq.like(DiagnoseToReq::getName, value.getSearchValue())
                        .or()
                        .like(DiagnoseToReq::getPyCode, value.getSearchValue().toUpperCase())
                        .or()
                        .like(DiagnoseToReq::getWbCode, value.getSearchValue().toUpperCase());
            }
        }
        selectPage.addOrder(OrderItem.asc("create_time"));
        Page<DiagnoseToReqVo> diagnoseToReqVoPage = dao.selectTemplateList(selectPage, eq);
        if (value.getTotal() != 0) {
            diagnoseToReqVoPage.setTotal(value.getTotal());
        }
        return R.ok(diagnoseToReqVoPage);
    }

    public ResultVo<String> createTemplate(String name) {
        if (StrUtil.isBlank(name)) {
            return R.fail(ExceptionEnum.NULL_POINTER, "名字不能为空。");
        }
        DiagnoseToReq build = DiagnoseToReq.builder()
                .id(SnowFlakeId.instance().nextId())
                .name(name)
                .pyCode(PingYinUtils.pyShouZiMuDaXie(name))
                .wbCode(PingYinUtils.getWBCode(name))
                .build();
        dao.insert(build);
        return R.ok(ExceptionEnum.SUCCESS_AND_EL_MESSAGE, ExceptionEnum.SUCCESS_AND_EL_MESSAGE.getMessage(), build.getId());
    }


    public ResultVo<DiagnoseTemplateContent> getTemplateContentById(String id) {
        DiagnoseTemplateContent rst = new DiagnoseTemplateContent();
        rst.setReqTemplates(dao.selectReqByTemplateId(id));
        rst.setDiagnoseList(dao.selectByTemplateId(id));
        rst.setId(id);
        return R.ok(rst);
    }


    public ResultVo<String> saveTemplateContent(DiagnoseTemplateContent data) {
        DiagnoseToReq build = DiagnoseToReq.builder()
                .id(data.getId())
                .updateCode(TokenUtil.getInstance().getTokenUserId())
                .updateTime(new Date())
                .build();

        int i = dao.updateById(build);
        if (i == 0) {
            return R.fail(ExceptionEnum.LOGICAL_ERROR, "病历已被删除。");
        }
        dao.delDiagnoseByTemplateId(data.getId());
        if (ListUtil.notBlank(data.getDiagnoseList())) {
            data.getDiagnoseList().forEach(item -> {
                item.setTemplateId(data.getId());
                item.setId(SnowFlakeId.instance().nextId());
            });
            diagnoseTemplateDao.insert(data.getDiagnoseList());
        }

        if (ListUtil.notBlank(data.getReqTemplates())) {
            List<DiagnoseReqTemplate> tmp = new ArrayList<>();
            data.getReqTemplates().forEach(item -> {
                item.setTemplateId(data.getId());
                item.setId(SnowFlakeId.instance().nextId());
                tmp.add(item);
            });
            diagnoseReqTemplateDao.insert(tmp);
        }
        return R.ok(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
    }

    public ResultVo<String> delTemplate(String id) {
        dao.deleteById(id);
        dao.delDiagnoseByTemplateId(id);
        return R.ok(ExceptionEnum.SUCCESS_AND_EL_MESSAGE);
    }

    public ResultVo<List<CodeName>> selectByDiagnose(SelectByDiagnose params) {
        // 患者不在院了就不提示了
        if (dao.inTheCourtyard(params.getPatNo(), params.getTimes()) == 0) {
            return R.ok(new ArrayList<>());
        }

        return R.ok(dao.selectDiagnoseTemplateByDiagnoseCode(new QueryWrapper<>()
                .in("diagnose_code", params.getDiagnoses())
        ));
    }

    public ResultVo<List<Integer>> createPatientJyJcReq(CreatePatientJyJcReq params) {
        if (ListUtil.isBlank(params.getData())) {
            return R.fail(ExceptionEnum.LOGICAL_ERROR, "请先选择需要开的申请。");
        }

        TianJiaJianChaJianYan addParams = new TianJiaJianChaJianYan();
        addParams.setInpatientNo(params.getPatNo());
        addParams.setAdmissTimes(params.getTimes());
        addParams.setReqType(params.getReqType());

        List<YshYjReq> list = new ArrayList<>();
        Date now = new Date();

        params.getData().forEach(item -> {
            YshYjReq req = new YshYjReq();
            req.setOrderName(item.getOrderName());
            req.setOrderCode(item.getOrderCode());
            req.setOrderCode(item.getZyOrderCode());
            req.setReqTzComment(params.getReqTzComment());
            req.setReqComment(params.getReqComment());
            req.setReqOtherResult(params.getReqOtherResult());
            req.setDiagCode(params.getDiagCode());
            req.setDiagText(params.getDiagName());
            req.setStartTime(now);
            req.setExecDept(item.getExecDept());
            if (Objects.equals(params.getReqType(), JianYanJianChaShenQingService.JC_TYPE)) {
                req.setInspectPart(item.getPartOrSample());
            } else {
                req.setInspectStuff(item.getPartOrSample());
            }
            list.add(req);
        });
        addParams.setInpatientNo(params.getPatNo());
        addParams.setAdmissTimes(params.getTimes());
        addParams.setList(list);
        return jianYanJianChaShenQingService.baoCunJianYanJianCha(addParams);
    }

}
