package com.tofly.project.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.haiqiu.tools.excel.utils.ExcelUtils;
import com.tofly.common.constant.Constant;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.common.service.IFileInfoService;
import com.tofly.project.entity.ProjectConstruction;
import com.tofly.project.entity.ProjectRegistration;
import com.tofly.project.entity.ProjectSupervision;
import com.tofly.project.entity.vo.ProjectOtherSupervisionVo;
import com.tofly.project.service.ProjectConstructionService;
import com.tofly.project.service.ProjectRegistrationService;
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.ProjectOtherSupervisionMapper;
import com.tofly.project.entity.ProjectOtherSupervision;
import com.tofly.project.entity.dto.ProjectOtherSupervisionDto;
import com.tofly.project.service.ProjectOtherSupervisionService;
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;

/**
 * (ProjectOtherSupervision)表服务实现类
 *
 * @author HaiQiu
 * @since 2022-11-14 11:56:45
 */
@Service("projectOtherSupervisionService")
public class ProjectOtherSupervisionServiceImpl extends ServiceImpl<ProjectOtherSupervisionMapper, ProjectOtherSupervision> implements ProjectOtherSupervisionService {

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

    @Resource
    private ProjectSupervisionService projectSupervisionService;

    @Resource
    private ProjectRegistrationService projectRegistrationService;

    @Resource
    private ProjectConstructionService projectConstructionService;


    /**
     * 根据ID查询
     *
     * @param id id
     * @return 数据
     */
    @Override
    public ProjectOtherSupervision get(Serializable id) {
        ProjectOtherSupervision supervision = getById(id);
        if (!ObjectUtils.isEmpty(supervision)) {
            //查询绑定的登记和监管信息父级
            List<ProjectSupervision> supervisionList = projectSupervisionService.list(Wrappers.<ProjectSupervision>lambdaQuery()
                    .eq(ProjectSupervision::getId, supervision.getProjectSupervisionId()));
            List<ProjectRegistration> registrations = projectRegistrationService.list(Wrappers.<ProjectRegistration>lambdaQuery()
                    .eq(ProjectRegistration::getId, supervision.getProjectId()));
            List<ProjectConstruction> constructions = projectConstructionService.list(Wrappers.<ProjectConstruction>lambdaQuery()
                    .eq(ProjectConstruction::getId, supervision.getProjectConstructionId()));
            supervision.setProjectSupervision(!CollectionUtils.isEmpty(supervisionList) ? supervisionList.get(0) : null);
            supervision.setProjectRegistration(!CollectionUtils.isEmpty(registrations) ? registrations.get(0) : null);
            supervision.setProjectConstruction(!CollectionUtils.isEmpty(constructions) ? constructions.get(0) : null);
        }
        return supervision;
    }

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

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

    /**
     * 实体转换
     *
     * @param projectOtherSupervisionDto dto实体
     */
    private ProjectOtherSupervision convert(ProjectOtherSupervisionDto projectOtherSupervisionDto) {
        ProjectOtherSupervision projectOtherSupervision = new ProjectOtherSupervision();
        BeanUtils.copyProperties(projectOtherSupervisionDto, projectOtherSupervision);
        //自动获取监管人
        if (projectOtherSupervision.getSupervise() == null) {
            projectOtherSupervision.setSupervise(SecurityUtils.getUserId());
        }
        //自动获取监管时间
        if (projectOtherSupervision.getSuperviseTime() == null) {
            projectOtherSupervision.setSuperviseTime(new Date());
        }
        return projectOtherSupervision;
    }

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

    /**
     * 生成模板下载
     */
    @Override
    public void template() {
        ProjectOtherSupervision projectOtherSupervision = new ProjectOtherSupervision();
        ExcelUtils.createTemplate("第三方施工监管", "第三方施工监管",
                "第三方施工监管", ProjectOtherSupervision.class, Collections.singletonList(projectOtherSupervision));
    }

    /**
     * 数据导入
     *
     * @param file 文件
     */
    @Override
    public void importData(MultipartFile file) {
        List<ProjectOtherSupervision> datas = ExcelUtils.getExcelToList("第三方施工监管", file, ProjectOtherSupervision.class);
        if (!CollectionUtils.isEmpty(datas)) {
            saveBatch(datas);
        }
    }

    /**
     * 分页查询
     *
     * @param page                    分页
     * @param projectOtherSupervision 查询wrapper
     * @return 数据集合
     */
    @Override
    public Page<ProjectOtherSupervisionVo> pageList(Page page, ProjectOtherSupervisionVo projectOtherSupervision) {
        QueryWrapper<Object> wrapper = getQueryWrapper(projectOtherSupervision);
        return baseMapper.pageList(page, wrapper);
    }


    /**
     * 构建查询条件
     *
     * @param projectOtherSupervision
     * @return
     */
    private QueryWrapper<Object> getQueryWrapper(ProjectOtherSupervisionVo projectOtherSupervision) {
        QueryWrapper<Object> wrapper = new QueryWrapper<>();
        wrapper.between(projectOtherSupervision.getStartTime() != null && projectOtherSupervision.getEndTime() != null, "os.CREATE_TIME"
                        , projectOtherSupervision.getStartTime(), projectOtherSupervision.getEndTime()).orderByDesc("os.CREATE_TIME")
                .ne("os.DELETED", Constant.DELETED)
                .eq(projectOtherSupervision.getProjectType() != null, "p.DATA_TYPE", projectOtherSupervision.getProjectType())
                .and(StringUtils.hasText(projectOtherSupervision.getSearchStr()), w -> {
                    w.like("p.NAME", projectOtherSupervision.getSearchStr())
                            .or()
                            .like("p.ADDRESS", projectOtherSupervision.getSearchStr())
                            .or()
                            .like("p.ID", projectOtherSupervision.getSearchStr());
                });
        return wrapper;
    }

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

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

