package cn.palmte.work.controller.backend;

import cn.palmte.work.bean.ResponseMsg;
import cn.palmte.work.service.MonthlySettleService;
import cn.palmte.work.utils.Utils;
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.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;

    @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));
        return "/admin/account_list";
    }

    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("人员信息"), "application/octet-stream");
        String[] headers = {"工号", "手机号码", "姓名", "常驻地", "一级部门", "直接主管", "职位", "角色名称", "公司邮件地址"};
        String[] exportColumns = {"userName", "telephone", "realName", "workLocation", "deptName", "directManager", "positionName", "roleName", "companyEmail"};
        ExportUtils.exportToExcel(headers, exportColumns, 1, 10000,
                httpServletResponse.getOutputStream(), (pN, pS) -> monthlySettleService.list(searchInfo, pN, pS).getList());
    }

    /**
     * 模板下载
     */
    @RequestMapping("/template")
    public void template(HttpServletResponse response) throws Exception {

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

    /**
     * 批量导入
     */
    @RequestMapping("/batchImport")
    @ResponseBody
    public String batchImport(MultipartFile file) {
        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));
            }
        } catch (OfficeXmlFileException | EncryptedDocumentException | InvalidFormatException e) {
            return JSON.toJSONString(ResponseMsg.buildFailedMsg("格式错误，请上传excel 2003/2007格式文件"));
        } catch (Exception e) {
            return JSON.toJSONString(ResponseMsg.buildFailedMsg("导入数据失败,请联系管理员"));
        }
    }
}
