package cn.com.countrygarden.bi.main.controller.marketing.backend;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.common.CommMapper;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.common.*;
import cn.com.countrygarden.bi.main.model.marketing.CommReportWeekly;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.common.CommService;
import cn.com.countrygarden.bi.main.service.dup.impl.ExcelHelper;
import cn.com.countrygarden.bi.main.service.marketing.ChargeService;
import cn.com.countrygarden.bi.main.service.marketing.CommReportWeeklyService;
import cn.com.countrygarden.bi.main.service.marketing.model.ChargeSummaryReport;
import cn.com.countrygarden.bi.main.service.marketing.model.ContractYearSummaryReport;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

@Controller("backendProjectReportController")
@RequestMapping("/api/biapp/marketing/backend/project/report")
public class ProjectReportController {


    @Autowired
    private CommService commService;
    @Autowired
    private CommMapper commMapper;

    @Autowired
    private CommReportWeeklyService reportWeeklyService;

    @Autowired
    private TbSysUserService userService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ChargeService chargeService;

    /**
     * 查看当前周报
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/weekly", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result weekly(@RequestParam(value = "serialNumber", required = true, defaultValue = "") String serialNumber) {
        int commId = Integer.parseInt(serialNumber.substring(2));
        Comm comm = commService.findById(commId);
        if (comm == null) {
            throw new ServiceException("项目不存在");
        }

        return Response.response(reportWeeklyService.getCurrentReportMap(commId));
    }

    /**
     * 查看当前周报
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/weeklys", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result lastReport(@RequestParam(value = "serialNumber", required = true, defaultValue = "") String serialNumber,
                             @RequestParam(value = "year", required = false, defaultValue = "0") int year,
                             @RequestParam(value = "limit", required = false, defaultValue = "0") int limit) {
    	  String commId = serialNumber;
          Comm comm = new Comm();
          comm.setCommCode(commId);
           comm = commMapper.selectOne(comm);
          if (comm == null) {
              throw new ServiceException("项目不存在");
          }

        return Response.response(reportWeeklyService.getLastWeeklyReport(comm.getId(), year, limit));
    }


    /**
     * 添加周报
     *
     * @param serialNumber
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/weekly", produces = "application/json; charset=utf-8", method = RequestMethod.PUT)
    public Result update(@RequestParam(value = "serialNumber", required = true, defaultValue = "") String serialNumber,
                         @RequestParam(value = "weekOfYear", required = true, defaultValue = "") int weekOfYear,
                         @RequestParam(value = "year", required = true, defaultValue = "") int year,
                         @RequestParam(value = "workContent", required = true, defaultValue = "") String workContent,
                         @RequestParam(value = "workPlan", required = true, defaultValue = "") String workPlan,
                         @RequestParam(value = "currentAssistanceIssues", required = true, defaultValue = "") String currentAssistanceIssues) {

        int commId = Integer.parseInt(serialNumber.substring(2));
        Comm comm = commService.findById(commId);
        if (comm == null) {
            throw new ServiceException("项目不存在");
        }

        TbSysUser sysUser = userService.getCurrentSysUser();
        Map<String, Object> response = reportWeeklyService.insertOrUpdate(
                commId,
                weekOfYear,
                year,
                workContent,
                workPlan,
                currentAssistanceIssues,
                sysUser.getUserCode()
        );
        response.put("serialNumber", comm.getCommNum());

        return Response.response(response);
    }

    /**
     * 查看周报汇总
     */
    @ResponseBody
    @RequestMapping(value = "/summary", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public Result searchSummary(@RequestParam(value = "search", required = false, defaultValue = "") String searchKey,
                                @RequestParam(value = "organId", required = false, defaultValue = "") String organId,
                                @RequestParam(value = "contractorName", required = false, defaultValue = "") String contractorName,
                                @RequestParam(value = "startDate", required = false, defaultValue = "") String startDteStr,
                                @RequestParam(value = "endDate", required = false, defaultValue = "")  String endDateStr,
                                @RequestParam(value = "state", required = false, defaultValue = "") String state,
                                @RequestParam(value = "skipe", required = false, defaultValue = "1")  int skipe,
                                @RequestParam(value = "limit", required = false, defaultValue = "1") int limit,
                                HttpServletRequest request, HttpServletResponse response){
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        PageData pageData = reportWeeklyService.searchSummary(token.getUserCode(),searchKey,organId,contractorName,startDteStr,endDateStr,state,skipe,limit);
        return Response.response(pageData);
    }


    /**
     * 导出周报汇总
     * @return
     */

    @RequestMapping(value = "/output", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public Result outputSummary(@RequestParam(value = "search", required = false, defaultValue = "") String searchKey,
                                @RequestParam(value = "organId", required = false, defaultValue = "") String organId,
                                @RequestParam(value = "contractorName", required = false, defaultValue = "") String contractorName,
                                @RequestParam(value = "startDate", required = false, defaultValue = "") String startDteStr,
                                @RequestParam(value = "endDate", required = false, defaultValue = "")  String endDateStr,
                                @RequestParam(value = "state", required = false, defaultValue = "") String state,
                                HttpServletRequest request, HttpServletResponse response){
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        if(!StringUtils.isEmpty(searchKey)){
            try {
                searchKey = URLDecoder.decode(searchKey, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if(!StringUtils.isEmpty(contractorName)){
            try {
                contractorName = URLDecoder.decode(contractorName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        PageData pageData = reportWeeklyService.searchSummary(token.getUserCode(),searchKey,organId,contractorName,startDteStr,endDateStr,state,1,0);
        ExcelHelper helper = new ExcelHelper();
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        helper.createWeeklyReportHeader(workbook, sheet);
        helper.createWeeklyReportBody(pageData, workbook, sheet);
        response.setContentType("multipart/form-data");
        String fileName = "export.xlsx";
        try {
            fileName = URLEncoder.encode("周报汇总.xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception ex) {

        } finally {
            try {
                workbook.close();
            } catch (Exception ex) {

            }
        }
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/contract/realtime", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public Result contractRealtime(
                                HttpServletRequest request, HttpServletResponse response){
        return Response.response(commService.contractYearSummaryReport());
    }

    @ResponseBody
    @RequestMapping(value = "/charge/summary", produces = "application/json; charset=utf-8", method = RequestMethod.GET)
    public Result chargeSummary(
            HttpServletRequest request, HttpServletResponse response){
        return Response.response(chargeService.chargeSummaryReport());
    }

}
