package cn.palmte.work.controller.backend;

import cn.palmte.work.bean.ResponseMsg;
import cn.palmte.work.model.MonthlySettle;
import cn.palmte.work.model.MonthlySettleRepository;
import cn.palmte.work.service.MonthlySettleService;
import cn.palmte.work.utils.FreeMarkerUtil;
import cn.palmte.work.utils.Utils;
import cn.palmte.work.utils.excel.AppendMore;
import cn.palmte.work.utils.excel.ExcelLogs;
import cn.palmte.work.utils.excel.ExcelUtil;
import cn.palmte.work.utils.excel.ExportUtils;
import com.alibaba.fastjson.JSON;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Yuanping Zhang
 * @date 2022/08/08
 */
@Controller
@RequestMapping("/monthlySettle")
public class MonthlySettleController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(MonthlySettleController.class);

    @Autowired
    private MonthlySettleService monthlySettleService;

    @Autowired
    private MonthlySettleRepository monthlySettleRepository;

    @RequestMapping("/list")
    public String list(@RequestParam(value = KEYWORDS, required = false) String keywords,
                       @RequestParam(value = PAGE_NUMBER, defaultValue = DEFAULT_PAGE_NUMBER) int pageNumber,
                       @RequestParam(value = PAGE_SIZE, defaultValue = DEFAULT_PAGE_SIZE) int pageSize,
                       Map<String, Object> model) {
        // 初始化参数
        setModel(keywords, model);
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo(keywords, model);
        model.put("pager", monthlySettleService.list(searchInfo, pageNumber, pageSize));
        model.put("Utils", FreeMarkerUtil.fromStaticPackage("cn.palmte.work.utils.Utils"));
        return "/admin/monthly_settle_list";
    }

    @RequestMapping("/info")
    public String info(@RequestParam("id") int id, Map<String, Object> model) {
        MonthlySettle monthlySettle = monthlySettleService.findById(id);
        model.put("monthlySettle", monthlySettle);
        model.put("projectNameStr", monthlySettle.getProjectName());
        model.put("Utils", FreeMarkerUtil.fromStaticPackage("cn.palmte.work.utils.Utils"));
        return "/admin/monthly_settle_info";
    }

    @RequestMapping("/infoByTime")
    public String infoByTime(@RequestParam String month, @RequestParam("projectName") String projectName, Map<String, Object> model) {
        MonthlySettle monthlySettle = monthlySettleService.findByMonthAndProjectName(month, projectName);
        if (monthlySettle == null) {
            monthlySettle = new MonthlySettle();
        }
        model.put("monthlySettle", monthlySettle);
        model.put("projectNameStr", projectName);
        model.put("Utils", FreeMarkerUtil.fromStaticPackage("cn.palmte.work.utils.Utils"));
        return "/admin/monthly_settle_info";
    }

    private void setModel(@RequestParam(value = "keywords", required = false) String keywords, Map<String, Object> model) {
        model.put("keywords", keywords);
    }

    @RequestMapping("/export")
    public void export(@RequestParam(value = "keywords", required = false) String keywords, HttpServletResponse httpServletResponse) throws IOException {
        Map<String, String> searchInfo = getSearchInfo(keywords);
        downloadHeader(httpServletResponse, Utils.generateExcelName("PMO项目执行进度管理"), "application/octet-stream");
        String[] headers = {"项目编号", "项目名称", "项目类型", "合同编号", "合同方", "合同金额", "合同签订时间", "最终业主", "累计已收款", "已采购累计付款", "已采购累计未付款", "超期垫资金额", "销售累计开票金额",
                "销售经理", "项目经理", "收款节点", "收款要求时间", "收款金额", "实际收款时间", "实际收款金额", "实际欠收金额", "到货证明", "项目风险预警", "已计收金额", "未计收金额", "超期天数", "验收报告时间"};
        String[] exportColumns = {"projectNo", "projectName", "projectType", "contractNo", "contractParty", "contractAmountRound", "contractSignTimeStr", "owner", "totalCollectRound",
                "totalPurchasedPaidRound", "totalPurchasedUnpaidRound", "timeOutAmountRound", "totalBillAmountRound", "saleManager", "projectManager", "collectPoint", "collectRequiredTimeStr", "collectAmountRound",
                "collectActualTimeStr", "collectActualAmountRound", "uncollectActualAmountRound", "productCertificate", "riskWarning", "uncalColAmountRound", "calColAmountRound", "timeOutDay", "inspectionReportTimeStr"};
        ExportUtils.exportToExcel(headers, exportColumns, 1, 10000,
                httpServletResponse.getOutputStream(), (pN, pS) -> monthlySettleService.list(searchInfo, pN, pS).getList());
    }

    @RequestMapping("/exportSingle")
    public void exportSingle(@RequestParam String id, @RequestParam String time, @RequestParam String projectName, HttpServletResponse httpServletResponse) throws IOException {
        downloadHeader(httpServletResponse, Utils.generateExcelName("PMO项目执行进度管理明细"), "application/octet-stream");
        String[] headers = {"月份", "项目编号", "项目名称", "项目类型", "合同编号", "合同方", "合同金额", "合同签订时间", "最终业主", "累计已收款", "已采购累计付款", "已采购累计未付款", "超期垫资金额", "销售累计开票金额",
                "销售经理", "项目经理", "收款节点", "收款要求时间", "收款金额", "实际收款时间", "实际收款金额", "实际欠收金额", "超期天数", "到货证明", "验收报告时间", "项目风险预警", "已计收金额", "未计收金额"};
        String[] exportColumns = {"month", "projectNo", "projectName", "projectType", "contractNo", "contractParty", "contractAmountRound", "contractSignTimeStr", "owner", "totalCollectRound",
                "totalPurchasedPaidRound", "totalPurchasedUnpaidRound", "timeOutAmountRound", "totalBillAmountRound", "saleManager", "projectManager", "collectPoint", "collectRequiredTimeStr", "collectAmountRound",
                "collectActualTimeStr", "collectActualAmountRound", "uncollectActualAmountRound", "timeOutDay", "productCertificate", "inspectionReportTimeStr", "riskWarning", "uncalColAmountRound", "calColAmountRound"};
        ExportUtils.exportToExcel2(headers, exportColumns, 1, 10000,
                httpServletResponse.getOutputStream(), monthlySettleService.findOne(id, time, projectName));
    }

    /**
     * 模板下载
     */
    @RequestMapping("/template")
    public void template(HttpServletResponse response) throws Exception {
        String[] headers = new String[]{"项目编号", "最终业主", "合同方", "项目名称", "合同金额", "累计已收款", "已采购累计付款", "已采购累计未付款", "超期垫资金额", "销售累计开票金额", "合同编号", "项目类型", "合同签订时间", "销售经理", "项目经理", "收款节点", "收款要求时间", "收款金额",
                "实际收款时间", "实际收款金额", "实际欠收金额", "超期天数", "到货证明", "验收报告时间", "项目风险预警", "已计收金额", "未计收金额"};
        downloadHeader(response, Utils.generateExcelName("PMO项目执行进度管理导入模板"));
        ExportUtils exportUtils = new ExportUtils(headers);
        exportUtils.write(response.getOutputStream());
    }

    /**
     * 批量导入
     */
    @RequestMapping("/batchImport")
    @ResponseBody
    public String batchImport(MultipartFile file, @RequestParam(value = "date",required = false) String date) {
        try {
            ExcelLogs logs = new ExcelLogs();
            Collection<Map> maps = ExcelUtil.importExcel(Map.class, file.getInputStream(),
                    "yyyy/MM/dd HH:mm:ss", logs, 0);
            synchronized (this) {
                return JSON.toJSONString(monthlySettleService.check(maps, date));
            }
        } catch (OfficeXmlFileException | EncryptedDocumentException | InvalidFormatException e) {
            return JSON.toJSONString(ResponseMsg.buildFailedMsg("格式错误，请上传excel 2003/2007格式文件"));
        } catch (Exception e) {
            return JSON.toJSONString(ResponseMsg.buildFailedMsg("导入数据失败,请联系管理员"));
        }
    }
}
