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

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
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.cqxy.bidManagement.dao.BidManagementDao;
import com.artfess.cqxy.bidManagement.manager.BidManagementManager;
import com.artfess.cqxy.bidManagement.model.BidManagement;
import com.artfess.cqxy.projectApproval.model.DecisionAnnualPlan;
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.artfess.sysConfig.persistence.manager.SysDictionaryManager;
import com.artfess.sysConfig.persistence.param.DictModel;
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.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
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.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 招投标管理 - 投标管理表(BidManagement)表服务实现类
 *
 * @author 黎沐华
 * @since 2022-04-08 15:34:31
 */
@Service
public class BidManagementManagerImpl extends BaseManagerImpl<BidManagementDao, BidManagement> implements BidManagementManager {

    @Autowired
    private AccessoryManager accessoryManager;

    @Autowired
    private SysDictionaryManager sdm;

    @Autowired
    private BaseContext baseContext;


    @Autowired
    private GlobalRetrievalManager grm;

    @Autowired
    private ProjectManagementManager pmm;

    @Override
    public boolean saveOrUpdate(BidManagement 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.eight.getCode());
            ele.setGroup("BidManagement");
            ele.setNode(ProjectStatusEnum.eight.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.eight.getCode()));
        // 同步到检索表
        GlobalRetrieval globalRetrieval= grm.getByBizId(entity.getId());
        handleRetrieval(save || BeanUtils.isEmpty(globalRetrieval) ?new GlobalRetrieval():globalRetrieval,entity);


        return savedMain && saveAcc;
    }

    private void handleRetrieval(GlobalRetrieval globalRetrieval,BidManagement 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.thirteen.getCode());
        globalRetrieval.setFunctionName(FunctionEnum.thirteen.getName());
        globalRetrieval.setBizTableName(FunctionEnum.thirteen.getTableName());
        globalRetrieval.setDetailsRoteUrl(FunctionEnum.thirteen.getTableRoteUrl());
        globalRetrieval.setTableRoteUrl(FunctionEnum.thirteen.getTableRoteUrl());
        globalRetrieval.setTableApiUrl(FunctionEnum.thirteen.getTableApiUrl());
        globalRetrieval.setDetailsApiUrl(FunctionEnum.thirteen.getDetailsApiUrl());
        globalRetrieval.setFunctionPath(FunctionEnum.thirteen.getFunctionPath());
        globalRetrieval.setDocumentNumber(entity.getDocumentNumber());
        globalRetrieval.setName(entity.getName());
        globalRetrieval.setSearchTitle(entity.getName()+"_"+entity.getTenderee()+"_"+entity.getBiddingAgency()+"_"+
                entity.getBiddingRange()+"_"+entity.getProjectOverview());
        grm.saveOrUpdate(globalRetrieval);
    }

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

    @Override
    public BidManagement getById(String id) {
        BidManagement result = baseMapper.getById(id);
        result.setAccessoryInfo(accessoryManager.getAccessoryBySourceId(id));
        return result;
    }

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

        return new PageList<>(result);
    }

    @Override
    public void importExcelData(MultipartFile file, String projectId) {
        Assert.notNull(projectId,"项目ID不能为空");
        // 获取字典
        List<DictModel> bidOf = sdm.queryDictListItemsByCode("tbgl-sfzb");
        try {
            //1、获取文件输入流
            InputStream inputStream = file.getInputStream();
            //2、获取Excel工作簿对象
            Workbook workbook = WorkbookFactory.create(inputStream);
            //3、得到Excel工作表对象
            Sheet sheetAt = workbook.getSheetAt(0);
            //4、循环读取表格数据
            for (Row row : sheetAt) {
                //首行（表头）不读取
                if (row.getRowNum() == 0) {
                    continue;
                }
                //读取当前行中单元格数据并赋值到对象，索引从0开始
                BidManagement data = new BidManagement();
                //处理单元格数据可能为空 getCell将会抛出空指针的问题
                data.setDocumentNumber(null==row.getCell(0)?row.createCell(0).getStringCellValue():row.getCell(0).getStringCellValue());
                data.setProjectOverview(null==row.getCell(1)?row.createCell(1).getStringCellValue():row.getCell(1).getStringCellValue());
                data.setTenderee(null==row.getCell(2)?row.createCell(2).getStringCellValue():row.getCell(2).getStringCellValue());
                data.setBiddingChargePerson(null==row.getCell(3)?row.createCell(3).getStringCellValue():row.getCell(3).getStringCellValue());
                data.setBiddingAgency(null==row.getCell(4)?row.createCell(4).getStringCellValue():row.getCell(4).getStringCellValue());
                data.setBiddingDate(null==row.getCell(5)?row.createCell(5).getDateCellValue():row.getCell(5).getDateCellValue());
                data.setBiddingFixedPrice(null==row.getCell(6)?row.createCell(6).getStringCellValue():row.getCell(6).getStringCellValue());
                data.setBiddingRange(null==row.getCell(7)?row.createCell(7).getStringCellValue():row.getCell(7).getStringCellValue());
                data.setConstructionControlUnit(null==row.getCell(8)?row.createCell(8).getStringCellValue():row.getCell(8).getStringCellValue());
                data.setTestingUnit(null==row.getCell(9)?row.createCell(9).getStringCellValue():row.getCell(9).getStringCellValue());
                data.setPlannedConstructionPeriod(null==row.getCell(10)?row.createCell(10).getStringCellValue():row.getCell(10).getStringCellValue());
                data.setBidAmount(null==row.getCell(11)?row.createCell(11).getStringCellValue():row.getCell(11).getStringCellValue());
                data.setBidDate(null==row.getCell(12)?row.createCell(12).getDateCellValue():row.getCell(12).getDateCellValue());
//                data.setBidOf(BizUtils.getDicCodeByValue_Int(bidOf,null==row.getCell(13)?row.createCell(13).getStringCellValue():row.getCell(13).getStringCellValue()));
                data.setEstablishmentRemarks(null==row.getCell(14)?row.createCell(14).getStringCellValue():row.getCell(14).getStringCellValue());
                data.setProjectId(projectId);
                data.setName(pmm.get(projectId).getProjectName());
                baseMapper.insert(data);
                // 同步到检索表
                handleRetrieval(new GlobalRetrieval(),data);
            }
            //5、关闭流
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportDatatoExcel(QueryFilter<BidManagement> queryFilter, HttpServletResponse response) throws IOException {
        // 获取字典
        List<DictModel> bidOf = sdm.queryDictListItemsByCode("tbgl-sfzb");

        String fileName = "投标信息-导出结果";

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

        // 翻译字典
        for(BidManagement ele : data){
            ele.setBidOf(BizUtils.getDicValueByCode(bidOf, ele.getBidOf()));
        }

        // EasyPoi 导出参数、样式、表格格式设置
        ExportParams exportParams = BizUtils.getExportParams(fileName);
        fileName += ".xlsx";

        // 导出下载excel文件
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, BidManagement.class, data);
        ExcelUtil.downloadExcel(workbook, fileName, response);
    }

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

}

