package com.jwipc.tender.controller.pc;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Pair;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import com.jwipc.dto.ExportDataDTO;
import com.jwipc.log.annotation.AuditLogInter;
import com.jwipc.page.PageView;
import com.jwipc.tender.constant.ModuleConst;
import com.jwipc.tender.dto.*;
import com.jwipc.tender.logic.BenchmarksLogic;
import com.jwipc.tender.logic.TenderTemplateLogic;
import com.jwipc.tender.model.query.TenderQuery;
import com.jwipc.util.EasyExcelImportUtils;
import com.jwipc.util.EasyExcelUtils;
import com.jwipc.util.FileNameUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.jwipc.tender.constant.ModuleConst.MODULE_ROOT;

/**
 * <p>定标管理相关页面</p>
 *
 * @author ZhangJie
 * @version 1.0
 * @since JDK 1.8
 */
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping(ModuleConst.MODULE_ROOT + "/benchmarks/rest")
public class BenchmarksRestController {
    private final BenchmarksLogic benchmarksLogic;
    private final TenderTemplateLogic tenderTemplateLogic;

    /**
     * 定标管理 列表页面
     *
     * @return
     */
    @GetMapping("list")
    @AuditLogInter(module = "定标管理",value = "列表页面")
    public PageView list(TenderQuery query) {
        return benchmarksLogic.getList(query);
    }

    @GetMapping("approvelList")
    public PageView approvelList(Long id) {
        return benchmarksLogic.getApprovelList(id);
    }

    /**
     * 投标单定标详情页面
     *
     * @param type 0:查看;1:定标
     * @param id   招标单id
     * @return
     * @see com.jwipc.tender.constant.TenderOptType
     */
    @GetMapping("detail")
    @AuditLogInter(module = "定标管理",value = "投标单定标详情页面")
    public String detail(@RequestParam(required = false, defaultValue = "0") Long id,
                         @RequestParam(required = false, defaultValue = "0") Long tenderId,
                         Model model,
                         @RequestParam(required = false, defaultValue = "0") Integer type)
    {
        model.addAttribute("tenderId", tenderId);
        model.addAttribute("type", type);
        return MODULE_ROOT + "/benchmarks/detail";
    }

    /**
     * 定标明细中获取报价明细
     *
     * @param id 招标单id
     * @return
     */
    @GetMapping("getQuoteDetails")
    @AuditLogInter(module = "定标管理",value = "获取报价明细")
    public PageView getQuoteDetails(Long id) {
        return benchmarksLogic.getQuoteDetails(id);
    }

    /**
     * 供应商投标全部附件
     *
     * @param tenderId 招标单id
     * @return
     */
    @GetMapping("getBidFileList")
    @AuditLogInter(module = "定标管理",value = "供应商投标全部附件")
    public PageView getBidFileList(Long tenderId) {
        return benchmarksLogic.getBidFileList(tenderId);
    }

    /**
     * 批量确认开标
     *
     * @param idStr 招标单ID
     */
    @PostMapping("updateOpenBidStatus")
    @AuditLogInter(module = "定标管理",value = "批量确认开标")
    public ResponseEntity updateOpenBidStatus(String idStr) {
        benchmarksLogic.updateOpenBidStatus(idStr);
        return ResponseEntity.ok().build();
    }

    /**
     * 定标获取招标单字段，包括评分维度
     *
     * @param id 招标单id
     * @return
     */
    @GetMapping("getFields")
    public ResponseEntity getFields(Long id) {
        return ResponseEntity.ok(tenderTemplateLogic.getTenderFields(id));
    }

    @GetMapping("downloadZip")
    public void downloadZip(Long tenderId, HttpServletResponse response) {
        Pair<String, String> result = benchmarksLogic.downloadZip(tenderId);
        final String filePath = result.getKey();
        final String fileName = result.getValue();
        String encodedFileName = FileNameUtil.replace(fileName);
        response.setContentType("application/zip");
        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);

        // 实现文件下载
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(filePath);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileUtil.del(filePath);
        }
    }

    /**
     * 定标 导出 报价明细
     *
     * @param response
     * @param exportFiled
     * @param queryStr
     * @throws IOException
     */
    @PostMapping("exportBidDetail")
    @AuditLogInter(module = "定标管理",value = "导出报价明细")
    public void exportBidDetail(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        final TenderQuery tenderQuery = JSON.parseObject(queryStr, TenderQuery.class);
        final Long tenderId = tenderQuery.getTenderId();
        final List<TenderBidDetailAllDTO> tenderBidDetailAllDTOS = benchmarksLogic.getTenderBidDetailAllDTOS(tenderId);
        List<ExportDataDTO> exportDataDTOS = JSON.parseArray(exportFiled, ExportDataDTO.class);
        exportDataDTOS.forEach(exportDataDTO -> {
            //如果字段为采购类型，则生成下拉框
            if ("status".equals(exportDataDTO.getField())) {
                //插入下拉框数据，也可以从字典里取数据，只插入字典名称
                exportDataDTO.setSelectList(ListUtil.toList("是", "否"));
            }
            if ("status,quota,bidNum,bidRemark,bargaining,bargainingRemark".contains(exportDataDTO.getField())) {
                exportDataDTO.setColor(IndexedColors.YELLOW.getIndex());
            }
        });
        final ExportDataDTO idField = ExportDataDTO.builder().width(0).title("").field("id").build();
        exportDataDTOS.add(0, idField);
        EasyExcelUtils.trendsModelWrite(response,
                "投标明细-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet",
                tenderBidDetailAllDTOS, exportDataDTOS);
    }

    /**
     * 到处分数信息
     *
     * @param response
     * @param exportFiled
     * @param queryStr
     * @throws IOException
     */
    @PostMapping("exportScore")
    @AuditLogInter(module = "定标管理",value = "导出分数信息")
    public void exportScore(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        final TenderQuery tenderQuery = JSON.parseObject(queryStr, TenderQuery.class);
        final Long tenderId = tenderQuery.getTenderId();
        List<BenchmarksScoreExportDTO> scoreExportDTOS = benchmarksLogic.getExportScoreList(tenderId);
        //先解析前端传过来的字段信息
        List<ExportDataDTO> exportDataDTOS = JSON.parseArray(exportFiled, ExportDataDTO.class);
        exportDataDTOS.forEach(exportDataDTO -> {
            //如果字段为采购类型，则生成下拉框
            if ("type".equals(exportDataDTO.getField())) {
                //插入下拉框数据，也可以从字典里取数据，只插入字典名称
                exportDataDTO.setSelectList(ListUtil.toList("是", "否"));
            }
        });
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("user_data.xlsx", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        EasyExcelUtils.trendsModelWrite(response,
                "分数-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet",
                scoreExportDTOS, exportDataDTOS);
    }

    /**
     * 导入分数
     *
     * @param file
     * @param tenderId
     * @return
     * @throws IOException
     */
    @PostMapping("importScore/{tenderId}")
    @AuditLogInter(module = "定标管理",value = "导入分数")
    public ResponseEntity importScore(@RequestPart("file") MultipartFile file, @PathVariable Long tenderId) throws
            IOException
    {
        List<Map<String, String>> dataList = EasyExcelImportUtils.parseExcelToData(file.getInputStream(), 2);
        List<BenchmarksScoreExportDTO> scoreExportDTOS = Lists.newArrayList();
        for (Map<String, String> stringStringMap : dataList) {
            scoreExportDTOS.add(BeanUtil.mapToBean(stringStringMap, BenchmarksScoreExportDTO.class, false));
        }
        benchmarksLogic.importScore(scoreExportDTOS, tenderId);
        return ResponseEntity.ok().build();
    }

    /**
     * 导入明细
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("importItem")
    @AuditLogInter(module = "定标管理",value = "导入议价信息")
    public ResponseEntity importItem(@RequestPart("file") MultipartFile file) throws
            IOException
    {
        List<Map<String, String>> dataList = EasyExcelImportUtils.parseExcelToData(file.getInputStream(), 2);
        return ResponseEntity.ok(dataList);
    }

    /**
     * 提交议价信息
     *
     * @param dto
     * @return
     */
    @PostMapping("submitBargaining")
    @AuditLogInter(module = "定标管理",value = "提交议价信息")
    public ResponseEntity submitBargaining(@RequestBody List<SubmitBargainingItemDTO> dto) {
        benchmarksLogic.submitBargaining(dto);
        return ResponseEntity.ok().build();
    }

    /**
     * 截止议价
     *
     * @return
     */
    @PostMapping("stopBargaining")
    @AuditLogInter(module = "定标管理",value = "截止议价")
    public ResponseEntity stopBargaining(@RequestBody List<Long> id) {
        benchmarksLogic.stopBargaining(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 提交定标信息
     *
     * @param submitBenchmarksDTO
     * @return
     */
    @PostMapping("submitBenchmarks")
    @AuditLogInter(module = "定标管理",value = "定标保存")
    public ResponseEntity submitBenchmarks(@RequestBody SubmitBenchmarksDTO submitBenchmarksDTO) {
        benchmarksLogic.submitBenchmarks(submitBenchmarksDTO);
        return ResponseEntity.ok().build();
    }

    /**
     * 发布定标结果
     *
     * @param id
     * @return
     */
    @PostMapping("releaseBenchmarks")
    @AuditLogInter(module = "定标管理",value = "发布定标结果")
    public ResponseEntity releaseBenchmarks(Long id) {
        benchmarksLogic.releaseBenchmarks(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("calculateQuotas")
    public ResponseEntity calculateQuotas(@RequestBody SubmitBenchmarksDTO submitBenchmarksDTO) {
        benchmarksLogic.calculateQuotas(submitBenchmarksDTO);
        return ResponseEntity.ok().build();
    }

    @GetMapping("confirmUserList")
    public PageView confirmUserList(Long tenderId) {
        return benchmarksLogic.getConfirmUserList(tenderId);
    }

    /**
     * 定标内部审批
     *
     * @param bidedApprovelDTO
     * @return
     */
    @PostMapping("approvel")
    public ResponseEntity approvel(BidedApprovelDTO bidedApprovelDTO) {
        benchmarksLogic.bidedApproval(bidedApprovelDTO.getId(), bidedApprovelDTO.getType(),
                bidedApprovelDTO.getAgreeFlag(), bidedApprovelDTO.getRemark());
        return ResponseEntity.ok().build();
    }

    @GetMapping("supplierRankList")
    public PageView supplierRankList(Long id) {
        return benchmarksLogic.getSupplierRankList(id);
    }


    /**
     * 查询供应商未报价的物料在系统中是否有维护有效价格
     * @param id
     * @return
     */
    @GetMapping("supplierUnquotedMaterials")
    public ResponseEntity supplierUnquotedMaterials(Long id)  {
        List<String> strings = benchmarksLogic.supplierUnquotedMaterials(id);
        return ResponseEntity.ok(strings);
    }


    @PostMapping("exportMaterial")
    public void exportMaterial(HttpServletResponse response, Long tenderId) throws IOException {
        //先解析前端传过来的字段信息
        List<ExportDataDTO> exportDataDTOS = Lists.newArrayList();
        ExportDataDTO id = ExportDataDTO.builder().field("id").title("").width(0).build();
        exportDataDTOS.add(id);
        ExportDataDTO materialCode = ExportDataDTO.builder().field("materialCode").title("物料编码").width(10).build();
        exportDataDTOS.add(materialCode);
        ExportDataDTO materialName = ExportDataDTO.builder().field("materialName").title("物料名称").width(10).build();
        exportDataDTOS.add(materialName);
        List<TenderDetailAllDTO> tenderDetails = benchmarksLogic.exportMaterial(tenderId);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("user_data.xlsx", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        EasyExcelUtils.trendsModelWrite(response,
                "定标补充物料-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet",
                tenderDetails, exportDataDTOS);
    }
    /**
     * 导入物料数据
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("importMaterial")
    public ResponseEntity importMaterial(@RequestPart("file") MultipartFile file) throws
            IOException
    {
        benchmarksLogic.importMaterial(file);
        return ResponseEntity.ok().build();
    }
}
