package com.tofly.project.service.impl;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.haiqiu.tools.excel.utils.ExcelUtils;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.service.IFileInfoService;
import com.tofly.project.entity.ProjectOtherSupervision;
import com.tofly.project.entity.ProjectSupervision;
import com.tofly.project.entity.dto.ProjectSearchDto;
import com.tofly.project.service.ProjectOtherSupervisionService;
import com.tofly.project.service.ProjectSupervisionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.project.mapper.ProjectRegistrationMapper;
import com.tofly.project.entity.ProjectRegistration;
import com.tofly.project.entity.dto.ProjectRegistrationDto;
import com.tofly.project.service.ProjectRegistrationService;
import org.springframework.stereotype.Service;

import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.io.Serializable;

/**
 * 工程登记(ProjectRegistration)表服务实现类
 *
 * @author HaiQiu
 * @since 2022-11-14 11:56:46
 */
@Service("projectRegistrationService")
public class ProjectRegistrationServiceImpl extends ServiceImpl<ProjectRegistrationMapper, ProjectRegistration> implements ProjectRegistrationService {

    @Value("${dcsw.ftp.project.projectRegistration:/dcsw/project/projectRegistration}")
    private String path;
    @Autowired
    private IFileInfoService fileInfoService;

    @Resource
    private ProjectOtherSupervisionService projectOtherSupervisionService;

    @Resource
    private ProjectSupervisionService projectSupervisionService;


    /**
     * 根据ID查询
     *
     * @param id id
     * @return 数据
     */
    @Override
    public ProjectRegistration get(Serializable id) {
        ProjectRegistration registration = getById(id);
        if (!ObjectUtils.isEmpty(registration)) {
            //获取工程监管信息
            List<ProjectSupervision> projectSupervisions = projectSupervisionService.list(Wrappers.<ProjectSupervision>lambdaQuery()
                    .eq(ProjectSupervision::getProjectId, registration.getId()));
            registration.setProjectSupervisions(projectSupervisions);
            //获取第三方工程监管信息
            List<ProjectOtherSupervision> otherSupervisions = projectOtherSupervisionService.list(Wrappers.<ProjectOtherSupervision>lambdaQuery()
                    .eq(ProjectOtherSupervision::getProjectId, registration.getId()));
            registration.setProjectOtherSupervisions(otherSupervisions);
        }
        return registration;
    }

    /**
     * 新增
     *
     * @param projectRegistrationDto 实体
     * @param files
     */
    @Override
    public void insert(ProjectRegistrationDto projectRegistrationDto, List<MultipartFile> files) {
        ProjectRegistration projectRegistration = convert(projectRegistrationDto);
        projectRegistration.setAnnex(fileInfoService.uploadFiles(files, projectRegistration.getAnnex()
                , projectRegistration.getAnnex(), path, "FLOW_PROJECT_REGISTRATION"));
        if (!save(projectRegistration)) {
            throw new RuntimeException("新增失败");
        }
    }

    /**
     * 修改
     *
     * @param projectRegistrationDto 实体
     * @param files
     */
    @Override
    public void edit(ProjectRegistrationDto projectRegistrationDto, List<MultipartFile> files) {
        ProjectRegistration projectRegistration = convert(projectRegistrationDto);
        projectRegistration.setAnnex(fileInfoService.uploadFiles(files, projectRegistration.getAnnex()
                , projectRegistration.getAnnex(), path, "FLOW_PROJECT_CONSTRUCTION"));
        if (!updateById(projectRegistration)) {
            throw new RuntimeException("修改失败");
        }
    }

    /**
     * 实体转换
     *
     * @param projectRegistrationDto dto实体
     */
    private ProjectRegistration convert(ProjectRegistrationDto projectRegistrationDto) {
        ProjectRegistration projectRegistration = new ProjectRegistration();
        BeanUtils.copyProperties(projectRegistrationDto, projectRegistration);
        //自动生成工程编号
        if (!StringUtils.hasText(projectRegistration.getNumberNo())){
            projectRegistration.setNumberNo("GC"+ DateUtil.getDateFormat(new Date(),"yyyyMMdd")
                    + RandomUtil.randomNumbers(4));
        }
        return projectRegistration;
    }

    /**
     * 批量删除
     *
     * @param idList 数据ID集合
     */
    @Override
    public void delete(List<Long> idList) {
        if (!removeByIds(idList)) {
            throw new RuntimeException("删除失败");
        }
    }

    /**
     * 生成模板下载
     */
    @Override
    public void template() {
        ProjectRegistration projectRegistration = new ProjectRegistration();
        ExcelUtils.createTemplate("工程登记", "工程登记",
                "工程登记", ProjectRegistration.class, Collections.singletonList(projectRegistration));
    }

    /**
     * 数据导入
     *
     * @param file 文件
     */
    @Override
    public void importData(MultipartFile file) {
        List<ProjectRegistration> datas = ExcelUtils.getExcelToList("工程登记", file, ProjectRegistration.class);
        if (!CollectionUtils.isEmpty(datas)) {
            saveBatch(datas);
        }
    }

    /**
     * 分页查询
     *
     * @param page                分页
     * @param projectRegistration 查询wrapper
     * @param projectSearchDto
     * @return 数据集合
     */
    @Override
    public Page<ProjectRegistration> pageList(Page page, ProjectRegistration projectRegistration, ProjectSearchDto projectSearchDto) {
        LambdaQueryWrapper<ProjectRegistration> wrapper = Wrappers.<ProjectRegistration>lambdaQuery(projectRegistration);
        if (projectSearchDto != null) {
            wrapper.and(StringUtils.hasText(projectSearchDto.getSearchStr()), w -> {
                w.like(ProjectRegistration::getAddress, projectSearchDto.getSearchStr())
                        .or()
                        .like(ProjectRegistration::getName, projectSearchDto.getSearchStr())
                        .or()
                        .like(ProjectRegistration::getId, projectSearchDto.getSearchStr());
            }).between(projectSearchDto.getStartTime() != null && projectSearchDto.getEndTime() != null,
                    ProjectRegistration::getCreateTime, projectSearchDto.getStartTime(), projectSearchDto.getEndTime());
        }
        return page(page, wrapper);
    }

    /**
     * 数据导出
     *
     * @param page                分页
     * @param projectRegistration 查询模型
     * @param isAll               是否导出全部数据，true是，false否
     */
    @Override
    public void export(Page page, ProjectRegistration projectRegistration, Boolean isAll) {
        Page<ProjectRegistration> pageData = new Page<>();
        if (isAll == null || !isAll) {
            pageData = page(page, new QueryWrapper<>(projectRegistration)).addOrder(page.getOrders());
        } else {
            pageData.setRecords(list(new QueryWrapper<>(projectRegistration)));
        }
        //导出数据
        ExcelUtils.getListToExcel(ProjectRegistration.class, pageData.getRecords(), "工程登记");
    }

    /**
     * 查询所有数据
     *
     * @param projectRegistration 查询条件
     * @return 查询所有数据
     */
    @Override
    public List<ProjectRegistration> allList(ProjectRegistration projectRegistration) {
        return list(new QueryWrapper<>(projectRegistration));
    }
}

