package com.ruoyi.busi.service.impl;

import java.util.List;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.busi.query.AppNoticeSign;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.busi.mapper.BusiNoticeSignMapper;
import com.ruoyi.busi.domain.BusiNoticeSign;
import com.ruoyi.busi.service.IBusiNoticeSignService;

/**
 * 通告报名Service业务层处理
 *
 * @author 朱春云
 * @date 2025-03-17
 */
@Service
public class BusiNoticeSignServiceImpl extends ServiceImpl<BusiNoticeSignMapper,BusiNoticeSign>  implements IBusiNoticeSignService
{
    @Autowired
    private BusiNoticeSignMapper busiNoticeSignMapper;

    @Override
    public IPage<BusiNoticeSign> queryListPage(BusiNoticeSign pageReqVO, Page<BusiNoticeSign> page) {
        return busiNoticeSignMapper.queryListPage(pageReqVO, page);
    }

    /**
     * 用户报名
     * @param appNoticeSign 报名实体
     */
    @Override
    public void userSign(AppNoticeSign appNoticeSign) throws Exception {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //当前用户是否已报名该通告
        if(busiNoticeSignMapper.selectOne(new LambdaQueryWrapper<BusiNoticeSign>().eq(BusiNoticeSign::getNoticeId, appNoticeSign.getNoticeId()).eq(BusiNoticeSign::getUserId, loginUser.getUserId()).last("limit 1"))!=null){
            throw new Exception("请勿重复报名！");
        }
        for (JSONObject cardInfo : appNoticeSign.getCardList()) {

            BusiNoticeSign busiNoticeSign =new BusiNoticeSign();
            busiNoticeSign.setNoticeId(appNoticeSign.getNoticeId());
            busiNoticeSign.setUserId(loginUser.getUserId());
            busiNoticeSign.setNickname(loginUser.getUser().getNickName());
            busiNoticeSign.setAvatar(loginUser.getUser().getAvatar());
            busiNoticeSign.setStatus("0");
            busiNoticeSign.setFormData(JSONArray.toJSONString(appNoticeSign.getCustomForm()));
            busiNoticeSign.setCardId(cardInfo.getString("id"));
            busiNoticeSign.setPrice(cardInfo.getBigDecimal("price"));
            busiNoticeSign.setRemark(cardInfo.getString("remark"));
            busiNoticeSign.setTel(cardInfo.getString("tel"));
            busiNoticeSign.setIsSuper(appNoticeSign.getIsSuper());
            busiNoticeSign.setAddrId(appNoticeSign.getAddressId());
            busiNoticeSignMapper.insert(busiNoticeSign);
        }
    }
}
