package common.controller;

import common.model.*;
import common.service.ContractService;
import common.service.ShareIncomeService;
import dic.AuthMenuEnmm;
import dic.ContractStatusEnum;
import dic.OperateObjectTypeEnum;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import security.annotation.AuthKey;
import security.annotation.CurrentAccount;
import util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by mxq on 17/12/21.
 * 优先测试账号查询
 */
@Controller
@RequestMapping("{platform}/contract")
public class ContractController {

    private static final Logger logger = LoggerFactory.getLogger(ContractController.class);

    private static final Map<String, String> CONTRACT_STATUS = new HashMap<String, String>() {{

        putdata(this, ContractStatusEnum.WAIT);
        putdata(this, ContractStatusEnum.EXECUTING);
        putdata(this, ContractStatusEnum.END);
        putdata(this, ContractStatusEnum.CANCEL);
        putdata(this, ContractStatusEnum.NFORMAL);
        putdata(this, ContractStatusEnum.SUSPEND);
        putdata(this, ContractStatusEnum.LATE);
        putdata(this, ContractStatusEnum.BACK_ALL);
        putdata(this, ContractStatusEnum.BACK_NONE);
        putdata(this, ContractStatusEnum.BACK_PART);
        putdata(this, ContractStatusEnum.MONEY_BACK_FIRST);
        putdata(this, ContractStatusEnum.DELETE);
        putdata(this, ContractStatusEnum.FIRST_SIGNING);
        putdata(this, ContractStatusEnum.RENEWAL);
        putdata(this, ContractStatusEnum.SUPPLEMENTARY_AGREEMENT);

    }};


    private static void putdata(Map map, ContractStatusEnum a) {
        map.put(a.getKey(), a.getValue());
    }

    @Autowired
    private ContractService service;

    @Autowired
    private ShareIncomeService shareIncomeService;

    @RequestMapping(value = "find", method = RequestMethod.GET)
    @ResponseBody
    @AuthKey(AuthMenuEnmm.CONTRACTMNG_V)
    public ResultModel findAll(@CurrentAccount User loginAccount, @PathVariable String platform,
                               @RequestParam String startDate, @RequestParam String endDate, String contractId) {

        return ResultModel.OK(service.findAll(loginAccount, startDate, endDate, platform, contractId));
    }

    @RequestMapping(value = "contractid/find", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findOne(@CurrentAccount User loginAccount, @PathVariable String platform,
                               String startDate, String endDate, String contractId) {

        return ResultModel.OK(service.findOne(loginAccount, startDate, endDate, platform, contractId));
    }


    @RequestMapping(value = "export", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @ResponseBody
    @AuthKey(AuthMenuEnmm.CONTRACTMNG_EX)
    public void export(@CurrentAccount User loginAccount, @PathVariable String platform, @RequestParam String startDate
            , @RequestParam String endDate, HttpServletRequest request, HttpServletResponse response) {
        List<Contract> contractList = service.findAll(loginAccount, startDate, endDate, platform, null);
        /*StringBuilder sb = new StringBuilder();
        //录入时间 合同编号 客户账号 我方签约主体 签约方 行业分类 销售 开始日期 结束日期 套餐类型 合同金额 签约类型 合同状态 回款状态 关联合同
        sb.append("录入时间,合同编号,客户账号,我方签约主体,签约方,行业分类,销售,开始日期,结束日期,套餐类型,合同金额,签约类型,合同状态,回款状态,关联合同\r\n");
        if (ValidateUtil.isValid(contractList)) {
            for (Contract c : contractList) {
                sb.append(c.getDs()).append(",").
                        append(c.getContractCode()).append(",")
                        .append(c.getEmail() == null ? "无" : c.getEmail()).append(",")
                        .append(c.getMyBodyName()).append(",")
                        .append(c.getCustomerBody()).append(",")
                        .append(c.getTradeName()).append(",")
                        .append(c.getSaleName()).append(",")
                        .append(c.getStartDate()).append(",")
                        .append(c.getEndDate()).append(",")
                        .append(c.getPriceLevelName()).append(",")
                        .append(c.getMoney()).append(",")
                        .append(CONTRACT_STATUS.get(c.getContractType())).append(",")
                        .append(CONTRACT_STATUS.get(c.getStatus())).append(",")
                        .append(CONTRACT_STATUS.get(c.getBackStatus() + "_back")).append(",")
                        .append(c.getRelationCode() == null ? "" : c.getRelationCode()).append(",")
                        .append("\r\n");
            }
        }
        String fileName = "合同管理_" + new DateTime(startDate).toString("yyyyMMdd") + "_" + new DateTime(endDate).toString("yyyyMMdd")
                + ".csv";
        this.exportWrite(fileName, sb.toString(), "合同管理", response);*/

        //创建工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();//这里也可以设置sheet的Name
        //创建工作表对象
        HSSFSheet sheet = workbook.createSheet();
        //创建工作表的行
        HSSFRow row = sheet.createRow(0);

        List<String> title = Arrays.asList("录入时间,合同编号,客户账号,我方签约主体,签约方,行政区域,隶属集团,行业分类,销售,开始日期,结束日期,套餐类型,合同金额,签约类型,合同状态,回款状态,关联合同"
                .split(","));
        if(platform.equals("tkio")){
            title.add("总点击次数(万次)");
        }
        int lineSize = title.size();
        for (int i = 0; i < lineSize; i++) {
            row.createCell(i).setCellValue(title.get(i));
        }

        for (int i = 0; i < contractList.size(); i++) {
            Contract contract = contractList.get(i);
            HSSFRow rowBody = sheet.createRow(i + 1);
            rowBody.createCell(0).setCellValue(new DateTime(contract.getCreateTime()).toString("yyyy-MM-dd"));
            rowBody.createCell(1).setCellValue(contract.getContractCode());
            rowBody.createCell(2).setCellValue(contract.getEmail() == null ? "无" : contract.getEmail());
            rowBody.createCell(3).setCellValue(contract.getMyBodyName());
            rowBody.createCell(4).setCellValue(contract.getCustomerBody());
            rowBody.createCell(5).setCellValue(contract.getBarrioName());
            rowBody.createCell(6).setCellValue(contract.getBelongGroup());
            rowBody.createCell(7).setCellValue(contract.getTradeName());
            rowBody.createCell(8).setCellValue(contract.getSaleName());
            rowBody.createCell(9).setCellValue(contract.getStartDate());
            rowBody.createCell(10).setCellValue(contract.getEndDate());
            rowBody.createCell(11).setCellValue(contract.getPriceLevelName());
            rowBody.createCell(12).setCellValue(contract.getMoney());
            rowBody.createCell(13).setCellValue(CONTRACT_STATUS.get(contract.getContractType()));
            rowBody.createCell(14).setCellValue(CONTRACT_STATUS.get(contract.getStatus()));
            rowBody.createCell(15).setCellValue(CONTRACT_STATUS.get(contract.getBackStatus() + "_back"));
            rowBody.createCell(16).setCellValue(contract.getRelationCode() == null ? "" : contract.getRelationCode());
            if(platform.equals("tkio")){
                rowBody.createCell(17).setCellValue(contract.getTrackFlow());

            }

        }

        String fileName = "合同管理_" + new DateTime(startDate).toString("yyyyMMdd")
                + "_" + new DateTime(endDate).toString("yyyyMMdd") + ".xls";
        this.exportWrite(fileName, workbook, "合同管理_", response);


        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), platform, "导出合同", startDate, endDate, request, platform);
        userlog.start();
        //返回文件字符串
//        return new ResponseEntity<byte[]>(content, headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "pay/export", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @ResponseBody
    @AuthKey(AuthMenuEnmm.COLLECTBILLLIST_EX)
    public void exportPay(@CurrentAccount User loginAccount, @RequestParam String startDate, @RequestParam String endDate,
                          HttpServletRequest request, HttpServletResponse response, @PathVariable String platform,
                          String moneyType, String packageTypeSearch, String money_ids) {
        List<ContractMoney> moneyList = service.findPayAll(loginAccount, startDate, endDate, platform, moneyType, packageTypeSearch, money_ids);
        Map<String, String> map = new HashMap<>();
        map.put("pay", "收款");
        map.put("invoice", "开票");

        byte[] content = new byte[0];
        StringBuilder sb = new StringBuilder();

        Double parseSum = 0d;
        if (ValidateUtil.isValid(moneyList)) {
            for (ContractMoney c : moneyList) {
                sb.append(c.getDs()).append(",")
                        .append(c.getContractCode() == null ? "" : c.getContractCode()).append(",")
                        .append(c.getEmail() == null ? "" : c.getEmail()).append(",")
                        .append(c.getCompany() == null ? "" : c.getCompany()).append(",")
                        .append(c.getPackageName() == null ? "" : c.getPackageName()).append(",")
                        .append(c.getSalseName() == null ? "" : c.getSalseName()).append(",")
                        .append(map.get(c.getType() == null ? "" : c.getType())).append(",")
                        .append(c.getMoney() == null ? "" : c.getMoney()).append(",")
                        .append(c.getCreateName() == null ? "" : c.getCreateName()).append("\r\n");

                if ("pay".equals(c.getType())) {
                    // 付款
                    parseSum += c.getMoney();

                } else {
                    parseSum -= c.getMoney();
                }
            }

        }

        StringBuffer titlebuffer = new StringBuffer();
        titlebuffer.append("日期, 合同编号 ,客户账号 ,签约方名称 ,套餐类型, 销售, 事项 ,金额 ,操作人 \r\n");
        titlebuffer.append("汇总,  - , -  ,  - ,  - ,  - ,  -  ,").append(parseSum).append(" , - \r\n");
        titlebuffer.append(sb);

        String fileName = "收款开票_" + new DateTime(startDate).toString("yyyyMMdd")
                + "_" + new DateTime(endDate).toString("yyyyMMdd") + ".csv";
        this.exportWrite(fileName, titlebuffer.toString(), "收款开票", response);

        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), platform, "导出收款开票", startDate, endDate, request, platform);
        userlog.start();
        //返回文件字符串
//        return new ResponseEntity<byte[]>(content, headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "findone", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findOne(@CurrentAccount User loginAccount, @RequestParam String code) {
        return ResultModel.OK(service.findOne(code));
    }

    @RequestMapping(value = "checkAccount", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel checkAccount(@CurrentAccount User loginAccount, @RequestParam String email, @PathVariable String platform) {
        return ResultModel.OK(service.checkAccount(email, platform));
    }

    @RequestMapping(value = "checkTime", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel checkTime(@RequestParam String type, @RequestParam String email,
                                 @RequestParam String platform, @RequestParam(required = false) String product) {
        return ResultModel.OK(service.checkTime(email, platform, type, product));
    }

    @RequestMapping(value = "find/body", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findBody(@CurrentAccount User loginAccount, @PathVariable String platform, String dropall) {

        if ("all".equals(dropall)) {
            platform = dropall;
        }

        return ResultModel.OK(service.findBody(platform, loginAccount));
    }

    @RequestMapping(value = "find/code", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findCode(@CurrentAccount User loginAccount, @RequestParam String code, @PathVariable String platform, String company) {

        return ResultModel.OK(service.getContractCode(code, platform, company));
    }

    @RequestMapping(value = "find/pricelevel", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findPricelevel(@CurrentAccount User loginAccount, @PathVariable String platform) {
        return ResultModel.OK(service.findSetmeal(platform));
    }

    @RequestMapping(value = "find/increment", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findIncrement(@CurrentAccount User loginAccount) {
        return ResultModel.OK(service.findIncrement());
    }

    @RequestMapping(value = "find/rebat", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel rebat(@CurrentAccount User loginAccount, @RequestParam String product, @RequestParam Integer level, @RequestParam Double money) {
        return ResultModel.OK(service.getRebat(product, level, money));
    }

    @RequestMapping(value = "find/sale", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel rebat(@CurrentAccount User loginAccount) {
        return ResultModel.OK(service.getSales());
    }


    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public ResultModel create(@CurrentAccount User loginAccount, @RequestBody Contract contract, HttpServletRequest request, @PathVariable String platform) {

        Contract contract1 = service.create(loginAccount, contract);
        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), contract1.getContractCode(), "新建合同", "", contract1.toString(), request, platform);
        userlog.start();
//        ContractSendEmailThread email = new ContractSendEmailThread(contract);
//        email.start();
        return ResultModel.OK(contract1);
    }

    @RequestMapping(value = "update", method = RequestMethod.PUT)
    @ResponseBody
    @AuthKey(AuthMenuEnmm.CONTRACTMNG_M)
    public ResultModel update(@CurrentAccount User loginAccount, @RequestBody Contract contract, HttpServletRequest request, @PathVariable String platform) {

        String ip = IPAddrUtil.getIpAddrNew(request);
        Contract contract1 = service.update(loginAccount, contract, ip);
        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), contract1.getContractCode(), "修改合同", "", contract1.toString(), request, platform);
        userlog.start();

        return ResultModel.OK(contract1);
    }

    @RequestMapping(value = "pay", method = RequestMethod.POST)
    @ResponseBody
    public ResultModel pay(@CurrentAccount User loginAccount, @RequestBody ContractMoney contract, HttpServletRequest request, @PathVariable String platform) {
        ContractMoney contract1 = service.pay(loginAccount, contract);
        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), contract1.getContractCode(), "收款开票", "", contract1.toString(), request, platform);
        userlog.start();
        return ResultModel.OK(contract1);
    }

    @RequestMapping(value = "change", method = RequestMethod.POST)
    @ResponseBody
    public ResultModel change(@CurrentAccount User loginAccount,
                              @RequestBody ContractChange contract, HttpServletRequest request, @PathVariable String platform) {
        Contract contract1 = service.change(loginAccount, contract, null);
        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), contract1.getContractCode(), "修改套餐", "", contract1.toString(), request, platform);
        userlog.start();
        return ResultModel.OK(contract1);
    }

    /**
     * @param loginAccount
     * @param startDate
     * @param endDate
     * @param code
     * @return
     */
    @RequestMapping(value = "find/pay", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findPay(@CurrentAccount User loginAccount, @RequestParam String startDate,
                               @RequestParam String endDate, @RequestParam String code) {
        return ResultModel.OK(service.findPay(startDate, endDate, code));
    }

    @RequestMapping(value = "find/change", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel findChange(@CurrentAccount User loginAccount, @RequestParam String startDate,
                                  @RequestParam String endDate, @RequestParam String code) {
        return ResultModel.OK(service.findChange(startDate, endDate, code));
    }

    @RequestMapping(value = "find/flowchange", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel flowchange(@CurrentAccount User loginAccount, @RequestParam String startDate,
                                  @RequestParam String endDate, @RequestParam String code) {
        return ResultModel.OK(service.findflowChange(startDate, endDate, code));
    }


    @RequestMapping(value = "update/pay", method = RequestMethod.PUT)
    @ResponseBody
    public ResultModel updatePay(@CurrentAccount User loginAccount, @RequestBody ContractMoney contract, HttpServletRequest request,
                                 @PathVariable String platform) {

        String ip = IPAddrUtil.getIpAddrNew(request);
        Contract contract1 = service.updatePay(loginAccount, contract, ip);
        NewUserLogThread userlog = new NewUserLogThread(loginAccount.getEmail(), loginAccount.getName(), OperateObjectTypeEnum.CUSTOMER.getKey(), contract1.getContractCode(), "修改收款开票", "", contract1.toString(), request, platform);
        userlog.start();
        return ResultModel.OK(contract1);
    }

    @RequestMapping(value = "find/payall", method = RequestMethod.GET)
    @ResponseBody
    @AuthKey(AuthMenuEnmm.COLLECTBILLLIST_V)
    public ResultModel findPayAll(@CurrentAccount User loginAccount, @RequestParam String startDate,
                                  @RequestParam String endDate, @PathVariable String platform,
                                  String moneyType, String packageTypeSearch, String money_ids) {
        return ResultModel.OK(service.findPayAll(loginAccount, startDate, endDate, platform, moneyType, packageTypeSearch, money_ids));

    }

    @RequestMapping(value = "build", method = RequestMethod.POST)
    @ResponseBody
    public ResultModel build(@RequestBody Contract contract, HttpServletRequest request) {

        logger.error("tkiio---------------" + contract);
        return ResultModel.OK(service.build(contract));
    }

    @RequestMapping(value = "trade", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel baseCreate(@PathVariable String platform) {
        return ResultModel.OK(service.getTradeData(platform));
    }


    @RequestMapping(value = "code/all", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel contractCodeAll(@PathVariable String platform, String contractId) {

        return ResultModel.OK(service.contractCodeAll(platform, contractId));
    }


    @RequestMapping(value = "setstaus", method = RequestMethod.GET)
    @ResponseBody
    @AuthKey(AuthMenuEnmm.CONTRACTMNG_D)
    public ResultModel contractStatusUpdate(@PathVariable String platform, @CurrentAccount User loginUser,
                                            String contractId, String status, HttpServletRequest request) {

        String ip = IPAddrUtil.getIpAddrNew(request);
        return ResultModel.OK(service.contractStatusUpdate(platform, contractId, status, ip, loginUser));
    }


    @RequestMapping(value = "codecheck", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel codeCheck(@PathVariable String platform, String contractCode) {

        return ResultModel.OK(service.contractCodeCheck(platform, contractCode));
    }


    /**
     * 删除记录
     *
     * @param platform
     * @param
     * @return
     */
    @RequestMapping(value = "change/del", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel changesDel(@PathVariable String platform, @CurrentAccount User loginAccount,
                                  String id, String type, HttpServletRequest request) {
        return ResultModel.OK(service.changesDel(platform, id, type, IPAddrUtil.getIpAddrNew(request), loginAccount));

    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ResultModel fileUpload2(@RequestParam("file") MultipartFile file, @PathVariable String platform) {
        return service.uploadBatchInfo(file, platform);
    }

    @RequestMapping(value = "/upload/tempurl", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel fileTempUrl() {
        return ResultModel.OK(Constant.importTempUrl);
    }

    /**
     * 分摊收入
     *
     * @param loginAccount
     * @param platform
     * @param startDate
     * @param endDate
     * @param serchName
     * @return
     */
    @RequestMapping(value = "/shareincome/list", method = RequestMethod.GET)
    @ResponseBody
    @AuthKey(AuthMenuEnmm.SHARED_INCOME_V)
    public ResultModel shareIncome(@CurrentAccount User loginAccount, @PathVariable String platform,
                                   @RequestParam String startDate, @RequestParam String endDate,
                                   String bodyCode, String serchName) {

        return ResultModel.OK(shareIncomeService.shareIncomeList(loginAccount, startDate, endDate, platform, bodyCode, serchName));

    }

    @RequestMapping(value = "/shareincome/export", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @ResponseBody
    @AuthKey(AuthMenuEnmm.SHARED_INCOME_E)
    public void shareIncomeExport(@CurrentAccount User loginAccount, @PathVariable String platform,
                                  @RequestParam String startDate, @RequestParam String endDate,
                                  String bodyCode, String serchName, HttpServletResponse response, HttpServletRequest request) {

        List<Contract> contracts = shareIncomeService.shareIncomeList(loginAccount, startDate, endDate, platform, bodyCode, serchName);
        //byte[] content = new byte[0];

        //StringBuilder sb = new StringBuilder();
        /*sb.append("我方签约主体,签约方,合同编号,合同金额,不含税收入,合同开始时间,合同截止时间,区间使用天数,区间分摊收入,调整额,分摊总收入\r\n");*/
        //sb.append("我方签约主体,签约方,合同编号,合同状态,合同金额,不含税收入,合同开始日期,合同截止日期,区间使用天数,区间分摊收入,调整额,分摊总收入\r\n");
        HSSFWorkbook workbook;
        if(platform.equals("tkio")){
            workbook = createTKIOExcel(contracts);
        }else{
            workbook = createCommonExcel(contracts);
        }


        String fileName = "分摊收入报表_" + new DateTime(startDate).toString("yyyyMMdd")
                + "_" + new DateTime(endDate).toString("yyyyMMdd") + ".xls";
        this.exportWrite(fileName, workbook, "分摊收入报表", response);



        /*if (ValidateUtil.isValid(contracts)) {
            for (Contract c : contracts) {
                sb.append(c.getMyBodyName()).append(",")
                        .append(c.getCustomerBody()).append(",")
                        .append(c.getContractCode()).append(",")
                        .append(CONTRACT_STATUS.get(c.getStatus())).append(",")
                        .append("\"").append(df.format(c.getMoney())).append("\",")
                        .append("\"").append(df.format(c.getIncomeExcludingTax() * 1.0 / 100)).append("\",")
                        .append(c.getStartDate()).append(",")
                        .append(c.getEndDate()).append(",")
                        .append(c.getIntervalUseDays()).append(",")
                        .append("\"").append(df.format(c.getIntervaIncomeShare() * 1.0 / 100)).append("\",")
                        .append("\"").append(df.format(c.getAdjustmentFund() * 1.0 / 100)).append("\",")
                        .append("\"").append(df.format(c.getIncomeShareAll() * 1.0 / 100)).append("\"")
                        .append("\r\n");
            }
        }
        String fileName = "分摊收入报表_" + new DateTime(startDate).toString("yyyyMMdd")
                + "_" + new DateTime(endDate).toString("yyyyMMdd") + ".csv";
        this.exportWrite(fileName, sb.toString(), "分摊收入报表", response);*/

    }

    private HSSFWorkbook createCommonExcel(List<Contract> contracts){
        DecimalFormat df = new DecimalFormat("##,##0.00");
        //创建工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();//这里也可以设置sheet的Name
        //创建工作表对象
        HSSFSheet sheet = workbook.createSheet();
        //创建工作表的行
        HSSFRow row = sheet.createRow(0);

        List<String> title = Arrays.asList("我方签约主体,签约方,合同编号,行政区域,隶属集团,合同状态,合同金额,不含税收入,合同开始日期,合同截止日期,区间使用天数,区间分摊收入,调整额,分摊总收入"
                .split(","));

        int lineSize = title.size();
        for (int i = 0; i < lineSize; i++) {
            row.createCell(i).setCellValue(title.get(i));
        }

        for (int i = 0; i < contracts.size(); i++) {
            Contract contract = contracts.get(i);
            HSSFRow rowBody = sheet.createRow(i + 1);
            rowBody.createCell(0).setCellValue(contract.getMyBodyName());
            rowBody.createCell(1).setCellValue(contract.getCustomerBody());
            rowBody.createCell(2).setCellValue(contract.getContractCode());
            rowBody.createCell(3).setCellValue(contract.getBarrioName());
            rowBody.createCell(4).setCellValue(contract.getBelongGroup());
            rowBody.createCell(5).setCellValue(CONTRACT_STATUS.get(contract.getStatus()));
            rowBody.createCell(6).setCellValue(df.format(contract.getMoney()));
            rowBody.createCell(7).setCellValue(df.format(contract.getIncomeExcludingTax() * 1.0 / 100));
            rowBody.createCell(8).setCellValue(contract.getStartDate());
            rowBody.createCell(9).setCellValue(contract.getEndDate());
            rowBody.createCell(10).setCellValue(contract.getIntervalUseDays());
            rowBody.createCell(11).setCellValue(df.format(contract.getIntervaIncomeShare() * 1.0 / 100));
            rowBody.createCell(12).setCellValue(df.format(contract.getAdjustmentFund() * 1.0 / 100));
            rowBody.createCell(13).setCellValue(df.format(contract.getIncomeShareAll() * 1.0 / 100));
        }
        return workbook;
    }
    private HSSFWorkbook createTKIOExcel(List<Contract> contracts){
        DecimalFormat df = new DecimalFormat("##,##0.00");
        DecimalFormat df2 = new DecimalFormat("##,##0.0000");
        //创建工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();//这里也可以设置sheet的Name
        //创建工作表对象
        HSSFSheet sheet = workbook.createSheet();
        //创建工作表的行
        HSSFRow row = sheet.createRow(0);

        List<String> title = Arrays.asList("我方签约主体,签约方,合同编号,行政区域,隶属集团,合同开始日期,合同截止日期,合同状态,合同金额(元),总点击次数(万次),单价(元/万次),区间点击数(万次),区间分摊收入(元),区间调整金额(元),区间总收入(元),累计总收入(元),赠送点击量(万次)"
                .split(","));

        int lineSize = title.size();
        for (int i = 0; i < lineSize; i++) {
            row.createCell(i).setCellValue(title.get(i));
        }

        for (int i = 0; i < contracts.size(); i++) {
            Contract contract = contracts.get(i);
            HSSFRow rowBody = sheet.createRow(i + 1);
            rowBody.createCell(0).setCellValue(contract.getMyBodyName());
            rowBody.createCell(1).setCellValue(contract.getCustomerBody());
            rowBody.createCell(2).setCellValue(contract.getContractCode());
            rowBody.createCell(3).setCellValue(contract.getBarrioName());
            rowBody.createCell(4).setCellValue(contract.getBelongGroup());
            rowBody.createCell(5).setCellValue(contract.getStartDate());
            rowBody.createCell(6).setCellValue(contract.getEndDate());
            rowBody.createCell(7).setCellValue(CONTRACT_STATUS.get(contract.getStatus()));
            rowBody.createCell(8).setCellValue(df.format(contract.getMoney()));
            rowBody.createCell(9).setCellValue(contract.getTrackFlow());
            rowBody.createCell(10).setCellValue(contract.getUnitPrice());
            rowBody.createCell(11).setCellValue(contract.getClickFlow());
            rowBody.createCell(12).setCellValue(df.format(contract.getIntervaIncomeShare() / 100.0));
            rowBody.createCell(13).setCellValue(df.format(contract.getAdjustmentFund() / 100.0));
            rowBody.createCell(14).setCellValue(df.format(contract.getIncomeShareAll() / 100.0));
            rowBody.createCell(15).setCellValue(df.format(contract.getIncomeGross() / 100.0));
            rowBody.createCell(16).setCellValue(df2.format(contract.getExtraFlow() / 10000.0));
        }
        return workbook;
    }

    private void exportWrite(String fileName, HSSFWorkbook workbook, String exportName, HttpServletResponse response) {
        OutputStream os = null;
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("filename", fileName);
            response.setHeader("content-disposition", "attachment; filename=" + fileName);
            response.setHeader("Content-Type", "text/xls");
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setCharacterEncoding("UTF-8");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            logger.error(exportName + "报错", e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    logger.error(exportName + "导出,关闭流报错", e);
                }
            }

        }
    }

    private void exportWrite(String fileName, String text, String exportName, HttpServletResponse response) {
        OutputStream os = null;
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("filename", fileName);
            response.setHeader("content-disposition", "attachment; filename=" + fileName);
            response.setHeader("Content-Type", "text/csv");
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setCharacterEncoding("UTF-8");
            os = response.getOutputStream();
            os.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            os.write(text.getBytes("UTF-8"));
            os.flush();
        } catch (Exception e) {
            logger.error(exportName + "报错", e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    logger.error(exportName + "导出,关闭流报错", e);
                }
            }

        }
    }

    /**
     * 功能描述:新建合同回显、获取行政区域列表
     * @author liyin
     * @date 2020/9/23
     */
    @GetMapping("/getBarrioCities")
    @ResponseBody
    public ResultModel getBarrioCities(){

        return ResultModel.OK(service.getBarrioCities());
    }


}
