package com.artfess.cqxy.completionAcceptance.manager.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.artfess.base.context.BaseContext;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.PageBean;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.DateUtils;
import com.artfess.cqxy.completionAcceptance.dao.PreAcceptanceDao;
import com.artfess.cqxy.completionAcceptance.manager.PreAcceptanceManager;
import com.artfess.cqxy.completionAcceptance.model.PreAcceptance;
import com.artfess.cqxy.projectManagement.enums.ProjectStatusEnum;
import com.artfess.cqxy.projectManagement.manager.ProjectManagementManager;
import com.artfess.cqxy.projectManagement.model.ProjectManagement;
import com.artfess.cqxy.search.enums.FunctionEnum;
import com.artfess.cqxy.search.manager.GlobalRetrievalManager;
import com.artfess.cqxy.search.model.GlobalRetrieval;
import com.artfess.cqxy.universal.manager.AccessoryManager;
import com.artfess.cqxy.universal.model.Accessory;
import com.artfess.cqxy.utils.BizUtils;
import com.artfess.poi.util.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 竣工验收 - 预验收表（暂定）(BizPreAcceptance)表服务实现类
 *
 * @author 黎沐华
 * @since 2022-03-07 11:41:48
 */
@Service
public class PreAcceptanceManagerImpl extends BaseManagerImpl<PreAcceptanceDao, PreAcceptance> implements PreAcceptanceManager {

    @Autowired
    private AccessoryManager accessoryManager;

    @Autowired
    private BaseContext baseContext;

    @Autowired
    private ProjectManagementManager pmm;

    @Autowired
    private GlobalRetrievalManager grm;

    @Override
    public boolean saveOrUpdate(PreAcceptance entity) {
        boolean save = StringUtils.isEmpty(entity.getId());
        boolean savedMain = super.saveOrUpdate(entity);
        // 处理附件信息
        List<Accessory> flag = entity.getAccessoryInfo();//处理空指针
        List<Accessory> accessoryList = null == flag ? new ArrayList<>():flag;
        for (Accessory ele : accessoryList) {
            ele.setSourceId(entity.getId());
            ele.setProjectId(entity.getProjectId());
            ele.setDirectory(ProjectStatusEnum.ten.getCode());
            ele.setGroup("PreAcceptance");
            ele.setNode(ProjectStatusEnum.ten.getCode());
            ele.setCreateBy(baseContext.getCurrentUserId());
            ele.setCreateName(baseContext.getCurrentUserName());
            ele.setCreateTime(LocalDateTime.now());
        }
        // 先清空该ID下的所有附件信息再添加
        accessoryManager.removeBySourceId(entity.getId());
        // 如果没有附件则返回true，不进入添加
        boolean saveAcc = accessoryList.size() == 0 || accessoryManager.saveAccess(accessoryList);
        //更新项目状态-预验收不作为竣工验收判断条件
//        pmm.updateStatusById(entity.getProjectId(), Integer.valueOf(ProjectStatusEnum.twelve.getCode()));
        // 同步到检索表
        GlobalRetrieval globalRetrieval= grm.getByBizId(entity.getId());
        handleRetrieval(save || BeanUtils.isEmpty(globalRetrieval) ?new GlobalRetrieval():globalRetrieval,entity);

        return savedMain && saveAcc;
    }

    private void handleRetrieval(GlobalRetrieval globalRetrieval,PreAcceptance entity){
        ProjectManagement projectManagement = pmm.getById(entity.getProjectId());
        globalRetrieval.setProjectId(entity.getProjectId());
        globalRetrieval.setProjectName(projectManagement.getProjectName());
        globalRetrieval.setPersonCharge(projectManagement.getProjectManager());
        globalRetrieval.setArchivesType(1);
        globalRetrieval.setBizDataId(entity.getId());
        globalRetrieval.setFunctionCode(FunctionEnum.twentyThree.getCode());
        globalRetrieval.setFunctionName(FunctionEnum.twentyThree.getName());
        globalRetrieval.setBizTableName(FunctionEnum.twentyThree.getTableName());
        globalRetrieval.setDetailsRoteUrl(FunctionEnum.twentyThree.getTableRoteUrl());
        globalRetrieval.setTableRoteUrl(FunctionEnum.twentyThree.getTableRoteUrl());
        globalRetrieval.setTableApiUrl(FunctionEnum.twentyThree.getTableApiUrl());
        globalRetrieval.setDetailsApiUrl(FunctionEnum.twentyThree.getDetailsApiUrl());
        globalRetrieval.setFunctionPath(FunctionEnum.twentyThree.getFunctionPath());
        globalRetrieval.setSearchTitle(entity.getPreAcceptancePersonName()+"_"+entity.getPreSufReason()+"_"+entity.getRemarks());
        grm.saveOrUpdate(globalRetrieval);

    }

    @Override
    public boolean deleteByIds(List<String> ids) {
        // 同步删除检索表中的信息
        for(String ele:ids){
            grm.remove(1,ele);
        }
        return removeByIds(ids);
    }

    @Override
    public PreAcceptance getById(String id) {
        return baseMapper.getById(id);
    }

    @Override
    public PageList<PreAcceptance> queryAllByPage(QueryFilter<PreAcceptance> queryFilter) {
        BizUtils.handleFilter(queryFilter,"bpa" ,false);
        IPage<PreAcceptance> result =
                baseMapper.queryAllByPage(
                        convert2IPage(queryFilter.getPageBean()),
                        convert2Wrapper(queryFilter, currentModelClass()));
        // 附件信息处理
        List<PreAcceptance> records = result.getRecords();
        for (PreAcceptance ele: records ) {
            ele.setAccessoryInfo(accessoryManager.getAccessoryBySourceId(ele.getId()));
        }

        return new PageList<>(result);
    }

    @Override
    public void importExcelData(MultipartFile file, String projectId) {
        Assert.notNull(projectId,"项目ID不能为空");
        try(InputStream inputStream = file.getInputStream();) {
            // 获取数据
            List<PreAcceptance> data = ExcelImportUtil.importExcel(inputStream,PreAcceptance.class,new ImportParams());
            for(PreAcceptance ele:data){
                ele.setProjectId(projectId);
                // 保存数据 & 同步到检索表
                save(ele);
                handleRetrieval(new GlobalRetrieval(),ele);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportDatatoExcel(QueryFilter<PreAcceptance> queryFilter, HttpServletResponse response) throws IOException {
        String fileName = "竣工验收-预验收-导出结果";

        // 创建excel工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建excel表
        HSSFSheet sheet = workbook.createSheet(fileName);

        // 标题行
        // 拼接标题行数据
        List<String> heards = new ArrayList<>();
        // 注意：Arrays.asList 将会返回一个不可修改的List，不能在初始化时调用
        heards.addAll(Arrays.asList(new String[]{"项目名称","验收时间","验收地点","验收主题","参加单位","经办人","备注" }));

        // 创建标题行并写入数据
        HSSFRow titleRow1 = sheet.createRow(0);
        for (int i = 0; i < heards.size(); i++) {
            BizUtils.handelCell(workbook,fileName, titleRow1.createCell(i), heards.get(i));
        }

        // 数据行,从1行开始,共data.size行
        int row = 1;

        // 获取数据
        BizUtils.handleFilter(queryFilter,"bpa" ,false);
        List<PreAcceptance> data = baseMapper.queryAllByPage(
                        convert2IPage(new PageBean(0,-1,false)),
                        convert2Wrapper(queryFilter, currentModelClass())).
                getRecords();
        if(null==data||data.size()==0){
            throw new RuntimeException("没有要导出的的数据！");
        }

        // 处理数据
        for (int i = 0; i < data.size(); i++) {
            HSSFRow listRow = sheet.createRow(row);// 创建行
            BizUtils.handelCell(workbook,fileName, listRow.createCell(0),data.get(i).getProjectInfo().getProjectName());
            BizUtils.handelCell(workbook,fileName, listRow.createCell(1), DateUtils.date2Str(data.get(i).getPlanAcceptanceDate(),new SimpleDateFormat("yyyy-MM-dd")));
            BizUtils.handelCell(workbook,fileName, listRow.createCell(2),data.get(i).getPreAcceptanceUnit());
            BizUtils.handelCell(workbook,fileName, listRow.createCell(3), data.get(i).getPreAcceptancePersonId());
            BizUtils.handelCell(workbook,fileName, listRow.createCell(4), data.get(i).getPreSufReason());
            BizUtils.handelCell(workbook,fileName, listRow.createCell(5), data.get(i).getPreAcceptancePersonName());
            BizUtils.handelCell(workbook,fileName, listRow.createCell(6), data.get(i).getRemarks());
            row++;
        }

        sheet.setColumnWidth(0,7000);
        ExcelUtil.downloadExcel(workbook, fileName, response);

//        // 获取数据
//        BizUtils.handleFilter(queryFilter,"bpa" ,false);
//        List<PreAcceptance> data = baseMapper.queryAllByPage(
//                        convert2IPage(new PageBean(0,-1,false)),
//                        convert2Wrapper(queryFilter, currentModelClass())).
//                getRecords();
//        if(null==data||data.size()==0){
//            throw new RuntimeException("没有要导出的的数据！");
//        }
//
//        // EasyPoi 导出参数、样式、表格格式设置
//        ExportParams exportParams = BizUtils.getExportParams(fileName);
//        fileName += ".xlsx";
//
//        // 导出下载excel文件
//        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, PreAcceptance.class, data);
//        ExcelUtil.downloadExcel(workbook, fileName, response);
    }


    @Override
    public void updateProjectIdByProiectId(String oldProjectIds, String newProjectId) {
        UpdateWrapper<PreAcceptance> wrapper = new UpdateWrapper<PreAcceptance>()
                .set(StringUtils.isNotBlank(newProjectId), "PROJECT_ID_", newProjectId)
                .in("PROJECT_ID_", Arrays.asList(oldProjectIds.split(",")));
        this.update(wrapper);
    }

}

