package com.artfess.cqxy.bidManagement.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 cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
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.query.QueryOP;
import com.artfess.base.util.BeanUtils;
import com.artfess.cqxy.bidManagement.dao.BiddingPriceExamineDao;
import com.artfess.cqxy.bidManagement.manager.BiddingPriceExamineManager;
import com.artfess.cqxy.bidManagement.manager.BiddingPriceLimitManager;
import com.artfess.cqxy.bidManagement.model.BiddingPriceExamine;
import com.artfess.cqxy.projectApproval.model.DecisionAnnualPlan;
import com.artfess.cqxy.projectApproval.model.DecisionBasis;
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.cqxy.utils.EasyPoiStyle;
import com.artfess.poi.util.ExcelUtil;
import com.artfess.sysConfig.persistence.manager.SysDictionaryManager;
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.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 招投标管理 - 清单限价 - 审核(BiddingPriceExamine)表服务实现类
 *
 * @author 黎沐华
 * @since 2022-04-08 11:08:32
 */
@Service
public class BiddingPriceExamineManagerImpl extends BaseManagerImpl<BiddingPriceExamineDao, BiddingPriceExamine> implements BiddingPriceExamineManager {

    @Autowired
    private AccessoryManager accessoryManager;

    @Autowired
    private SysDictionaryManager sdm;

    @Autowired
    private BaseContext baseContext;

    @Autowired
    private GlobalRetrievalManager grm;

    @Autowired
    private ProjectManagementManager pmm;

    @Autowired
    private BiddingPriceLimitManager bplManager;

    @Override
    public boolean saveOrUpdate(BiddingPriceExamine 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("BiddingPriceExamine");
            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, BiddingPriceExamine 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.thirtyOne.getCode());
        globalRetrieval.setFunctionName(FunctionEnum.thirtyOne.getName());
        globalRetrieval.setBizTableName(FunctionEnum.thirtyOne.getTableName());
        globalRetrieval.setDetailsRoteUrl(FunctionEnum.thirtyOne.getTableRoteUrl());
        globalRetrieval.setTableRoteUrl(FunctionEnum.thirtyOne.getTableRoteUrl());
        globalRetrieval.setTableApiUrl(FunctionEnum.thirtyOne.getTableApiUrl());
        globalRetrieval.setDetailsApiUrl(FunctionEnum.thirtyOne.getDetailsApiUrl());
        globalRetrieval.setFunctionPath(FunctionEnum.thirtyOne.getFunctionPath());
        globalRetrieval.setDocumentNumber(String.valueOf(entity.getDocNumber()));
        globalRetrieval.setName(String.valueOf(entity.getName()));
        globalRetrieval.setSearchTitle(entity.getName() + "_" + entity.getTenderee() + "_" + entity.getDocNumber() + "_" +
                entity.getOwnerUnit() + "_" + entity.getProjectOverview() + entity.getTenderee() + "_" + entity.getHandler() + "_" + entity.getEstablishmentRemarks());
        grm.saveOrUpdate(globalRetrieval);
    }

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

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

    @Override
    public PageList<BiddingPriceExamine> queryAllByPage(QueryFilter<BiddingPriceExamine> queryFilter) {
//        BizUtils.handleFilter(queryFilter, "bbpl", "pm");

        queryFilter.addFilter("bbpe.IS_DELE_", "0", QueryOP.EQUAL);
        queryFilter.addFilter("pm.IS_DELE_", "0", QueryOP.EQUAL);
        IPage<BiddingPriceExamine> result =
                baseMapper.queryAllByPage(
                        convert2IPage(queryFilter.getPageBean()),
                        convert2Wrapper(queryFilter, currentModelClass()));
        // 附件信息处理
        List<BiddingPriceExamine> records = result.getRecords();
        for (BiddingPriceExamine ele : records) {
            ele.setAccessoryInfo(accessoryManager.getAccessoryBySourceId(ele.getId()));
        }

        return new PageList<>(result);
    }


    @Override
    public void importExcelData(MultipartFile file, String projectId, String priceLimitId) {
        Assert.notNull(projectId, "项目ID不能为空");
        Assert.notNull(priceLimitId, "清单信息ID不能为空");

        try(InputStream inputStream = file.getInputStream();) {
            // 获取数据
            List<BiddingPriceExamine> data = ExcelImportUtil.importExcel(inputStream,BiddingPriceExamine.class,new ImportParams());
            for(BiddingPriceExamine ele:data){
                ele.setProjectId(projectId);
                ele.setPriceLimitId(priceLimitId);
                try{
                    ele.setOwnerUnit(String.valueOf(ele.getDocNumber().divide(ele.getPriceCeiling(),4,BigDecimal.ROUND_HALF_EVEN).multiply(BigDecimal.valueOf(100))));
                }catch (Exception e){
                    ele.setOwnerUnit("0.00");
                }
                // 保存数据 & 同步到检索表
                save(ele);
                handleRetrieval(new GlobalRetrieval(),ele);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportDatatoExcel(QueryFilter<BiddingPriceExamine> queryFilter, HttpServletResponse response) throws IOException {
        String fileName = "招投标-清单限价-审核-导出结果";

        // 获取数据
        BizUtils.handleFilter(queryFilter, "bbpl", "pm");
        queryFilter.addFilter("bbpe.IS_DELE_", "0", QueryOP.EQUAL);
        List<BiddingPriceExamine> 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, BiddingPriceExamine.class, data);
        ExcelUtil.downloadExcel(workbook, fileName, response);
    }

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

}

