package cn.iocoder.yudao.module.system.service.biz;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.MonthlyActivityPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.MonthlyActivityRespVO;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.MonthlyActivitySaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ActivityExecutionRecordDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ActivityItemPurchaseDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlyInfoDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.MonthlyActivityDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ActivityExecutionRecordMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ActivityItemPurchaseMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.MonthlyActivityMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;


/**
 * 月度活动 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
public class MonthlyActivityServiceImpl implements MonthlyActivityService {


    @Resource
    private BuildService buildService;

    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;

    @Resource
    private MonthlyActivityMapper monthlyActivityMapper;

    @Resource
    private ActivityItemPurchaseMapper activityItemPurchaseMapper;

    @Resource
    private ActivityExecutionRecordMapper activityExecutionRecordMapper;


    @Override
    public Long createMonthlyActivity(MonthlyActivitySaveReqVO createReqVO) {
        MonthlyActivityDO monthlyActivityDO = new MonthlyActivityDO();
        BeanUtils.copyProperties(createReqVO, monthlyActivityDO);
        monthlyActivityDO.setAssistantId(createReqVO.getAssistantIdList());
        monthlyActivityDO.setAssistantName(createReqVO.getAssistantNameList());
        monthlyActivityDO.setCreatedTime(LocalDateTime.now());
        monthlyActivityDO.setCreatedBy(SecurityFrameworkUtils.getLoginUserNickname());
        monthlyActivityMapper.insert(monthlyActivityDO);
        return monthlyActivityDO.getActivityId();
    }

    @Override
    public MonthlyActivityDO getMonthlyActivity(Long id) {
        return monthlyActivityMapper.selectById(id);
    }

    @Override
    @TenantIgnore
    public List<MonthlyActivityDO> getMonthlyActivityByMonth(String month, Long[] tenantIds, Integer orgType) {
        YearMonth yearMonth = YearMonth.parse(month, DateTimeFormatter.ofPattern("yyyy-MM"));
        LocalDate firstDayOfMonth = yearMonth.atDay(1);
        LocalDate lastDayOfMonth = yearMonth.atEndOfMonth();
        return monthlyActivityMapper.selectList(new LambdaQueryWrapperX<MonthlyActivityDO>()
                .betweenIfPresent(MonthlyActivityDO::getActivityDate, Stream.of(firstDayOfMonth, lastDayOfMonth).toArray())
                .inIfPresent(MonthlyActivityDO::getTenantId, tenantIds)
                .eqIfPresent(MonthlyActivityDO::getOrgType,orgType));
    }

    @Override
    public PageResult<MonthlyActivityDO> getMonthlyActivityPage(MonthlyActivityPageReqVO pageReqVO) {
        return monthlyActivityMapper.selectPage(pageReqVO);
    }

    @Override
    public void updateMonthlyActivity(MonthlyActivitySaveReqVO updateReqVO) {
        MonthlyActivityDO monthlyActivityDO = new MonthlyActivityDO();
        BeanUtils.copyProperties(updateReqVO, monthlyActivityDO);
        monthlyActivityDO.setAssistantId(updateReqVO.getAssistantIdList());
        monthlyActivityDO.setAssistantName(updateReqVO.getAssistantNameList());
        monthlyActivityMapper.updateById(monthlyActivityDO);
    }

    @Override
    public void createActivityExecutionRecord(ActivityExecutionRecordDO activityExecutionRecordDO) {
        ActivityExecutionRecordDO dbActivityExecutionRecord = activityExecutionRecordMapper.selectOne(new LambdaQueryWrapperX<ActivityExecutionRecordDO>().eq(ActivityExecutionRecordDO::getActivityId, activityExecutionRecordDO.getActivityId()));
        if (dbActivityExecutionRecord == null) {
            activityExecutionRecordDO.setCreatedTime(LocalDateTime.now());
            activityExecutionRecordDO.setCreatedBy(SecurityFrameworkUtils.getLoginUserNickname());
            activityExecutionRecordMapper.insert(activityExecutionRecordDO);

            List<ActivityItemPurchaseDO> items = activityExecutionRecordDO.getItems();
            for (ActivityItemPurchaseDO item : items) {
                item.setCreatedBy(SecurityFrameworkUtils.getLoginUserNickname());
                item.setCreatedTime(LocalDateTime.now());
                activityItemPurchaseMapper.insert(item);
            }

            MonthlyActivityDO monthlyActivityDO = monthlyActivityMapper.selectById(activityExecutionRecordDO.getActivityId());
            if (monthlyActivityDO != null) {
                monthlyActivityDO.setStatus(1);
                monthlyActivityMapper.updateById(monthlyActivityDO);
            }
        }
    }

    @Override
    public MonthlyActivityRespVO getActivityExecutionRecord(Long activityId) {
        MonthlyActivityRespVO respVO = new MonthlyActivityRespVO();
        MonthlyActivityDO monthlyActivity = monthlyActivityMapper.selectById(activityId);
        BeanUtils.copyProperties(monthlyActivity, respVO);
        respVO.setAssistantIdList(monthlyActivity.getAssistantId());
        respVO.setAssistantNameList(monthlyActivity.getAssistantName());

        //查询执行计划记录
        ActivityExecutionRecordDO activityExecutionRecord = activityExecutionRecordMapper
                .selectOne(new LambdaQueryWrapperX<ActivityExecutionRecordDO>()
                        .eq(ActivityExecutionRecordDO::getActivityId, activityId));

        if (activityExecutionRecord != null) {
            //todo  查询已报名人员

            //查询参加人员列表
            if (StringUtils.isNotBlank(activityExecutionRecord.getParticipantIds())) {
                List<ElderlyInfoDO> participantList = new ArrayList<>();
                String participantIds = activityExecutionRecord.getParticipantIds();
                String[] split = participantIds.split(",");
                for (String elderId : split) {
                    ElderlyInfoDO elderlyInfo = elderlyInfoMapper.selectById(elderId);
                    elderlyInfo.setBedName(buildService.getFullBedName(elderlyInfo.getId()));
                    participantList.add(elderlyInfo);
                }
                activityExecutionRecord.setParticipantList(participantList);
            }
        }
        respVO.setActivityExecutionRecordDO(activityExecutionRecord);
        return respVO;
    }

    @Override
    public void deleteMonthlyActivity(Long[] ids) {
        monthlyActivityMapper.deleteBatchIds(Arrays.asList(ids));
    }
}