package thyyxxk.webserver.service.outpatient.thmz;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.outpatient.thmz.ShareholderCardDao;
import thyyxxk.webserver.dao.his.outpatient.thmz.ZdDiscountDetailDao;
import thyyxxk.webserver.dao.his.outpatient.thmz.ZdVisitTypeNewDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.executeItem.ZdChargeItem;
import thyyxxk.webserver.entity.outpatient.thmz.DiscountEnum;
import thyyxxk.webserver.utils.AssertUtil;
import thyyxxk.webserver.utils.CommonUtil;
import thyyxxk.webserver.utils.ResultVoUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author:lihong
 * @Date: 2024/1/12
 */
@Service
@Slf4j
public class ShareholderCardService {
    private final ShareholderCardDao dao;
    private final ZdVisitTypeNewDao zdVisitTypeNewDao;
    private final ZdDiscountDetailDao zdDiscountDetailDao;
    private final RestTemplate template;

    @Value("${thmz-api-url}")
    private String thmzUrl;

    public ShareholderCardService(ShareholderCardDao dao, ZdVisitTypeNewDao zdVisitTypeNewDao, ZdDiscountDetailDao zdDiscountDetailDao, RestTemplate template) {
        this.dao = dao;
        this.zdVisitTypeNewDao = zdVisitTypeNewDao;
        this.zdDiscountDetailDao = zdDiscountDetailDao;
        this.template = template;
    }

    public List<Map<String, Object>> queryDiscountClass() {
        return DiscountEnum.listDiscount();
    }

    /**
     * @description: 查询身份
     * @author: lihong
     * @date: 2024/1/12 9:44
     * @return: java.util.List<thyyxxk.webserver.service.mz.ZdVisitTypeNew>
     **/
    public List<ZdVisitTypeNew> queryZdVisitTypeNew(ZdVisitTypeNew zdVisitTypeNew) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(zdVisitTypeNew.getDelFlag() !=null,"del_flag", zdVisitTypeNew.getDelFlag());
        return zdVisitTypeNewDao.selectList(queryWrapper);
    }


    public void insertZdVisitTypeNew(ZdVisitTypeNew param) {
        AssertUtil.isnotBlank(param.getStartDate(), "有效开始时间不能为空");
        AssertUtil.isnotBlank(param.getEndDate(), "有效截止时间不能为空");
        AssertUtil.isnotBlank(param.getName(), "身份名称不能为空");
        zdVisitTypeNewDao.insert(param);
    }

    public void updateZdVisitTypeNew(ZdVisitTypeNew param) {
        AssertUtil.isnotBlank(param.getId(), "id不能为空");
        AssertUtil.isnotBlank(param.getStartDate(), "有效开始时间不能为空");
        AssertUtil.isnotBlank(param.getEndDate(), "有效截止时间不能为空");
        AssertUtil.isnotBlank(param.getName(), "身份名称不能为空");
        zdVisitTypeNewDao.updateById(param);
    }

    public void delZdVisitTypeNew(ZdVisitTypeNew param) {
        AssertUtil.isnotBlank(param.getId(), "id不能为空");
        AssertUtil.isnotBlank(param.getDelFlag(), "删除标识不能为空");
        zdVisitTypeNewDao.updateById(param);
    }

    public IPage queryPatientInfo(Page page, String keyWard, Integer id) {
        List<Map<String, Object>> list = dao.selectPatientInfo(page, keyWard, id);
        if (CollUtil.isNotEmpty(list)) {
            CommonUtil.BeanTrim(list);
            list.forEach(item -> {
                ZdVisitTypeNew zdVisitTypeNew = dao.selectByPatientId(Convert.toStr(item.get("patientId"), "").trim());
                item.put("visitName", zdVisitTypeNew == null || StrUtil.isBlank(zdVisitTypeNew.getName()) ? "" : zdVisitTypeNew.getName());
                item.put("visitId", zdVisitTypeNew == null || zdVisitTypeNew.getId() == null ? null : zdVisitTypeNew.getId());
            });
        }
        page.setRecords(list);
        return page;
    }

    /**
     * @description: 保存身份关系表
     * @author: lihong
     * @date: 2024/1/12 16:21
     * @param: params
     **/
    public void saveZdVisitTypeUser(ZdVisitTypeNew params) {
        AssertUtil.isnotBlank(params.getPatientId(), "门诊号不能为空");
        AssertUtil.isnotBlank(params.getId(), "病人身份id不能为空");
        params.setPatientId(params.getPatientId().trim());
        Integer count = dao.selectZdVisitTypeUserBypatienId(params.getPatientId());
        params.setOpDate(new Date());
        if (count == null) {
            List<ZdVisitTypeNew> list = new ArrayList<>();
            list.add(params);
            dao.insertZdVisitTypeUser(list);
        } else {
            dao.updateZdVisitTypeUserBypatienId(params);
        }
    }

    public void delZdVisitTypeUser(ZdVisitTypeNew params) {
        AssertUtil.isnotBlank(params.getPatientId(), "门诊号不能为空");
        dao.delZdVisitTypeUser(params.getPatientId());
    }

    public IPage queryZdDiscountDetail(ZdDiscountDetail params) {
        IPage<ZdDiscountDetail> page = new Page<>(params.getCurrentPage(), params.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(Convert.toInt(params.getVisitType(), 0) != 0, "visit_type", params.getVisitType());
        queryWrapper.eq(StrUtil.isNotBlank(params.getDiscountClass()) && !"all".equals(params.getDiscountClass()), "discount_class", params.getDiscountClass());
        return zdDiscountDetailDao.selectPage(page, queryWrapper);
    }

    public int updateZdDiscountDetailDelFlag(ZdDiscountDetail params) {
        AssertUtil.isnotBlank(params.getId(),"id不能为空");
        AssertUtil.isnotBlank(params.getDelFlag(),"启用状态不能为空");
        params.setOpDate(new Date());
        return zdDiscountDetailDao.updateById(params);
    }

    public int saveZdDiscountDetail(ZdDiscountDetail params) {
        AssertUtil.isnotBlank(params.getVisitType(),"身份不能为空");
        AssertUtil.isnotBlank(params.getDiscountClass(),"优惠类型不能为空");
        AssertUtil.isnotBlank(params.getDiscountType(),"折扣方式不能为空");
        AssertUtil.isnotBlank(params.getDiscount(),"折扣不能为空");
        AssertUtil.isnotBlank(NumberUtil.isNumber(params.getDiscount()),"折扣只能为数字,请输入折扣或具体的收费金额(如0.8或500)");
        AssertUtil.isnotBlank(params.getStartDate(), "有效开始时间不能为空");
        AssertUtil.isnotBlank(params.getEndDate(), "有效截止时间不能为空");
        AssertUtil.isnotBlank(params.getChargeItem(), "项目编码不能为空");
        params.setOpDate(new Date());
        if (params.getId() == null) {
            checkData(params);
            return zdDiscountDetailDao.insert(params);
        } else {
            ZdDiscountDetail zdDiscountDetail = zdDiscountDetailDao.selectById(params.getId());
            if(!params.getVisitType().equals(zdDiscountDetail.getVisitType()) || !params.getDiscountClass().equals(zdDiscountDetail.getDiscountClass()) || !params.getChargeItem().equals(zdDiscountDetail.getChargeItem())){
                checkData(params);
            }
            return zdDiscountDetailDao.updateById(params);
        }
    }

    public void checkData(ZdDiscountDetail params) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("visit_type", params.getVisitType());
        queryWrapper.eq("discount_class", params.getDiscountClass());
        queryWrapper.eq("charge_item", params.getChargeItem());
        long count = zdDiscountDetailDao.selectCount(queryWrapper);
        if(count > 0){
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "该项目已经存在,请不要重复!");
        }
    }

    public List<ZdChargeItem> queryItemList(String discountClass,String keyWard){
        AssertUtil.isnotBlank(discountClass,"优惠类型不能为空!");
        List<ZdChargeItem> list;
        if(DiscountEnum.AUDIT_CODE.getCode().equals(discountClass)){
            list = dao.selectZyAuditItem(keyWard);
        }else if(DiscountEnum.CHARGE_CODE.getCode().equals(discountClass)){
            list =  dao.selcetZdChargeItem(keyWard);
        }
        else if(DiscountEnum.JY_JC_CODE.getCode().equals(discountClass)){
            if(StrUtil.isBlank(keyWard)){
                keyWard = null;
            }else {
                keyWard = "%" + keyWard + "%";
            }
            list =  dao.selectJcJyItemByCommonParams(keyWard,40);
        }
        else {
            list = dao.selectMzTc(keyWard);
        }
        return list;
    }

    public ResultVo<List<Map<String,Object>>> queryAllTemplate(){
        ResultVo response = template.getForObject(thmzUrl+"/queryAllTemplate", ResultVo.class);
        if(response == null){
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "查询组合套餐失败");
        }
        if(response.getCode() == -1){
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "查询组合套餐失败,原因:"+response.getMessage());
        }
        return ResultVoUtil.success((List<Map<String,Object>>)response.getData());
    }

    public List<Map<String,Object>> queryTemplateDetails(Long templateId){
        Map<String,Object> params = new HashMap<String,Object>(5);
        params.put("templateId", templateId);
        ResultVo response = template.postForObject(thmzUrl + "/queryTemplateDetails", params, ResultVo.class);
        if(response == null){
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "查询组合套餐明细失败");
        }
        if(response.getCode() == -1){
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "查询组合套餐明细失败,原因:"+response.getMessage());
        }
        return  (List<Map<String,Object>>)response.getData();
    }

    public List<Map<String,Object>> queryMzChargeType() {
        ResultVo response = template.getForObject(thmzUrl+"/queryMzChargeType", ResultVo.class);
        if(response == null){
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "查询号别失败");
        }
        if(response.getCode() == -1){
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "查询号别失败,原因:"+response.getMessage());
        }
        return  (List<Map<String,Object>>)response.getData();
    }

    public List<ZdChargeItem> queryItemDetail(ZdDiscountDetail params) {
        AssertUtil.isnotBlank(params.getChargeItem(),"编码不能为空");
        AssertUtil.isnotBlank(params.getDiscountClass(),"类型不能不能为空");
        List<ZdChargeItem> list;
        if(DiscountEnum.AUDIT_CODE.getCode().equals(params.getDiscountClass())){
           list =   dao.selcetZdChargeItemByCode(params.getChargeItem());
        }
        else if(DiscountEnum.JY_JC_CODE.getCode().equals(params.getDiscountClass())){
            list =  dao.selectJcJyZdChargeItemByCode(params.getChargeItem(), params.getJyjcType());
        }
        else {
        //    tc_no
            list = dao.selectTcDeatil(params.getChargeItem());
        }
        return list;
    }
}
