/*
 * 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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
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.dto.AssayReportWQuery;
import com.tofly.quality.mapper.AssayConfigRMapper;
import com.tofly.quality.service.AssayReportWService;
import com.tofly.quality.service.AssayResultWService;
import com.tofly.quality.service.comm.FileService;
import com.tofly.quality.unit.UploadFiles;
import lombok.extern.slf4j.Slf4j;
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.AssayReportWMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 化验报告管理
 *
 * @author admin
 * @date Thu Nov 03 00:00:00 CST 2022
 */
@Slf4j
@Service("assayReportWService")
public class AssayReportWServiceImpl extends ServiceImpl<AssayReportWMapper, AssayReportW> implements AssayReportWService {

    @Value("${quality.ftp.build_report}")
    private String buildFilePath;
    @Autowired
    private FileService fileService;
    @Autowired
    private AssayResultWService assayResultWService;
    @Autowired
    private AssayConfigRMapper assayConfigRMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAssayReport(List<MultipartFile> fileList, AssayReportW assayReportW, boolean isAdd) {
        // 判断当前是否有文件,则存入返回文件id
        String tableName = "TF_WATERQUALITY_ASSAY_REPORT_W";

        Long count=assayResultWService.getResultList(assayReportW.getId()).stream().filter(a->a.getId().equals(assayReportW.getAssayResultId())).count();
        if(count==0){
            throw new RuntimeException("选择的化验结果数据已经有对应的化验报告,请重新选择");
        }

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


            if (StringUtil.isEmpty(assayReportW.getFileState())) {
                assayReportW.setFileState("0");
            }

            String baseNo="HYBG";

            Date now = new Date(); // 创建一个Date对象，获取当前时间
            String strDateFormat = "yyyyMMdd";
            String start_no = baseNo + DateFormatUtils.format(now, strDateFormat);
            //获取当天最大的采样编号
            String Sample_No = this.baseMapper.getReportMaxNo(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补位

            assayReportW.setReportNo(start_no+end_no);

            return this.save(assayReportW);
        } else {

            String fileIds=assayReportW.getUploadFileids();
            if(StringUtil.isNotEmpty(assayReportW.getUploadFileids())){
                fileIds=assayReportW.getUploadFileids();
                if(fileIds.equals("[]")){
                    fileIds="";
                }
            }
            if(StringUtil.isEmpty(assayReportW.getRemark()) ||
                    assayReportW.getRemark().equals("null")){
                assayReportW.setRemark("");
            }
            if(StringUtil.isEmpty(assayReportW.getEnvironmentInfo()) ||
                    assayReportW.getEnvironmentInfo().equals("null")){
                assayReportW.setEnvironmentInfo("");
            }
            AssayReportW  data_old= this.getById(assayReportW.getId());
            if(data_old.getFileState().equals("1")){
                throw  new RuntimeException("已归档的报告不能修改");

            }

            String fileIdsList = UploadFiles.saveFiles(fileService, fileList, data_old.getUploadFileids(), fileIds,
                    buildFilePath, tableName);

            assayReportW.setUploadFileids(fileIdsList);
            assayReportW.setReportNo(null);
            return this.updateById(assayReportW);
        }

    }

    @Override
    public Page<AssayReportW> getPageData(Page page, AssayReportWQuery 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(","));
        QueryWrapper<AssayReportW> R_queryWrapper = new QueryWrapper<>();
        R_queryWrapper.in("ID", list);
        R_queryWrapper.ne("CREATE_USER", SecurityUtils.getUserId());

        Integer isDelRoot=assayConfigRMapper.isDeleteRoot(SecurityUtils.getUserId());
       if(isDelRoot==0) {
           Integer count_check = this.baseMapper.selectCount(R_queryWrapper);
           if (count_check > 0) {
               throw new RuntimeException("只能删除自己创建的并且没有归档的数据");
           }
           R_queryWrapper.clear();
           R_queryWrapper.in("ID", list);
           R_queryWrapper.eq("FILE_STATE", "1");
           count_check = this.baseMapper.selectCount(R_queryWrapper);
           if (count_check > 0) {
               throw new RuntimeException("只能删除自己创建的并且没有归档的数据");
           }
       }
        return this.removeByIds(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean synFile(String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        for (String id : list
        ) {
            AssayReportW model = new AssayReportW();
            model.setId(Long.parseLong(id));
            model.setFileState("1");
            this.baseMapper.updateById(model);
        }
        return true;
    }

}
