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.RdNewProjectMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.ManagerMapForErpMapper;
import cn.com.countrygarden.bi.main.dto.districtReport.RdNewProjectDTO;
import cn.com.countrygarden.bi.main.dto.districtReport.RdNewProjectVO;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.districtReport.RdNewProject;
import cn.com.countrygarden.bi.main.service.districtReport.RdNewProjectService;
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 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("RdNewProjectController")
@RequestMapping("/api/rdNewProject")
public class RdNewProjectController extends BaseController{
    @Autowired
    private RdNewProjectService rdNewProjectService;

    @Autowired
    private RdNewProjectMapper rdNewProjectMapper;

    @Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;

    @Autowired
    private RdProjectpermissionService rdProjectpermissionService;

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

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

    @PostMapping(value = "/add")
    public Result add(RdNewProjectDTO rdNewProjectDTO,
                      HttpServletRequest request){
        return  rdNewProjectService.add(rdNewProjectDTO,getAccessToken(request));
    }

    @PutMapping(value = "/edit")
    public Result edit(RdNewProject rdNewProject, HttpServletRequest request){
        return  rdNewProjectService.edit(rdNewProject,getAccessToken(request));
    }

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

    @PutMapping(value = "/synchronousData")
    public Result synchronousData(@RequestParam(value = "id", required = true)Integer id,@RequestParam(value = "regionCode", required = true)String regionCode,
                                  @RequestParam(value = "projectCode", required = true)String projectCode,
                                  @RequestParam(value = "syncUsercode", required = true)String syncUsercode,
                                  HttpServletRequest request){
        return  rdNewProjectService.synchronousData(id,regionCode,projectCode,syncUsercode,getAccessToken(request));
    }

    @PutMapping(value = "/synchronousDataAll")
    public Result synchronousDataAll(@RequestParam(value = "ids", required = true)String ids,@RequestParam(value = "regionCodeList", required = true)String regionCodeList,
                                  @RequestParam(value = "projectCodeList", required = true)String projectCodeList,
                                  @RequestParam(value = "syncUsercode", required = true)String syncUsercode,
                                  HttpServletRequest request){
        return  rdNewProjectService.synchronousDataAll(ids,regionCodeList,projectCodeList,syncUsercode,getAccessToken(request));
    }

    //导出数据
    @RequestMapping(value = "/evaluationRdNewProject", produces = "multipart/form-data",  method = RequestMethod.GET)
    public void evaluationRdNewProject(RdNewProjectDTO rdNewProjectDTO,
                                   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<RdNewProjectVO> util = new ExportExcelUtil<RdNewProjectVO>();
        String[] columnNames = { "区域名称" ,"片区名称"  , "项目名称"  , "规划用地面积（亩）" , "总建筑面积（万㎡）" , "建筑类型","总规划（户）","物业费定价（元/㎡/月）",
                "展厅开放日期" ,"展厅面积（㎡）","综合楼面积（㎡）","示范区面积（㎡）","开放日期","预计开盘时间"};
       /* String[] idInte=ids.split(",");
        List<String> rids = Arrays.asList(idInte);*/

        Collection<RdNewProjectVO> list=rdNewProjectMapper.evaluationRdNewProject(rdNewProjectDTO,organCodeString,commIdString,principaString);
        for(int i=0;i<list.size();i++){
            if(StringUtil.isNotBlank(((List<RdNewProjectVO>) list).get(i).getBuildingType())){
                String[] buildingType=((List<RdNewProjectVO>) list).get(i).getBuildingType().split(",");
                List<String> buildin = Arrays.asList(buildingType);
                Set<String> buildinSet=new HashSet<>(buildin);
                List<String> buildinList = new ArrayList(buildinSet);
                String bu="";
                for (int y=0;y<buildinList.size();y++){
                  bu+=buildinList.get(y)+"  ";
                }
                ((List<RdNewProjectVO>) list).get(i).setBuildingType(bu);
            }

            if(StringUtil.isNotBlank(((List<RdNewProjectVO>) list).get(i).getPropertyPrice())){
                String[] propertyfeepricing=((List<RdNewProjectVO>) list).get(i).getPropertyPrice().split(",");
                List<String> propertyf = Arrays.asList(propertyfeepricing);
                Set<String> propertyfSet=new HashSet<>(propertyf);
                List<String> propertyfList = new ArrayList(propertyfSet);
                String pr="";
                for (int y=0;y<propertyfList.size();y++){
                    pr+=propertyfList.get(y)+"  ";
                }
                ((List<RdNewProjectVO>) list).get(i).setPropertyPrice(pr);
            }
        }
        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);
    }

}