package org.dromara.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.impl.SysDictDataServiceImpl;
import org.dromara.web.domain.NutritionEducation;
import org.dromara.web.domain.NutritionSetting;
import org.dromara.web.domain.bo.NutritionSettingBo;
import org.dromara.web.domain.vo.NutritionSettingVo;
import org.dromara.web.mapper.NutritionSettingMapper;
import org.dromara.web.service.INutritionSettingService;
import org.dromara.web.service.MetabolicCalculator;
import org.dromara.web.service.NutritionDataUtil;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 营养设定Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-21
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class NutritionSettingServiceImpl implements INutritionSettingService {

    private final NutritionSettingMapper baseMapper;

    private final SysUserMapper userMapper;

    private final SysDictDataServiceImpl dictDataService;

    /**
     * 查询营养设定
     *
     * @param id 主键
     * @return 营养设定
     */
    @Override
    public NutritionSettingVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询营养设定列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 营养设定分页列表
     */
    @Override
    public TableDataInfo<NutritionSettingVo> queryPageList(NutritionSettingBo bo, PageQuery pageQuery) {
        List<SysUser> userList = userMapper.selectList(Wrappers.lambdaQuery(SysUser.class).select(SysUser::getUserId, SysUser::getUserName));
        Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(k1 -> k1.getUserId(), k2 -> String.valueOf(k2.getUserName()), (k1, k2) -> k1));

        LambdaQueryWrapper<NutritionSetting> lqw = buildQueryWrapper(bo);
        Page<NutritionSettingVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<NutritionSettingVo> records = result.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            for (NutritionSettingVo record : records) {
                record.setCreateByUser(userMap.get(record.getCreateBy()));
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的营养设定列表
     *
     * @param bo 查询条件
     * @return 营养设定列表
     */
    @Override
    public List<NutritionSettingVo> queryList(NutritionSettingBo bo) {
        LambdaQueryWrapper<NutritionSetting> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NutritionSetting> buildQueryWrapper(NutritionSettingBo bo) {
        Map<String, Object> params = bo.getParams();
        List<Date> dateRange = bo.getDateRange();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        List<SysUser> userList = userMapper.selectList(Wrappers.lambdaQuery(SysUser.class).select(SysUser::getUserId, SysUser::getUserName));
        Map<String, Long> userMap = userList.stream().collect(Collectors.toMap(k1 -> String.valueOf(k1.getUserName()), k2 -> k2.getUserId(), (k1, k2) -> k1));
        LambdaQueryWrapper<NutritionSetting> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(NutritionSetting::getId);

        lqw.eq(bo.getPatientId() != null, NutritionSetting::getPatientId, bo.getPatientId());
        lqw.eq(StringUtils.isNotBlank(bo.getSettingType()), NutritionSetting::getSettingType, bo.getSettingType());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), NutritionSetting::getType, bo.getType());
        if (StringUtils.isNotBlank(bo.getSearchValue())) {
            lqw.and(wrapper -> wrapper.like(NutritionSetting::getCreateBy, userMap.get(bo.getSearchValue())).or().like(NutritionSetting::getOutpatientNo, bo.getSearchValue()));
        }
        if (dateRange != null && dateRange.size() == 2) {
            String startTime = sdf.format(dateRange.get(0)) + " 00:00:00";  // 开始时间
            String endTime = sdf.format(dateRange.get(1)) + " 23:59:59";    // 结束时间
            if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
                lqw.between(NutritionSetting::getCreateTime, startTime, endTime);

            }
        }
        return lqw;
    }

    /**
     * 新增营养设定
     *
     * @param bo 营养设定
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(NutritionSettingBo bo) {
        NutritionSetting add = MapstructUtils.convert(bo, NutritionSetting.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改营养设定
     *
     * @param bo 营养设定
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(NutritionSettingBo bo) {
        NutritionSetting update = MapstructUtils.convert(bo, NutritionSetting.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(NutritionSetting entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除营养设定信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    public Map<String, String> calculateEnergyRequirements(Integer settingType,
                                                           String gender, String ageStr, double height, double weight,
                                                           Integer activity, Integer stressType, BigDecimal burnArea) {
        Map<String, String> settingTypeMap = Optional.ofNullable(dictDataService.selectMapByType("nutrition_setting_type").getData())
            .orElseGet(MapUtil::newHashMap)
            .entrySet().stream()
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                entry -> entry.getValue().getDictLabel()
            ));

        Map<String, String> activityMap = Optional.ofNullable(dictDataService.selectMapByType("physical_activity").getData())
            .orElseGet(MapUtil::newHashMap)
            .entrySet().stream()
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                entry -> entry.getValue().getDictLabel()
            ));

// 2. 保持一致的Map方向（根据业务需求选择一种）
        Map<String, String> stressTypeMap = Optional.ofNullable(dictDataService.selectMapByType("stress_level").getData())
            .orElseGet(MapUtil::newHashMap)
            .entrySet().stream()
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                entry -> entry.getValue().getDictLabel()
            ));
        String activityLevel = null;
        String stressLevel = null;
        Integer age = null;
        if (null != ageStr) {
            age = Integer.valueOf(ageStr.substring(0, 2));

        }
        if (null != activity) {
            activityLevel = activityMap.get(Integer.toString(activity));
        }
        if (null != stressType) {
            stressLevel = stressTypeMap.get(Integer.toString(stressType));

        }

        if (null != activityLevel) {
            if (activityLevel.contains("低")) {
                activityLevel = "低";
            } else if (activityLevel.contains("中")) {
                activityLevel = "中";
            } else if (activityLevel.contains("重")) {
                activityLevel = "重";
            }
        }

        // 3. 应激系数转换
        if (null != stressLevel) {
            if (stressLevel.contains("低级")) {
                stressLevel = "低级";
            } else if (stressLevel.contains("中级")) {
                stressLevel = "中级";
            } else if (stressLevel.contains("严重")) {
                stressLevel = "严重";
            } else if (stressLevel.contains("恶性")) {
                stressLevel = "恶性肿瘤";
            }
        }

        Map<String, String> map = null;
        if ("BEE".equals(settingTypeMap.get(Integer.toString(settingType)))) {
            map = MetabolicCalculator.calculateByBEE(gender, age, height, weight, activityLevel, stressLevel);
        } else if ("DRIS".equals(settingTypeMap.get(Integer.toString(settingType)))) {
            map = MetabolicCalculator.calculateByDRIS(gender, age, height, weight, activityLevel);
        } else if ("拇指测法".equals(settingTypeMap.get(Integer.toString(settingType)))) {
            map = MetabolicCalculator.calculateByThumb(gender, age, height, weight, activityLevel);
        } else if ("烧伤公式".equals(settingTypeMap.get(Integer.toString(settingType)))) {
            map = MetabolicCalculator.calculateByBurnFormula(gender, age, height, age, activityLevel, burnArea.doubleValue());
        }

        Map<String, String> results = new HashMap<>();


        double proteinCaloriePercentage = 20;
        double fatCaloriePercentage = 20;
        double carbohydrateCaloriePercentage = 50;

        // 5. 设置计算结果
        results.put("caloriesKcalPerDay", map.get("kcal/d"));
        results.put("caloriesKjPerDay", map.get("kJ/d"));
        results.put("caloriesKcalPerKgDay", map.get("kcal/kg*d"));

        results.put("proteinCaloriePercentage", String.format("%.2f", proteinCaloriePercentage));//蛋白质热量占比
        results.put("proteinGPerKgDay", map.get("kcal/d"));
        results.put("proteinGPerDay", map.get("kJ/d"));

        results.put("fatCaloriePercentage", String.format("%.2f", fatCaloriePercentage));//脂肪热量占比
        results.put("fatGPerKgDay", map.get("kJ/d"));
        results.put("fatGPerDay", map.get("kcal/d"));

        results.put("carbohydrateCaloriePercentage", String.format("%.2f", carbohydrateCaloriePercentage));//碳水化合物占比
        results.put("carbohydrateGPerKgDay", map.get("kcal/d"));
        results.put("carbohydrateGPerDay", map.get("kJ/d"));

        results.put("calcium", NutritionDataUtil.getValueByAge("钙", null, age));
        results.put("potassium", NutritionDataUtil.getValueByAge("钾", null, age));
        results.put("sodium", NutritionDataUtil.getValueByAge("钠", null, age));
        results.put("magnesium", NutritionDataUtil.getValueByAge("镁", null, age));
        results.put("phosphorus", NutritionDataUtil.getValueByAge("磷", null, age));
        results.put("chloride", NutritionDataUtil.getValueByAge("氯", null, age));
        results.put("iron", NutritionDataUtil.getValueByAge("铁", gender, age));
        results.put("selenium", NutritionDataUtil.getValueByAge("硒", null, age));
        results.put("manganese", NutritionDataUtil.getValueByAge("锰", null, age));
        results.put("fluoride", NutritionDataUtil.getValueByAge("氟", null, age));
        results.put("molybdenum", NutritionDataUtil.getValueByAge("钼", null, age));
        results.put("zinc", NutritionDataUtil.getValueByAge("锌", gender, age));
        results.put("copper", NutritionDataUtil.getValueByAge("铜", null, age));
        results.put("iodine", NutritionDataUtil.getValueByAge("碘", null, age));
        results.put("chromium", NutritionDataUtil.getValueByAge("铬", null, age));
        results.put("vitaminA", NutritionDataUtil.getValueByAge("维生素A", null, age));
        results.put("vitaminD", NutritionDataUtil.getValueByAge("维生素D", null, age));
        results.put("vitaminE", NutritionDataUtil.getValueByAge("维生素E", null, age));
        results.put("vitaminK", NutritionDataUtil.getValueByAge("维生素K", null, age));
        results.put("vitaminBOne", NutritionDataUtil.getValueByAge("维生素B1", gender, age));
        results.put("vitaminBTwo", NutritionDataUtil.getValueByAge("维生素B2", gender, age));
        results.put("vitaminBSix", NutritionDataUtil.getValueByAge("维生素B6", gender, age));
        results.put("vitaminBTwelve", NutritionDataUtil.getValueByAge("维生素B12", null, age));
        results.put("niacin", NutritionDataUtil.getValueByAge("烟酸", gender, age));
        results.put("vitaminC", NutritionDataUtil.getValueByAge("维生素C", null, age));
        results.put("folicAcid", NutritionDataUtil.getValueByAge("叶酸", null, age));
        results.put("choline", NutritionDataUtil.getValueByAge("胆碱", null, age));
        results.put("biotin", NutritionDataUtil.getValueByAge("生物素", null, age));
        results.put("pantothenicAcid", NutritionDataUtil.getValueByAge("泛酸", null, age));
        results.put("dietaryFiber", NutritionDataUtil.getValueByAge("膳食纤维", null, age));

        return results;
    }
}
