package com.mmc.iuav.user.service.impl;

import com.mmc.iuav.response.ResultBody;
import com.mmc.iuav.response.ResultEnum;
import com.mmc.iuav.user.dao.CompanyAuthDao;
import com.mmc.iuav.user.dao.CooperationDao;
import com.mmc.iuav.user.entity.CompanyAuthDO;
import com.mmc.iuav.user.entity.CooperationTagDO;
import com.mmc.iuav.user.entity.UserApplyTagDO;
import com.mmc.iuav.user.model.vo.CooperationTagVO;
import com.mmc.iuav.user.model.vo.UserApplyTagVO;
import com.mmc.iuav.user.service.CooperationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: zj
 * @Date: 2023/5/17 21:19
 */
@Service
public class CooperationServiceImpl implements CooperationService {
    @Autowired
    private CooperationDao cooperationDao;

    @Autowired
    private CompanyAuthDao companyAuthDao;

    @Override
    public ResultBody listTag() {
        List<CooperationTagDO> list = cooperationDao.listTags();
        List<CooperationTagVO> resList = list.stream().map(CooperationTagDO::buildCooperationTagVO).collect(Collectors.toList());
        return ResultBody.success(resList);
    }

    @Override
    public ResultBody apply(UserApplyTagVO userApplyTagVO) {
        //判断企业认证
        CompanyAuthDO companyAuthDO = companyAuthDao.getCompanyAuth(userApplyTagVO.getUserAccountId());
        if (companyAuthDO == null) {
            return ResultBody.error(ResultEnum.COMPANY_NOT_AUTH_ERROR);
        }
        UserApplyTagDO userApplyTagDO = new UserApplyTagDO(userApplyTagVO);
        //判断是否已加盟
        UserApplyTagDO existUserApplyTagDO = cooperationDao.getUserApplyTag(userApplyTagVO.getUserAccountId());
        if (existUserApplyTagDO != null) {
            if (existUserApplyTagDO.getApplyStatus().equals(0)){
                return ResultBody.error("已存在合作申请，待审核");
            }else if (existUserApplyTagDO.getApplyStatus().equals(1)){
                return ResultBody.success("已申请通过");
            }else {
                userApplyTagDO.setId(existUserApplyTagDO.getId());
                userApplyTagDO.setApplyStatus(0);
                cooperationDao.updateUserApplyTag(userApplyTagDO);
                return ResultBody.success();
            }
        }
        cooperationDao.addApply(userApplyTagDO);
        return ResultBody.success();
    }
}
