package com.ltgk.catches.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ltgk.catches.domain.entity.TpAquaticDict;
import com.ltgk.catches.domain.entity.TpFishCatch;
import com.ltgk.catches.domain.entity.TpFishCatchRecord;
import com.ltgk.catches.mapper.TpFishCatchMapper;
import com.ltgk.catches.service.ITpAquaticDictService;
import com.ltgk.catches.service.ITpFishCatchRecordService;
import com.ltgk.catches.service.ITpFishCatchService;
import com.ltgk.common.constant.Constants;
import com.ltgk.common.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 渔获上岸记录Service业务层处理
 *
 * @author Qi ChengBin
 * @date 2025-01-07
 */
@Service
public class TpFishCatchServiceImpl extends ServiceImpl<TpFishCatchMapper, TpFishCatch> implements ITpFishCatchService {

    @Resource
    private ITpFishCatchRecordService tpFishCatchRecordService;
    @Resource
    private ITpAquaticDictService tpAquaticDictService;

    /**
     * 根据主键获取渔获上岸记录详细信息
     *
     * @param id: 渔获上岸记录表主键
     * @return com.ltgk.catches.domain.entity.TpFishCatch
     * @author Qi ChengBin
     * @date 2025/1/8 09:45
     */
    @Override
    public TpFishCatch getTpFishCatchDetailById(String id) {
        TpFishCatch tpFishCatch = this.getById(id);
        if (Objects.nonNull(tpFishCatch)) {
            List<TpFishCatchRecord> tpFishCatchRecordList = tpFishCatchRecordService.lambdaQuery()
                    .eq(TpFishCatchRecord::getCatchId, id)
                    .list();
            Map<String, String> tpAquaticDictMap = tpAquaticDictService.list().stream()
                    .collect(Collectors.toMap(TpAquaticDict::getDictCode, TpAquaticDict::getDictName));

            tpFishCatchRecordList.forEach(tpFishCatchRecord -> {
                if (tpAquaticDictMap.containsKey(tpFishCatchRecord.getFishType())) {
                    tpFishCatchRecord.setFishTypeCode(tpFishCatchRecord.getFishType());
                    tpFishCatchRecord.setFishType(tpAquaticDictMap.get(tpFishCatchRecord.getFishType()));
                }
                if (tpAquaticDictMap.containsKey(tpFishCatchRecord.getFishName())) {
                    tpFishCatchRecord.setFishNameCode(tpFishCatchRecord.getFishName());
                    tpFishCatchRecord.setFishName(tpFishCatchRecord.getFishName());
                }
            });
            tpFishCatch.setTpFishCatchRecordList(tpFishCatchRecordList);
        }
        return tpFishCatch;

    }

    /**
     * 新增渔获上岸记录及其详细信息
     *
     * @param tpFishCatch: 渔获上岸记录数据传输对象
     * @return boolean
     * @author Qi ChengBin
     * @date 2025/1/8 13:51
     */
    @Override
    public boolean saveTpFishCatch(TpFishCatch tpFishCatch) {
        String userName = SecurityUtils.getLoginUser().getUser().getNickName();
        Date nowDate = new Date();
        tpFishCatch
                .setDelFlag(Constants.FLAG_FALSE)
                .setCreateBy(userName)
                .setCreateAt(nowDate)
                .setUpdateBy(userName)
                .setUpdateAt(nowDate);
        if (this.save(tpFishCatch)) {
            return saveTpFishCatchRecordByTpFishCatch(tpFishCatch, userName, nowDate);
        }
        return false;
    }

    /**
     * 修改渔获上岸记录及其详细信息
     * -- 详细信息，先删除再新增
     *
     * @param tpFishCatch: 渔获上岸记录数据传输对象
     * @return boolean
     * @author Qi ChengBin
     * @date 2025/1/8 14:04
     */
    @Override
    public boolean updateTpFishCatch(TpFishCatch tpFishCatch) {
        String userName = SecurityUtils.getLoginUser().getUser().getNickName();
        Date nowDate = new Date();
        tpFishCatch.setUpdateBy(userName)
                .setUpdateAt(nowDate);
        if (this.updateById(tpFishCatch)) {
            // 删除原有渔获明细
            removeTpFishCatchRecordByCatchId(tpFishCatch.getId());
            return saveTpFishCatchRecordByTpFishCatch(tpFishCatch, userName, nowDate);
        }
        return false;
    }

    /**
     * 删除渔获上岸记录及其渔获上岸记录详细信息
     *
     * @param tpFishCatchId: 渔获上岸记录主键
     * @return boolean
     * @author Qi ChengBin
     * @date 2025/1/8 14:40
     */
    @Override
    public boolean removeFishCatchAndCatchRecordById(String tpFishCatchId) {
        if (this.removeById(tpFishCatchId)) {
            return removeTpFishCatchRecordByCatchId(tpFishCatchId);
        }
        return false;
    }

    /**
     * 获取指定时间范围内的渔获上岸总量
     *
     * @param startTime: 开始时间
     * @param endTime:   结束时间
     * @return java.lang.String
     * @author Qi ChengBin
     * @date 2025/1/8 15:33
     */
    @Override
    public String rangeTotalNum(String startTime, String endTime) {
        BigDecimal totalSum = baseMapper.getRangeTotalNum(startTime, endTime);
        if (Objects.isNull(totalSum)) {
            return "0.00";
        }
        // 转化为吨（除以 1000），并且保留两位小数，四舍五入
        BigDecimal decimal = totalSum.divide(new BigDecimal("1000"), 2, RoundingMode.HALF_UP);
        return decimal.toString();
    }

    /**
     * 根据渔获上岸记录数据新增渔获上岸记录详情信息
     *
     * @param tpFishCatch: 渔获上岸记录信息
     * @param userName:    用户名称
     * @param nowDate:     当前时间
     * @return boolean
     * @author Qi ChengBin
     * @date 2025/1/8 14:27
     */
    private boolean saveTpFishCatchRecordByTpFishCatch(TpFishCatch tpFishCatch, String userName, Date nowDate) {
        List<TpFishCatchRecord> tpFishCatchRecordList = tpFishCatch.getTpFishCatchRecordList();
        tpFishCatchRecordList.forEach(
                tpFishCatchRecord -> tpFishCatchRecord.setCatchId(tpFishCatch.getId())
                        .setDelFlag(Constants.FLAG_FALSE)
                        .setAreaCode(tpFishCatch.getAreaCode())
                        .setAreaName(tpFishCatch.getAreaCode())
                        .setCreateBy(userName)
                        .setCreateAt(nowDate)
                        .setUpdateBy(userName)
                        .setUpdateAt(nowDate)
        );
        return tpFishCatchRecordService.saveBatch(tpFishCatchRecordList);
    }

    /**
     * 根据渔获上岸记录主键删除渔获上岸记录详细信息
     *
     * @param tpFishCatchId: 渔获上岸记录主键
     * @return boolean
     * @author Qi ChengBin
     * @date 2025/1/8 14:46
     */
    private boolean removeTpFishCatchRecordByCatchId(String tpFishCatchId) {
        LambdaQueryWrapper<TpFishCatchRecord> tpFishCatchRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tpFishCatchRecordLambdaQueryWrapper.eq(TpFishCatchRecord::getCatchId, tpFishCatchId);
        return tpFishCatchRecordService.remove(tpFishCatchRecordLambdaQueryWrapper);
    }
}
