package com.lh.service;

import com.lh.bean.CrowdfundingInfo;
import com.lh.bean.Participant;
import com.lh.exception.MyException;
import com.lh.mapper.CrowdfundingMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class CrowdfundingServiceImpl implements CrowdfundingService {
    @Autowired
    private CrowdfundingMapper crowdfundingMapper;
    @Override
    public CrowdfundingInfo loadPage() {
        CrowdfundingInfo crowdfundingInfoList = crowdfundingMapper.loadPage();
        List<Participant> participants = crowdfundingMapper.queryCrowdUser(null);
        crowdfundingInfoList.setParticipantList(participants);
        return crowdfundingInfoList;
    }

    @Override
    public void updateTitle(String title) throws MyException {
        if (title.length() == 0) {
            throw new MyException("标题不能为空");
        }
        crowdfundingMapper.updateTitle(title);
    }

    @Override
    public void updateTarget(Integer target) throws MyException {
        //target不能为空
        if (target == null) {
            throw new MyException("目标不能为空");
        }
        //target只能输入数字且必须大于0
        if (target <= 0) {
            throw new MyException("目标必须大于0");
        }
        if (target.toString().matches("[0-9]+") == false) {
            throw new MyException("目标只能输入数字");
        }
        crowdfundingMapper.updateTarget(target);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCrowdUser(Participant participant) throws MyException {
        //精网号重复
        if (crowdfundingMapper.queryCrowdUser(new Participant(null,participant.getJwcode(),null,null)) != null) {
            throw new MyException("精网号重复");
        }
        //精网号不能为空
        if (participant.getJwcode() == null) {
            throw new MyException("精网号不能为空");
        }
        //精网号不能为空
        if (participant.getIdentity() == null) {
            throw new MyException("身份不能为空");
        }
        crowdfundingMapper.updateNowNumber();
        crowdfundingMapper.addCrowdUser(participant);
    }

    @Override
    public void deleteCrowdUser(String jwcode) throws MyException {
        if (crowdfundingMapper.queryCrowdUser(new Participant(null,jwcode,null,null)) == null) {
            throw new MyException("删除失败,用户不存在");
        }
        List<Participant> participants = crowdfundingMapper.queryCrowdUser(new Participant(null, jwcode, null, null));
        Participant participant = participants.get(0);
        crowdfundingMapper.saveDeleteCrowdUser(participant);
        crowdfundingMapper.deleteCrowdUser(jwcode);
    }

    @Override
    public List<Participant> queryCrowdUser(Participant participant) {
        return crowdfundingMapper.queryCrowdUser(participant);
    }
}