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.RdUncollectedBuildingProjectsMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.ManagerMapForErpMapper;
import cn.com.countrygarden.bi.main.dto.districtReport.RdUncollectedBuildingProjectsDTO;
import cn.com.countrygarden.bi.main.dto.districtReport.RdUncollectedBuildingProjectsVO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.districtReport.RdUncollectedBuildingProjects;
import cn.com.countrygarden.bi.main.service.districtReport.RdProjectpermissionService;
import cn.com.countrygarden.bi.main.service.districtReport.RdUncollectedBuildingProjectsService;
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("RdUncollectedBuildingProjectsController")
@RequestMapping("/api/rdUncollectedBuildingProjects")
public class RdUncollectedBuildingProjectsController extends BaseController{
    @Autowired
    private RdUncollectedBuildingProjectsService rdUncollectedBuildingProjectsService;

    @Autowired
    private RdUncollectedBuildingProjectsMapper rdUncollectedBuildingProjectsMapper;

    @Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;

    @Autowired
    private RdProjectpermissionService rdProjectpermissionService;

    @GetMapping(value = "/list", produces = "application/json;charset=utf-8")
    public Result list(RdUncollectedBuildingProjectsDTO rdUncollectedBuildingProjectsDTO,
                       @RequestParam(value = "size", required = false, defaultValue = "10") int size,
                       @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                       HttpServletRequest request){
        return  rdUncollectedBuildingProjectsService.queryPageList(rdUncollectedBuildingProjectsDTO,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  rdUncollectedBuildingProjectsService.queryById(id);
    }

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

    @PostMapping(value = "/add")
    public Result add(RdUncollectedBuildingProjects rdUncollectedBuildingProjects,
                      HttpServletRequest request){
        return  rdUncollectedBuildingProjectsService.add(rdUncollectedBuildingProjects,getAccessToken(request));
    }

    @PutMapping(value = "/edit")
    public Result edit(RdUncollectedBuildingProjects rdUncollectedBuildingProjects, HttpServletRequest request){
        return  rdUncollectedBuildingProjectsService.edit(rdUncollectedBuildingProjects,getAccessToken(request));
    }

    @DeleteMapping(value="/del")
    public Result del(@RequestParam(value = "id", required = true)Integer id,@RequestParam(value = "updateName", required = true)String updateName){
        return  rdUncollectedBuildingProjectsService.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  rdUncollectedBuildingProjectsService.delpiliang(ids,getAccessToken(),updateName);
    }

    //导出数据
    @RequestMapping(value = "/evaluationrdUncollectedBuildingProjects", produces = "multipart/form-data",  method = RequestMethod.GET)
    public void evaluationrdUncollectedBuildingProjects(RdUncollectedBuildingProjectsDTO rdUncollectedBuildingProjectsDTO,
                                       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;
                }
                break;
            }
        }

        ExportExcelUtil<RdUncollectedBuildingProjectsVO> util = new ExportExcelUtil<RdUncollectedBuildingProjectsVO>();
        String[] columnNames = {"片区名称"  , "项目名称"  , "营销定级" , "物业定级" , "开放时间","开盘时间","项目（驻场）负责人）",
                "联系方式" ,"案场数量","年货值-已售","年货值-剩余","管理形态","接管面积（㎡）","日客流量（组）",
                "别墅样板房（间）","洋房样板房（间）","高层样板房（间）"};
        /*String[] idInte=ids.split(",");
        List<String> rids = Arrays.asList(idInte);*/

        if(StringUtil.isNotBlank(rdUncollectedBuildingProjectsDTO.getOpenDateList())){
            String[] openDateList=rdUncollectedBuildingProjectsDTO.getOpenDateList().split(",");
            rdUncollectedBuildingProjectsDTO.setOpenDateString1(openDateList[0]);
            rdUncollectedBuildingProjectsDTO.setOpenDateString2(openDateList[1]);
        }
        if(StringUtil.isNotBlank(rdUncollectedBuildingProjectsDTO.getOpeningDateList())){
            String[] openingDateList=rdUncollectedBuildingProjectsDTO.getOpeningDateList().split(",");
            rdUncollectedBuildingProjectsDTO.setOpeningDateString1(openingDateList[0]);
            rdUncollectedBuildingProjectsDTO.setOpeningDateString2(openingDateList[1]);
        }

        Collection<RdUncollectedBuildingProjectsVO> list=rdUncollectedBuildingProjectsMapper.evaluationrdUncollectedBuildingProjects(rdUncollectedBuildingProjectsDTO,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(rdUncollectedBuildingProjectsService.excelToxls(radio, multipartFile, fileName, usname,
                    getAccessToken().getUserCode(), getAccessToken(request)));
        }
        if (fileName.indexOf(".xls") != -1) {
            return Response.response(rdUncollectedBuildingProjectsService.excelToxls(radio, multipartFile, fileName, usname,
                    getAccessToken().getUserCode(), getAccessToken(request)));
        }
        return Response.responseFail("上传文件应为excel文件格式为：xlsx或xls");
    }

}