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

import cn.com.countrygarden.bi.main.controller.BaseController;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.districtReport.RdPendingBuildingProjectMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.ManagerMapForErpMapper;
import cn.com.countrygarden.bi.main.dto.districtReport.RdPendingBuildingProjectDTO;
import cn.com.countrygarden.bi.main.dto.districtReport.RdPendingBuildingProjectVO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.districtReport.RdPendingBuildingProject;
import cn.com.countrygarden.bi.main.service.districtReport.RdPendingBuildingProjectService;
import cn.com.countrygarden.bi.main.service.districtReport.RdProjectpermissionService;
import cn.com.countrygarden.bi.main.util.ExportExcelUtil;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

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("RdPendingBuildingProjectController")
@RequestMapping("/api/rdPendingBuildingProject")
public class RdPendingBuildingProjectController extends BaseController{
    @Autowired
    private RdPendingBuildingProjectService rdPendingBuildingProjectService;

    @Autowired
    private RdPendingBuildingProjectMapper rdPendingBuildingProjectMapper;

    @Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;

    @Autowired
    private RdProjectpermissionService rdProjectpermissionService;

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

    @GetMapping(value = "/one", produces = "application/json;charset=utf-8")
    public Result queryById(@RequestParam(value = "id", required = true)Integer id,
                            HttpServletRequest request){
        return  rdPendingBuildingProjectService.queryById(id);
    }

    @GetMapping(value = "/buildingProjectAddone", produces = "application/json;charset=utf-8")
    public Result buildingProjectAddone(@RequestParam(value = "regionCode", required = true)String regionCode,
                                        @RequestParam(value = "districtCode", required = true)String districtCode,
                                        @RequestParam(value = "projectName", required = true)String projectName,
                            HttpServletRequest request){
        return  rdPendingBuildingProjectService.buildingProjectAddone(regionCode,districtCode,projectName,getAccessToken());
    }

    @PostMapping(value = "/add")
    public Result add(RdPendingBuildingProject rdPendingBuildingProject,
                      HttpServletRequest request){
        return  rdPendingBuildingProjectService.add(rdPendingBuildingProject,getAccessToken(request));
    }

    @PutMapping(value = "/edit")
    public Result edit(RdPendingBuildingProject rdPendingBuildingProject, HttpServletRequest request){
        return  rdPendingBuildingProjectService.edit(rdPendingBuildingProject,getAccessToken(request));
    }

    @DeleteMapping(value="/del")
    public Result del(@RequestParam(value = "id", required = true)Integer id,@RequestParam(value = "updateName", required = true)String updateName){
        return  rdPendingBuildingProjectService.del(id,getAccessToken(),updateName);
    }

    @DeleteMapping(value="/delpiliang")
    public Result delpiliang(
            @RequestParam(value="ids",required=false)String ids,@RequestParam(value = "updateName", required = true)String updateName){
        return  rdPendingBuildingProjectService.delpiliang(ids,getAccessToken(),updateName);
    }

    //导出数据
    @RequestMapping(value = "/evaluationrdPendingBuildingProject", produces = "multipart/form-data",  method = RequestMethod.GET)
    public void evaluationrdPendingBuildingProject(RdPendingBuildingProjectDTO rdPendingBuildingProjectDTO,
                                                        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<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;
                }*/
                rdPendingBuildingProjectDTO.setCreateBy(getAccessToken().getUserCode());
                commIdString=null;
                break;
            }
        }

        ExportExcelUtil<RdPendingBuildingProjectVO> util = new ExportExcelUtil<RdPendingBuildingProjectVO>();
        String[] columnNames = {"区域名称","片区名称" ,"项目名称"  , "建筑类型" , "接管面积（万㎡）" , "合同收楼日期","暂定收楼日期","接管户数",
                "精装交付户数" ,"精装可收费面积（万㎡）","毛坯交付户数","毛坯可收费面积（万㎡）","物业费单价（元/㎡/月）","物业用房面积（㎡）","物业服务中心面积（㎡）"
                };
        /*String[] idInte=ids.split(",");
        List<String> rids = Arrays.asList(idInte);*/

        if(StringUtil.isNotBlank(rdPendingBuildingProjectDTO.getContractCloseBuildingDateList())){
            String[] openDateList=rdPendingBuildingProjectDTO.getContractCloseBuildingDateList().split(",");
            rdPendingBuildingProjectDTO.setContractCloseBuildingDate1(openDateList[0]);
            rdPendingBuildingProjectDTO.setContractCloseBuildingDate2(openDateList[1]);
        }
        if(StringUtil.isNotBlank(rdPendingBuildingProjectDTO.getTemporaryCloseBuildingDateList())){
            String[] openingDateList=rdPendingBuildingProjectDTO.getTemporaryCloseBuildingDateList().split(",");
            rdPendingBuildingProjectDTO.setTemporaryCloseBuildingDate1(openingDateList[0]);
            rdPendingBuildingProjectDTO.setTemporaryCloseBuildingDate2(openingDateList[1]);
        }

        Collection<RdPendingBuildingProjectVO> list=rdPendingBuildingProjectMapper.evaluationrdUncollectedBuildingProjects(rdPendingBuildingProjectDTO,organCodeString,commIdString,principaString);
        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);
    }

    @ResponseBody
    @RequestMapping(value = "/importXlsx", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result importXlsx(@RequestParam(value = "usname", defaultValue = "", required = false) String usname,
                             @RequestParam(value = "radio", defaultValue = "", required = false) Integer radio,
                             HttpServletRequest request,
                             @RequestParam(value = "file", defaultValue = "", required = true) MultipartFile multipartFile)
            throws ServiceException {
        if (multipartFile == null) {
            throw new ServiceException("请选择需要上传的文件");
        }
        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
        if (commonsMultipartFile.isEmpty()) {
            return Response.responseFail("上传文件为空文件");
        }
        String fileName = commonsMultipartFile.getOriginalFilename();
        if (fileName.indexOf(".xlsx") != -1) {
            return Response.response(rdPendingBuildingProjectService.excelToxls(radio, multipartFile, fileName, usname,
                    getAccessToken().getUserCode(), getAccessToken(request)));
        }
        if (fileName.indexOf(".xls") != -1) {
            return Response.response(rdPendingBuildingProjectService.excelToxls(radio, multipartFile, fileName, usname,
                    getAccessToken().getUserCode(), getAccessToken(request)));
        }
        return Response.responseFail("上传文件应为excel文件格式为：xlsx或xls");
    }
}