package cn.com.countrygarden.bi.main.controller.districtReport;


import cn.com.countrygarden.bi.main.controller.BaseController;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.districtReport.*;
import cn.com.countrygarden.bi.main.dao.twerp.hm.ManagerMapForErpMapper;
import cn.com.countrygarden.bi.main.dto.districtReport.RdClosedBuildingProjectDTO;
import cn.com.countrygarden.bi.main.dto.districtReport.RdDistrictInfoDTO;
import cn.com.countrygarden.bi.main.dto.districtReport.RdDistrictSettledDTO;
import cn.com.countrygarden.bi.main.dto.districtReport.RdprojectInformationSummaryVO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.service.districtReport.*;
import cn.com.countrygarden.bi.main.util.ExportExcelUtil;
import cn.com.countrygarden.bi.main.util.POIUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;

/**
 * 项目信息汇总
 *
 * @author 吕伟峰
 * @email www.justintoforest@gamail.com
 * @url
 * @date 2019-08-14
 */

@RestController("RdprojectInformationSummaryController")
@RequestMapping("/api/rdprojectInformationSummary")
public class RdprojectInformationSummaryController extends BaseController {

    @Autowired
    private RdprojectInformationSummaryService rdprojectInformationSummaryService;

    @Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;

    @Autowired
    private RdProjectpermissionService rdProjectpermissionService;

    @Autowired
    private RdDistrictInfoMapper rdDistrictInfoMapper;

    @Autowired
    private RdDistrictSettledMapper rdDistrictSettledMapper;

    @Autowired
    private RdNewProjectMapper rdNewProjectMapper;

    @Autowired
    private RdUncollectedBuildingProjectsMapper rdUncollectedBuildingProjectsMapper;

    @Autowired
    private RdClosedBuildingProjectMapper rdClosedBuildingProjectMapper;

    @GetMapping(value = "/list", produces = "application/json;charset=utf-8")
    public Result list(RdClosedBuildingProjectDTO rdClosedBuildingProjectDTO,
                       @RequestParam(value = "size", required = false, defaultValue = "10") int size,
                       @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                       HttpServletRequest request){
        return  rdprojectInformationSummaryService.queryPageList(rdClosedBuildingProjectDTO,page,size,getAccessToken());
    }

    //导出数据
    @RequestMapping(value = "/evaluationrdprojectInformationSummary", produces = "multipart/form-data",  method = RequestMethod.GET)
    public void evaluationrdprojectInformationSummary(RdClosedBuildingProjectDTO rdClosedBuildingProjectDTO,
                                                  AccessToken accessToken, HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {

        // 获取登录人的角色授权
        Map<String, Object> rolesMap = rdProjectpermissionService.findRoleInfoMap(getAccessToken().getUserCode());

        List<String> organCodeString=new ArrayList<>();
        List<String> commIdString=new ArrayList<>();
        List<Integer> paixu=new ArrayList<>();
        List<String> principaString=new ArrayList<>();
        for (Map.Entry<String, Object> entry : rolesMap.entrySet()) {
            if(entry.getKey().equals("project_manager_admin")){
                paixu.add(1);
            }
            if(entry.getKey().equals("project_manager_principalAdmin")){
                paixu.add(2);
            }
            if(entry.getKey().equals("project_manager_regionAdmin")){
                paixu.add(3);
            }
            if(entry.getKey().equals("project_manager_regionUser")){
                paixu.add(4);
            }
            if(entry.getKey().equals("project_manager_projectUser")){
                paixu.add(5);
            }
            if(entry.getKey().equals("role")){
                throw new ServiceException("权限不足,无法使用此模块");
            }
        }
        Collections.sort(paixu);

        for (int i=0;i<paixu.size();i++) {
            if (paixu.get(i)==1){
                break;
            }else if(paixu.get(i)==2){
            principaString=rdProjectpermissionService.principalList(getAccessToken().getUserCode());
            break;
            }else if(paixu.get(i)==3||paixu.get(i)==4){
                organCodeString=managerMapForErpMapper.organCodeString(getAccessToken().getUserCode(),null);
                if(organCodeString==null||organCodeString.size()==0){
                    return;
                }
                break;
            }else if(paixu.get(i)==5){
                commIdString=managerMapForErpMapper.commIdString(getAccessToken().getUserCode());
                if(commIdString==null||commIdString.size()==0){
                    return;
                }
                break;
            }
        }

        ExportExcelUtil<RdprojectInformationSummaryVO> util = new ExportExcelUtil<RdprojectInformationSummaryVO>();
        String[] columnNames = { "区域名称" ,"片区名称","项目名称" ,"规划区域" , "项目开发主体" , "住宅用地面积","公建用地面积","道路用地面积",
                "绿地用地面积" ,"住宅数量","商业数量","车位数量","其他数量","住宅总面积","商业总面积","车位总面积",
                "其他总面积","容积率"};

        List<String> commId=new ArrayList<>();
        List<RdDistrictInfoDTO> rdDistrictProjectDTO=rdDistrictInfoMapper.rdDistrictProjectDTO(rdClosedBuildingProjectDTO.getDistrictCode(),principaString);
        if(rdDistrictProjectDTO.size()==0||rdDistrictProjectDTO==null){
            Collection<RdprojectInformationSummaryVO> list=new ArrayList<>();
            response.setContentType("multipart/form-data");
            String fileName = URLEncoder.encode("项目信息汇总.xls","UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
            util.exportExcel("项目信息汇总", columnNames, list, response.getOutputStream(), ExportExcelUtil.EXCEL_FILE_2003,null);
        }else {
            for (int i = 0; i < rdDistrictProjectDTO.size(); i++) {
                commId.add(rdDistrictProjectDTO.get(i).getCommid());
            }
        }


//        String[] idInte=ids.split(",");
//        List<String> rids = Arrays.asList(idInte);

        List<RdprojectInformationSummaryVO> rdprojectInformationSummaryList= managerMapForErpMapper.evaluationrdprojectInformationSummary(rdClosedBuildingProjectDTO,organCodeString,commIdString,commId);

        if (rdprojectInformationSummaryList.size()>=rdDistrictProjectDTO.size()){
            for (int i=0;i<rdprojectInformationSummaryList.size();i++){
                for (int y=0;y<rdDistrictProjectDTO.size();y++){
                    if (rdprojectInformationSummaryList.get(i).getCommId().equals(rdDistrictProjectDTO.get(y).getCommid())){
                        rdprojectInformationSummaryList.get(i).setDistrictName(rdDistrictProjectDTO.get(y).getDistrictName());
                    }
                }
            }
        }else {
            for (int y=0;y<rdDistrictProjectDTO.size();y++){
                for (int i=0;i<rdprojectInformationSummaryList.size();i++){
                    if (rdprojectInformationSummaryList.get(i).getCommId().equals(rdDistrictProjectDTO.get(y).getCommid())){
                        rdprojectInformationSummaryList.get(i).setDistrictName(rdDistrictProjectDTO.get(y).getDistrictName());
                    }
                }
            }
        }

        Collection<RdprojectInformationSummaryVO> list=rdprojectInformationSummaryList;
        response.setContentType("multipart/form-data");
        String fileName = URLEncoder.encode("项目信息汇总.xls","UTF-8");
        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
        util.exportExcel("项目信息汇总", columnNames, list, response.getOutputStream(), ExportExcelUtil.EXCEL_FILE_2003,null);
    }

    @Autowired
    private RdDistrictSettledService rdDistrictSettledService;


    @Autowired
    private RdPendingBuildingProjectService rdPendingBuildingProjectService;

    @Autowired
    private RdNewProjectService rdNewProjectService;

    @Autowired
    private RdUncollectedBuildingProjectsService rdUncollectedBuildingProjectsService;

    @Autowired
    private RdClosedBuildingProjectService rdClosedBuildingProjectService;

     /* 汇总导出数据
     * @param accessToken
     * @param request
     * @param response
     * @throws ParseException
     * @throws IOException
     */
    @RequestMapping(value = "/exportAll", produces = "multipart/form-data",  method = RequestMethod.GET)
    public void exportAll(RdDistrictSettledDTO rdDistrictSettledDTO,AccessToken accessToken,HttpServletResponse response) throws ParseException, IOException {
        // 获取登录人的角色授权
        Map<String, Object> rolesMap = rdProjectpermissionService.findRoleInfoMap(getAccessToken().getUserCode());

        List<String> organCodeString=new ArrayList<>();
        List<String> commIdString=new ArrayList<>();
        List<String> principaString=new ArrayList<>();
        List<Integer> paixu=rdProjectpermissionService.roleInfoList(rolesMap);

        for (int i=0;i<paixu.size();i++) {
            if (paixu.get(i)==1||paixu.get(i)==2){
                break;
            }else if(paixu.get(i)==3){
                principaString=rdProjectpermissionService.principalList(getAccessToken().getUserCode());
                break;
            }else if(paixu.get(i)==4||paixu.get(i)==5){
                organCodeString=managerMapForErpMapper.organCodeString(getAccessToken().getUserCode(),null);
                if(organCodeString==null||organCodeString.size()==0){
                    return;
                }
                break;
            }else if(paixu.get(i)==6){
                commIdString=managerMapForErpMapper.commIdString(getAccessToken().getUserCode());
                if(commIdString==null||commIdString.size()==0){
                    return;
                }
                break;
            }
        }
//      sheet汇总
        HSSFWorkbook workbook=new HSSFWorkbook();
        ExportExcelUtil util = new ExportExcelUtil();
        int sheetIndex=0;
//      项目进驻计划
        HSSFWorkbook result1 = rdDistrictSettledService.exportAllRdDistrictSettledService(getAccessToken(),response);
        workbook.createSheet(result1.getSheetAt(0).getSheetName());
        POIUtil.copySheet(result1,workbook,0,sheetIndex);
        sheetIndex++;
//     TODO 项目交付计划
        HSSFWorkbook result1jiaofu = rdPendingBuildingProjectService.exportAllRdPendingBuildingProject(getAccessToken(),response);
        workbook.createSheet(result1jiaofu.getSheetAt(0).getSheetName());
        POIUtil.copySheet(result1jiaofu,workbook,0,sheetIndex);
        sheetIndex++;
//     TODO  未开盘项目信息

        HSSFWorkbook resultweikai = rdNewProjectService.exportAllRdNewProject(getAccessToken(),response);
        workbook.createSheet(resultweikai.getSheetAt(0).getSheetName());
        POIUtil.copySheet(resultweikai,workbook,0,sheetIndex);
        sheetIndex++;
        //  TODO  未收楼项目信息
        HSSFWorkbook resultwweishou = rdUncollectedBuildingProjectsService.exportAllRdUncollectedBuildingProjects(getAccessToken(),response);
        workbook.createSheet(resultwweishou.getSheetAt(0).getSheetName());
        POIUtil.copySheet(resultwweishou,workbook,0,sheetIndex);
        sheetIndex++;
//      TODO 已收楼项目信息

        HSSFWorkbook resultyishou = rdClosedBuildingProjectService.exportAllRdClosedBuildingProject(getAccessToken(),response);
        workbook.createSheet(resultyishou.getSheetAt(0).getSheetName());
        POIUtil.copySheet(resultyishou,workbook,0,sheetIndex);
        sheetIndex++;
//      TODO 项目信息汇总

        HSSFWorkbook resultzong = rdprojectInformationSummaryService.exportAllRdprojectInformationSummary(getAccessToken(),response);
        workbook.createSheet(resultzong.getSheetAt(0).getSheetName());
        POIUtil.copySheet(resultzong,workbook,0,sheetIndex);

        response.setContentType("multipart/form-data");
        String fileName = URLEncoder.encode("区域汇总报表.xls","UTF-8");
        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
        workbook.write(response.getOutputStream());
    }





}
