package com.sptg.estate.biz.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.estate.api.entity.ProjectCompletion;
import com.sptg.estate.biz.mapper.ProjectCompletionMapper;
import com.sptg.estate.biz.service.ProjectCompletionServiceInterface;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * title: ProjectServiceImpl
 * package: com.sptg.estate.biz.security
 * description: 物业验收-服务层实现层
 *
 *               
 *                     
 */
@Service
public class ProjectCompletionServiceImpl extends ServiceImpl<ProjectCompletionMapper, ProjectCompletion> implements ProjectCompletionServiceInterface {

    @Override
    public ResultBean<Boolean> insertProjectCompletion(ProjectCompletion projectCompletion) {
        if(this.countByProjectId(projectCompletion.getProjectId()).getData()){
            return new ResultBean<>(ResultEnum.SUCCESS,false);
        }else{
            Boolean result;
            projectCompletion.setOrderNo(this.getOrderNo());
            result = this.insert(projectCompletion);
            return new ResultBean<>(ResultEnum.SUCCESS,result);
        }
    }

    @Override
    public ResultBean<ProjectCompletion> findByProjectId(Long projectId) {
        Wrapper<ProjectCompletion> wrapper = new EntityWrapper<>();
        wrapper.eq("l_project_id",projectId);
        return new ResultBean<>(ResultEnum.SUCCESS,this.selectOne(wrapper));
    }

    @Override
    public ResultBean<Boolean> countByProjectId(Long projectId) {
        Wrapper<ProjectCompletion> wrapper = new EntityWrapper<>();
        //项目id
        wrapper.eq("l_project_id", projectId);
        int count = this.selectCount(wrapper);
        if(count>0){
            return new ResultBean<>(ResultEnum.SUCCESS,true);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,false);
    }

    /**
     * 生成竣工单号
     *
     */
    private String getOrderNo(){
        //获取时间对象
        Date date = new Date();
        //获取日期字符串
        String s = new SimpleDateFormat("yyMMdd").format(date);
        Wrapper<ProjectCompletion> wrapper = new EntityWrapper<>();
        wrapper.like("s_order_no",s);
        //统计当天新增的广告条数
        int count = this.selectCount(wrapper);
        //广告编号的格式用yyMMdd+2位排序号前面补0
        return (s+(count<9?("0"+(count+1)):++count));
    }
}
