/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.quality.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.quality.entity.AssayReportW;
import com.tofly.quality.entity.AssayResMxW;
import com.tofly.quality.entity.AssayResultW;
import com.tofly.quality.entity.dto.AssayResultWQuery;
import com.tofly.quality.mapper.AssayConfigRMapper;
import com.tofly.quality.mapper.AssayReportWMapper;
import com.tofly.quality.service.AssayResMxWService;
import com.tofly.quality.service.AssayResultWService;
import com.tofly.quality.service.CollectWService;
import com.tofly.quality.service.comm.FileService;
import com.tofly.quality.unit.UploadFiles;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.tofly.quality.mapper.AssayResultWMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 化验结果
 *
 * @author admin
 * @date Thu Nov 03 00:00:00 CST 2022
 */
@Service("assayResultWService")
public class AssayResultWServiceImpl extends ServiceImpl<AssayResultWMapper, AssayResultW> implements AssayResultWService {
 @Autowired
 private AssayResMxWService assayResMxWService;
    @Value("${quality.ftp.build_result}")
    private String buildFilePath;
    @Autowired
    private FileService fileService;

    @Autowired
    private AssayReportWMapper assayReportWMapper;

    @Autowired
    private CollectWService collectWService;

    @Autowired
    private AssayConfigRMapper assayConfigRMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveAssayResult(List<MultipartFile> fileList, AssayResultW assayResultW, boolean isAdd) {
        // 判断当前是否有文件,则存入返回文件id
        String tableName = "TF_WATERQUALITY_ASSAY_RESULT_W";
        if(assayResultW.getAssayResultDetails()==null || assayResultW.getAssayResultDetails().stream().count()==0){
            throw new RuntimeException("化验项明细数据不能为空");

        }

        Long count=collectWService.getCollectList(assayResultW.getId()).stream().filter(a->a.getCollectNo().equals(assayResultW.getCollectNo())).count();
        if(count==0){
            throw new RuntimeException("水样编号:"+assayResultW.getCollectNo()+"已经有对应的化验结果,请重新选择");
        }

          boolean flag=false;
        if (isAdd) {
            if (CollUtil.isNotEmpty(fileList)) {
                String fileIds = UploadFiles.saveFiles(fileService, fileList, assayResultW.getUploadFileids(), assayResultW.getUploadFileids(),
                        buildFilePath, tableName);
                if (!StringUtil.isEmpty(fileIds)) {
                    assayResultW.setUploadFileids(fileIds);
                }
            }

            String baseNo="HYJG";

            Date now = new Date(); // 创建一个Date对象，获取当前时间
            String strDateFormat = "yyyyMMdd";
            String start_no = baseNo + DateFormatUtils.format(now, strDateFormat);
            //获取当天最大的采样编号
            String Sample_No = this.baseMapper.getResultMaxNo(start_no);

            int firstNum = 1;
            if (Sample_No.length() == 16) {
                firstNum = Integer.parseInt(Sample_No.substring(11)) + 1;
            }

            String end_no = String.format("%04d", firstNum); //补全数字，不足用0补位

            assayResultW.setAssayResultNo(start_no+end_no);


            flag=this.save(assayResultW);
        } else {
            String fileIds=assayResultW.getUploadFileids();
            if(StringUtil.isNotEmpty(assayResultW.getUploadFileids())){
                fileIds=assayResultW.getUploadFileids();
                if(fileIds.equals("[]")){
                    fileIds="";
                }
            }
            if(StringUtil.isEmpty(assayResultW.getRemark()) ||
                    assayResultW.getRemark().equals("null")){
                assayResultW.setRemark("");
            }
            AssayResultW data_old= this.getById(assayResultW.getId());
            String fileIdsList = UploadFiles.saveFiles(fileService, fileList, data_old.getUploadFileids(), fileIds,
                    buildFilePath, tableName);

            assayResultW.setUploadFileids(fileIdsList);

            assayResMxWService.remove(Wrappers.<AssayResMxW>lambdaQuery()
                    .eq(AssayResMxW::getAssayResultId, assayResultW.getId()));
            assayResultW.setAssayResultNo(null);
            flag=this.updateById(assayResultW);
        }
        for (AssayResMxW detail:assayResultW.getAssayResultDetails()
        ) {
            detail.setAssayResultId(assayResultW.getId());
            detail.setCollectNo(assayResultW.getCollectNo());
            assayResMxWService.save(detail);
        }
        return flag;
    }

    @Override
    public Page<AssayResultW> getPageData(Page page, AssayResultWQuery query) {
        if (query.getStartTime() != null && query.getStartTime() != null) {
            if (query.getStartTime().getTime() > query.getEndTime().getTime()) {
                throw new RuntimeException("开始时间不能大于结束时间");
            }
        }

        return this.baseMapper.getPageData(page, query);
    }

    @Override
    public boolean deleteByIds(String ids) {
        List<String> list = Arrays.asList(ids.split(","));

       Integer  count_check =0;
        count_check=assayReportWMapper.selectCount(Wrappers.<AssayReportW>lambdaQuery()
                .in(AssayReportW::getAssayResultId,list));
        if (count_check > 0) {
            throw new RuntimeException("化验结果已经生成了对应的报告，不能删除");
        }
        Integer isDelRoot=assayConfigRMapper.isDeleteRoot(SecurityUtils.getUserId());
        if(isDelRoot==0){
        count_check= this.baseMapper.selectCount(Wrappers.<AssayResultW>lambdaQuery()
                .in(AssayResultW::getId,list)
                .ne(AssayResultW::getCreateUser,SecurityUtils.getUserId()));

         if (count_check > 0) {
            throw new RuntimeException("只能删除自己创建的数据");
         }
        }
        //删除明细数据
        assayResMxWService.remove(Wrappers.<AssayResMxW>lambdaQuery()
                .in(AssayResMxW::getAssayResultId,list));
        return this.removeByIds(list);
    }

    @Override
    public List<AssayResultW> getResultList(Long assayReportId) {
        if(assayReportId==null){
            assayReportId=0L;
        }
       return this.baseMapper.getResultList(assayReportId);
    }

}

