package thyyxxk.webserver.service.medicine;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.YbTjConstant;
import thyyxxk.webserver.dao.his.medicine.YpTempPurchaseDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.entity.medicine.YpTempPurchase;
import thyyxxk.webserver.entity.medicine.YpTempPurchaseVo;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.YbReportUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName YpTempPurchaseService
 * @Author hsh
 * @Date 2024/4/24 15:17
 * @Version 1.0
 * @Description 药品预购申请与审核
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class YpTempPurchaseService {

    private final YpTempPurchaseDao dao;

    private final UserCache userCache;



    /**
     * @Description 查询临购药品明细
     * @Author hsh
     * @param text 关键字
     * @return map
     * @Date 2024/4/24 16:59
     */
    public ResultVo<List<Map<String, Object>>> selectTempPurchaseYp(String text){
        List<Map<String, Object>> list = dao.selectTempPurchaseYp(text);
        Map<String, List<Map<String, Object>>> collect = list.stream().collect(Collectors.groupingBy(a -> String.valueOf(a.get("chargeCode"))));
        List<Map<String, Object>> newList = new ArrayList<>();
        collect.forEach((k,v)->{
            if(v.size() >= 2){
                v.forEach(m->{
                    String serial = String.valueOf(m.get("serial"));
                    if("99".equals(serial)){
                        newList.add(m);
                    }
                });
            } else {
                newList.addAll(v);
            }
        });
        return ResultVoUtil.success(newList);
    }

    /**
     * @Description 查询临购药品申请信息
     * @Author hsh
     * @param vo 临购药品申请条件
     * @return YpTempPurchase
     * @Date 2024/4/29 9:15
     */
    public ResultVo<List<YpTempPurchase>> selectYpTempPurchase(YpTempPurchaseVo vo){
        // 控制只能查询自己的申请记录(审核人员除外)
        UserInfo us = userCache.getUserInfoByToken();
        // 根据登录者id查询是否符合审核权限
        int d = dao.selectAuditTempPurchaseOp(us.getCode().trim());
        if(d == 0){
            vo.setOpId(us.getCode().trim());
        }
        // 审核人不能审核自己申请的记录,只能修改
        List<YpTempPurchase> list = dao.selectYpTempPurchase(vo);
        for(YpTempPurchase ypTempPurchase : list){
            String opId = ypTempPurchase.getOpId();
            if(d == 0){
                // 没有审核权限只能修改
                ypTempPurchase.setPermissions("0");
            } else {
                // 有审核权限但自己申请的只能修改不能审核，除此之外的只能审核不修改
                if(opId.equals(us.getCode().trim())){
                    ypTempPurchase.setPermissions("0");
                } else {
                    ypTempPurchase.setPermissions("1");
                }
            }
        }
        return ResultVoUtil.success(list);
    }

    /**
     * @Description 保存药品临购申请
     * @Author hsh
     * @param ypTempPurchase 临购药品申请信息
     * @return map
     * @Date 2024/5/8 9:26
     */
    public ResultVo<Map<String, Object>> saveYpTempPurchase(YpTempPurchase ypTempPurchase){

        if(null == ypTempPurchase || ypTempPurchase.getChargeCode() == null){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "临购药品申请信息不存在，请检查！");
        }

        Map<String, Object> resultMap = new HashMap<>();
        String applyId = ypTempPurchase.getApplyId();
        YpTempPurchase tempPurchase = dao.selectYpTempPurchaseByApplyId(applyId);

        int num;
        try{
            if(null != tempPurchase){
                num = dao.updateYpTempPurchaseByApplyId(ypTempPurchase);
            } else {
                // 新增的时候添加pId
                String id = YbTjConstant.YP_LG_SQ + YbReportUtil.generateUkStr(1, 8);
                ypTempPurchase.setApplyId(id);
                ypTempPurchase.setAuditDate(null);
                num = dao.insert(ypTempPurchase);
            }
            if(num == 0){
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存临购药品申请失败！");
            }
            resultMap.put("cg", "保存临购药品申请成功！");
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存临购药品申请失败！");
        }
    }

    /**
     * @Description 更新临购药品审核信息
     * @Author hsh
     * @param ypTempPurchase 临购药品审核信息
     * @return map
     * @Date 2024/5/8 9:44
     */
    public ResultVo<Map<String, Object>> auditYpTempPurchase(YpTempPurchase ypTempPurchase){

        if(null == ypTempPurchase || ypTempPurchase.getChargeCode() == null){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "临购药品审核信息不存在，请检查！");
        }

        Map<String, Object> resultMap = new HashMap<>();
        String applyId = ypTempPurchase.getApplyId();
        YpTempPurchase tempPurchase = dao.selectYpTempPurchaseByApplyId(applyId);
        int num;
        try{
            if(null != tempPurchase){
                // 增加审核(接收)人，采购人，入库人审核信息
                UserInfo us = userCache.getUserInfoByToken();
                if("1".equals(ypTempPurchase.getReceptFlag())){
                    if(!"1".equals(tempPurchase.getReceptFlag())){
                        ypTempPurchase.setAuditId(us.getCode().trim());
                        ypTempPurchase.setAuditName(us.getName().trim());
                    }
                } else {
                    ypTempPurchase.setAuditId("");
                    ypTempPurchase.setAuditName("");
                }
                if("1".equals(ypTempPurchase.getPurchaseFlag())){
                    if(!"1".equals(tempPurchase.getPurchaseFlag())){
                        ypTempPurchase.setPurchaseId(us.getCode().trim());
                        ypTempPurchase.setPurchaseName(us.getName().trim());
                    }
                } else {
                    ypTempPurchase.setPurchaseId("");
                    ypTempPurchase.setPurchaseName("");
                }
                if("1".equals(ypTempPurchase.getStorageFlag())){
                    if(!"1".equals(tempPurchase.getStorageFlag())){
                        ypTempPurchase.setStorageId(us.getCode().trim());
                        ypTempPurchase.setStorageName(us.getName().trim());
                    }
                } else {
                    ypTempPurchase.setStorageId("");
                    ypTempPurchase.setStorageName("");
                }
                UpdateWrapper<YpTempPurchase> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("apply_id", ypTempPurchase.getApplyId());
                num = dao.update(ypTempPurchase, updateWrapper);
//                num = dao.updateYpTempPurchaseFlagByApplyId(ypTempPurchase);
            } else {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "未查到临购药品审核信息！");
            }
            if(num == 0){
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "更新临购药品审核信息失败！");
            }
            resultMap.put("cg", "更新临购药品审核信息成功！");
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            log.info("更新临购药品审核信息失败: " + e.getMessage());
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "更新临购药品审核信息失败！");
        }
    }

}
