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.RdClosedBuildingProjectMapper;
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.RdClosedBuildingProjectVO;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.districtReport.RdClosedBuildingProject;
import cn.com.countrygarden.bi.main.service.districtReport.RdClosedBuildingProjectService;
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("RdClosedBuildingProjectController")
@RequestMapping("/api/rdClosedBuildingProject")
public class RdClosedBuildingProjectController extends BaseController{
    @Autowired
    private RdClosedBuildingProjectService rdClosedBuildingProjectService;

    @Autowired
    private RdClosedBuildingProjectMapper rdClosedBuildingProjectMapper;

    @Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;

    @Autowired
    private RdProjectpermissionService rdProjectpermissionService;


    @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  rdClosedBuildingProjectService.queryPageList(rdClosedBuildingProjectDTO,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  rdClosedBuildingProjectService.queryById(id);
    }

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

    @PostMapping(value = "/add")
    public Result add(RdClosedBuildingProjectDTO rdClosedBuildingProjectDTO,
                      HttpServletRequest request){
        return  rdClosedBuildingProjectService.add(rdClosedBuildingProjectDTO,getAccessToken(request));
    }

    @PutMapping(value = "/edit")
    public Result edit(RdClosedBuildingProject rdClosedBuildingProject, HttpServletRequest request){
        return  rdClosedBuildingProjectService.edit(rdClosedBuildingProject,getAccessToken(request));
    }

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

    //导出数据
    @RequestMapping(value = "/evaluationrdClosedBuildingProject", produces = "multipart/form-data",  method = RequestMethod.GET)
    public void evaluationrdClosedBuildingProject(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<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<RdClosedBuildingProjectVO> util = new ExportExcelUtil<RdClosedBuildingProjectVO>();
        String[] columnNames = { "区域名称" ,"片区名称" ,"项目名称"  , "规划占地面积" , "规划建筑面积" , "接管建筑面积","规划车位面积","可收费面积-住宅",
                "可收费面积-商业" ,"规划户数（户）","累积接管户数（户）","接管车位数（户）","业态构成","首批交付时间","物业费标准（元/㎡/月）","车位服务费标准（元/月）",
                "物业费综合收缴率","往年欠费追缴率","绿化面积（㎡）","容积率","建筑密度","项目地址","办公地址","联系方式","项目负责人","电梯数量","外占应收比","委外项目","委外单位",
                "编制数量-客服","编制数量-秩序","编制数量-工程","编制数量-保洁","编制数量-案场","编制数量-其他","备注","同步时间","同步人"};
       /* String[] idInte=ids.split(",");
        List<String> rids = Arrays.asList(idInte);*/

        if(StringUtil.isNotBlank(rdClosedBuildingProjectDTO.getFirstPayDateList())){
            String[] firstPayDate=rdClosedBuildingProjectDTO.getFirstPayDateList().split(",");
            rdClosedBuildingProjectDTO.setFirstPayDateList1(firstPayDate[0]);
            rdClosedBuildingProjectDTO.setFirstPayDateList2(firstPayDate[1]);
        }

        Collection<RdClosedBuildingProjectVO> list=rdClosedBuildingProjectMapper.evaluationrdClosedBuildingProject(rdClosedBuildingProjectDTO,organCodeString,commIdString,principaString);
        for(int i=0;i<list.size();i++){
            if (StringUtil.isNotBlank(((List<RdClosedBuildingProjectVO>) list).get(i).getIndustryComposition())){
                String[] industryComposition=((List<RdClosedBuildingProjectVO>) list).get(i).getIndustryComposition().split(",");
                List<String> industryCompo = Arrays.asList(industryComposition);
                Set<String> industryCompoSet=new HashSet<>(industryCompo);
                List<String> industryCompoList = new ArrayList(industryCompoSet);
                String ind="";
                for (int y=0;y<industryCompoList.size();y++){
                    ind+=industryCompoList.get(y)+"  ";
                }
                ((List<RdClosedBuildingProjectVO>) list).get(i).setIndustryComposition(ind);
            }

            if (StringUtil.isNotBlank(((List<RdClosedBuildingProjectVO>) list).get(i).getPropertyPrice())){
                String[] propertyPrice=((List<RdClosedBuildingProjectVO>) list).get(i).getPropertyPrice().split(",");
                List<String> property = Arrays.asList(propertyPrice);
                Set<String> propertySet=new HashSet<>(property);
                List<String> propertyList = new ArrayList(propertySet);
                String pr="";
                for (int y=0;y<propertyList.size();y++){
                    pr+=propertyList.get(y)+"  ";
                }
                ((List<RdClosedBuildingProjectVO>) list).get(i).setPropertyPrice(pr);
            }


            if (StringUtil.isNotBlank(((List<RdClosedBuildingProjectVO>) list).get(i).getCarPrice())){
                String[] carPrice=((List<RdClosedBuildingProjectVO>) list).get(i).getCarPrice().split(",");
                List<String> car = Arrays.asList(carPrice);
                Set<String> carSet=new HashSet<>(car);
                List<String> carList = new ArrayList(carSet);
                String ca="";
                for (int y=0;y<carList.size();y++){
                    ca+=carList.get(y)+"  ";
                }
                ((List<RdClosedBuildingProjectVO>) list).get(i).setCarPrice(ca);
            }
        }
        
        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);
    }

}