package thyyxxk.webserver.service.medicaladvice.common;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.medicaladvice.common.MedicalCommonDao;
import thyyxxk.webserver.dao.his.medicalinsurance.UpIdCollectionDao;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.common.YzSequence;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.common.YzYpPageNo;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.drugmanage.PageClassEnum;
import thyyxxk.webserver.utils.AssertUtil;
import thyyxxk.webserver.utils.CommonUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:医嘱公共服务
 * @Author:lihong
 * @Date: 2023/9/22
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class MedicalCommonService {
    private final MedicalCommonDao dao;
    private final UpIdCollectionDao upIdCollectionDao;

    /**
     * @description:查询药房下拉
     * @author: lihong
     * @date: 2023/9/22 11:34
     * @return: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public List<Map<String, Object>> queryYpZdGroupName() {
        String params = "'73','71','11','81','82'";
        String dictValue = upIdCollectionDao.getDictValueByDictName("1.8", "yf_dict");
        if (StrUtil.isNotBlank(dictValue)) {
            String[] split = dictValue.split(",");
            ArrayList<String> strings = CollUtil.newArrayList(split);
            params = CommonUtil.toInStringSql(strings);
        }
        return dao.selectYpZdGroupName(params);
    }

    /**
     * @description:查询药单
     * @author: lihong
     * @date: 2023/9/22 11:39
     * @param: wardCode
     * @return: java.util.List<thyyxxk.webserver.entity.medicaladvice.medicamanage.common.YzYpPageNo>
     **/
    public IPage queryYzYpPageNo(YzYpPageNo ypPageNo) {
        AssertUtil.isnotBlank(ypPageNo.getWardCode(), "病室不能为空,请选择病室");
        IPage page = new Page(ypPageNo.getCurrentPage(), ypPageNo.getPageSize());
        OrderItem orderItem = new OrderItem();
        orderItem.setAsc(false);
        orderItem.setColumn("sort_no , page_no");
        page.orders().add(orderItem);
        StringBuilder condition = new StringBuilder();
        condition.append(" where 1=1 ");
        if (ypPageNo.getPageNo() != null) {
            condition.append(StrUtil.format(" and page_no = {} ", ypPageNo.getPageNo()));
        }
        if (StrUtil.isNotBlank(ypPageNo.getPageClass())) {
            condition.append(StrUtil.format(" and page_class = '{}' ", ypPageNo.getPageClass()));
        }
        if (StrUtil.isNotBlank(ypPageNo.getTjStartDate())) {
            condition.append(StrUtil.format(" and submit_time >='{}' ", ypPageNo.getTjStartDate()));
        }
        if (StrUtil.isNotBlank(ypPageNo.getTjEndDate())) {
            condition.append(StrUtil.format(" and submit_time <='{} 23:59:59' ", ypPageNo.getTjEndDate()));
        }
        if (StrUtil.isNotBlank(ypPageNo.getQxStartDate())) {
            condition.append(StrUtil.format(" and cancel_submit_time >='{}' ", ypPageNo.getQxStartDate()));
        }
        if (StrUtil.isNotBlank(ypPageNo.getQxEndDate())) {
            condition.append(StrUtil.format(" and cancel_submit_time <='{} 23:59:59' ", ypPageNo.getQxEndDate()));
        }
        List<YzYpPageNo> yzYpPageNos;
        if (PageClassEnum.TYD.getCode().equals(ypPageNo.getPageClass())) {
            yzYpPageNos = dao.selectTydYzYpPageNo(page, ypPageNo.getWardCode(), condition.toString());
        } else {
            yzYpPageNos = dao.selectYzYpPageNo(page, ypPageNo.getWardCode(), condition.toString());
        }
        page.setRecords(yzYpPageNos);
        return page;
    }

    /**
     * @description:获取最新的药单号
     * @author: lihong
     * @date: 2023/9/27 14:28
     * @return: java.lang.Integer
     **/
    @Transactional(timeout = 36000, rollbackFor = Exception.class)
    public Integer getPageNo() {
        Integer oldPageNo = dao.selectPageNo();
        Integer newPageNo = oldPageNo + 1;
        int no = dao.updatePageNo(oldPageNo, newPageNo);
        if (no == 0) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "生成药单号错误，请重试！");
        }
        return CommonUtil.getSerPagNo(newPageNo);
    }

    /**
     * @description:查询序列表信息
     * @author: lihong
     * @date: 2023/10/8 11:30
     * @return: thyyxxk.webserver.entity.medicaladvice.medicamanage.common.YzSequence
     **/
    public YzSequence queryYzSequence() {
        return dao.selectYzSequence();
    }

    /**
     * @description: 查询项目细类
     * @author: lihong
     * @date: 2023/11/9 10:46
     * @param: param
     * @return: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public List<Map<String, Object>> queryItemsSubclass(Map<String, String> param) {
        AssertUtil.isnotBlank(param.get("wardCode"), "病室不能为空");
        List<Map<String, Object>> list = dao.selectItemsSubclass(param);
        return CollUtil.isNotEmpty(list) ? list.stream().sorted(Comparator.comparing(item -> Convert.toStr(item.get("code"), ""))).collect(Collectors.toList()) : Collections.emptyList();
    }

    /**
     * @description:查询项目分类
     * @author: lihong
     * @date: 2023/11/9 10:46
     * @return: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public List<Map<String, Object>> queryItemsList() {
        List<Map<String, Object>> list = dao.selectItemsList();
        CommonUtil.BeanTrim(list);
        return list;
    }

    /**
     * @description:查询项目明细
     * @author: lihong
     * @date: 2023/11/9 10:47
     * @param: params
     * @return: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     **/
    public List<Map<String, Object>> queryItemDetail(Map<String, String> params) {
        AssertUtil.isnotBlank(params.get("wardCode"), "病室不能为空");
        AssertUtil.isnotBlank(params.get("code"), "编码不能为空");
        if (params.get("code").equals("#")) {
            List<Map<String, Object>> mapList = dao.selectDrugDetail(params.get("wardCode"));
            CommonUtil.BeanTrim(mapList);
            return mapList;
        } else {
            List<Map<String, Object>> mapList = dao.selectItemDetail(params.get("code"), params.get("wardCode"));
            CommonUtil.BeanTrim(mapList);
            return mapList;
        }
    }

    public List<Map<String, Object>> queryZyWard() {
        return dao.selectZyWard();
    }


    public List<Map<String, Object>> querySmallWard(Map<String, String> params) {
        AssertUtil.isnotBlank(params.get("code"), "科室编码不能为空");
        return dao.selectSmallWard(params.get("code"));
    }
}
