package com.goafanti.RD.service.impl;

import com.goafanti.RD.bo.*;
import com.goafanti.RD.service.RDService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.RdDetailsMapper;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.RdDetails;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.common.utils.excel.NewExcelUtil;
import com.goafanti.common.utils.pdf.PDFUtils;
import com.goafanti.common.utils.word.WordUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class RDServiceImpl extends BaseMybatisDao<RdDetailsMapper> implements RDService {
    @Autowired
    private RdDetailsMapper rdDetailsMapper;


    @Value(value = "${upload.path}")
    private final String	uploadPath			= null;




    @Override
    public int add(RdDetails in) {
        in.setAid(TokenManager.getAdminId());
        in.setStatus(0);
        return rdDetailsMapper.insertSelective(in);
    }

    @Override
    public int update(InputRdDetails in) {
        return rdDetailsMapper.updateByPrimaryKeySelective(in);
    }

    @Override
    public int updateBrowseOrDownload(Long id, Integer type) {
        return rdDetailsMapper.updateBrowseOrDownload(id,type);
    }



    @Override
    public boolean checkRdNo(String rdNo, Long id) {
        int i = rdDetailsMapper.checkRdNo(rdNo,id);
        if (i>0)return true;
        return false;
    }



    @Override
    public OutRdDetails details(Long id) {
        return rdDetailsMapper.details(id);
    }

    @Override
    public Pagination<OutExcelRdDetails> list(InputRdList in) {
        Map<String, Object> param = getParam(in);

        return (Pagination<OutExcelRdDetails>) findPage("RdDetailsList","RdDetailsCount",param,in.getPageNo(), in.getPageSize());
    }

    private Map<String, Object> getParam(InputRdList in) {
        Map<String,Object> param=new HashMap<>();
        param.put("RdStart", in.getRdStart());
        param.put("RdNo", in.getRdNo());
        param.put("RdEnd", in.getRdEnd());
        param.put("RdName", in.getRdName());
        param.put("consultantName", in.getConsultantName());
        param.put("userName", in.getUserName());
        if (in.getStartTime()!=null&&in.getEndTime()!=null){
            param.put("startTime",in.getStartTime());
            param.put("endTime",in.getEndTime()+" 23:59:59");
        }
        if (TokenManager.hasRole(AFTConstants.SUPERADMIN)||TokenManager.hasRole(AFTConstants.APPROVAL_DECISION_ASSISTANT)||TokenManager.hasRole(AFTConstants.CED)){
        }else {
            param.put("aid", TokenManager.getAdminId());
        }
        return param;
    }

    @Override
    public Result exportList(InputRdList in, String uploadPath) {
        Map<String, Object> param = getParam(in);
        List<OutExcelRdDetails> list = (List<OutExcelRdDetails>) findList("RdDetailsList", param, 1, 999999);
        NewExcelUtil<OutExcelRdDetails> newExcelUtil=new NewExcelUtil<>(OutExcelRdDetails.class);
        return newExcelUtil.exportExcel(list,"研发活动信息",uploadPath);
    }

    @Override
    public Object batchList(MultipartFile file) {
        NewExcelUtil<InputExcelRdDetails> newExcelUtil=new NewExcelUtil<>(InputExcelRdDetails.class);
        List<InputExcelRdDetails> list = null;
        try {
            list = newExcelUtil.importExcel(file.getInputStream(),2);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }

        //新增
        return insertBatchList(list);
    }

    private Map<String,Object> insertBatchList(List<InputExcelRdDetails> list) {
        String aid=TokenManager.getAdminId();
        Date date =new Date();
        Map<String,Object> map=new HashMap<>();
        int OkCount=0;
        int RdCount=0;
        int erCount=0;
        List<String>errors=new ArrayList<>();
        for (InputExcelRdDetails in : list) {
            if (StringUtils.isNotEmpty(in.getRdName())){
                RdCount++;
                OkCount++;
                RdDetails details = rdDetailsMapper.selectByRDName(in.getRdName(),in.getUserName());
                if (details==null){
                    try {
                        in.setStatus(1);
                        in.setAid(aid);
                        in.setCreateTime(date);
                        rdDetailsMapper.insertSelective(in);
                    }catch (Exception e ){
                        int errorsCount=RdCount+3;
                        erCount++;
                        OkCount--;
                        errors.add(String.format("%s.数据第%s行，项目名称[%s]数据异常!",erCount,errorsCount,in.getRdName()));
                    }
                }else if (details.getAid().equals(TokenManager.getAdminId())) {
                    try {
                        in.setId(details.getId());
                        rdDetailsMapper.updateByPrimaryKeySelective(in);
                    }catch (Exception e ){
                        int errorsCount=RdCount+3;
                        erCount++;
                        OkCount--;
                        errors.add(String.format("%s.数据第%s行，项目名称[%s]数据更新异常!",erCount,errorsCount,in.getRdName()));
                    }
                }else {
                    int errorsCount=RdCount+3;
                    erCount++;
                    OkCount--;
                    errors.add(String.format("%s.数据第%s行，公司名称[%s]项目名称[%s]已被其他管理员录入!",erCount,errorsCount,in.getUserName(),in.getRdName()));
                }
            }
        }

//        if (relust.size()>0)insertBatch(relust);
        map.put("OK",OkCount);
        map.put("ERROR",errors);
        return map;
    }

    private void insertBatch(List<InputExcelRdDetails> relust) {
        List<InputExcelRdDetails> list=new ArrayList<>();
        for (int i = 0; i < relust.size(); i++) {
            list.add(relust.get(i));
            if (50 == list.size() || i == relust.size() - 1) {
                if (list.size() > 0) rdDetailsMapper.insertBatch(list);
                list.clear();
            }
        }
    }


    @Override
    public void pushDownloadDetailsWord(Long id, HttpServletResponse response) {
        OutWordRdDetails data = getOutWordRdDetails(id);

        WordUtils wordUtils=new WordUtils();
        wordUtils.pushWord(data,response,uploadPath);
    }


    @Override
    public void pushDownloadDetailsPDF(Long id, HttpServletResponse response) {
        OutWordRdDetails data = getOutWordRdDetails(id);
        PDFUtils pdfUtils=new PDFUtils();
        pdfUtils.pushRd(data,response,uploadPath);
    }

    private OutWordRdDetails getOutWordRdDetails(Long id) {
        OutRdDetails bo = rdDetailsMapper.details(id);
//        rdDetailsMapper.updateBrowseOrDownload(id, 1);
        OutWordRdDetails data = new OutWordRdDetails();
        BeanUtils.copyProperties(bo, data);
        if (bo.getRdStartStr() != null && bo.getRdEndStr() != null) {
            data.setStartEndTime(bo.getRdStartStr() + "～" + bo.getRdEndStr());
        } else {
            data.setStartEndTime("");
        }
        return data;
    }


}
