package cn.com.countrygarden.bi.main.service.districtReport.impl;

import cn.com.countrygarden.bi.main.core.Response;
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.dto.districtReport.hasNotYetOpenedDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
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 com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 新项目信息-未开盘项目信息-业务逻辑层实现
 *
 * @author 吕伟峰
 * @email www.justintoforest@gamail.com
 * @url 
 * @date 2019-08-14
 */
@Service
@Transactional
public class RdNewProjectServiceImpl implements RdNewProjectService{
    @Autowired
    private RdNewProjectMapper rdNewProjectMapper;

    @Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;

    @Autowired
    private RdProjectpermissionService rdProjectpermissionService;

    @Override
    public Result queryPageList(RdNewProjectDTO rdNewProjectDTO, int page, int size,AccessToken accessToken) {

        // 获取登录人的角色授权
        Map<String, Object> rolesMap = rdProjectpermissionService.findRoleInfoMap(accessToken.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(accessToken.getUserCode());
                break;
            }else if(paixu.get(i)==4||paixu.get(i)==5){
                organCodeString=managerMapForErpMapper.organCodeString(accessToken.getUserCode(),null);
                if(organCodeString==null||organCodeString.size()==0){
                    return null;
                }
                break;
            }else if(paixu.get(i)==6){
                rdNewProjectDTO.setCreateBy(accessToken.getUserCode());
                commIdString=null;
                organCodeString=null;
                break;
               /* commIdString=managerMapForErpMapper.commIdString(accessToken.getUserCode());
                if(commIdString==null||commIdString.size()==0){
                    return null;
                }
                break;*/
            }
        }

        Page<Object> pageList = PageHelper.startPage(page, size);
        List<RdNewProjectDTO> queryPageList=rdNewProjectMapper.queryPageList(rdNewProjectDTO,organCodeString,commIdString,principaString);
        if(queryPageList!=null){
            for (int i=0;i<queryPageList.size();i++){
                if(StringUtil.isNotBlank(queryPageList.get(i).getBuildingType())){
                    String[] buildingType=queryPageList.get(i).getBuildingType().split(",");
                    List<String> buildin = Arrays.asList(buildingType);
                    queryPageList.get(i).setBuildingTypeList(buildin);
                }else {
                    String[] buildingType={"0"};
                    List<String> buildin = Arrays.asList(buildingType);
                    queryPageList.get(i).setBuildingTypeList(buildin);
                }
                if(StringUtil.isNotBlank(queryPageList.get(i).getPropertyPrice())){
                    String[] propertyfeepricing=queryPageList.get(i).getPropertyPrice().split(",");
                    List<String> propertyf = Arrays.asList(propertyfeepricing);
                    queryPageList.get(i).setPropertyPriceList(propertyf);
                }else {
                    String[] propertyfeepricing={"0"};
                    List<String> propertyf = Arrays.asList(propertyfeepricing);
                    queryPageList.get(i).setPropertyPriceList(propertyf);
                }
            }
        }
        PageData data=new PageData(pageList);
        data.setData(pageList.getResult());
        return Response.response(data);
    }

    @Override
    public Result queryById(Integer id) {
        return Response.response(rdNewProjectMapper.queryById(id));
    }

    @Override
    public Result rdNewProjectAddOne(String districtCode, String projectCode,AccessToken accessToken) {
        Map<String, Object> rolesMap = rdProjectpermissionService.findRoleInfoMap(accessToken.getUserCode());
        List<Integer> paixu=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_regionAdmin")){
                paixu.add(2);
            }
            if(entry.getKey().equals("project_manager_regionUser")){
                paixu.add(3);
            }
            if(entry.getKey().equals("project_manager_projectUser")){
                paixu.add(4);
            }
            if(entry.getKey().equals("role")){
                throw new ServiceException("权限不足,无法使用此模块");
            }
        }
        Collections.sort(paixu);
        String createdBy=null;
        if(paixu.get(0)==4){
            createdBy=accessToken.getUserCode();
        }
        return Response.response(rdNewProjectMapper.rdNewProjectAddOne(districtCode,projectCode,createdBy));
    }

    @Override
    public Result add(RdNewProjectDTO rdNewProjectDTO, AccessToken accessToken) {

       int count=rdNewProjectMapper.RdNewProjectAddone(rdNewProjectDTO);
        if(count>0){
            return Response.responseFail("项目名不能重复，请核实");
        }

        List<hasNotYetOpenedDTO> hasNotYetOpenedList=managerMapForErpMapper.hasNotYetOpenedList(rdNewProjectDTO.getRegionCode(),rdNewProjectDTO.getProjectCode());
        if(hasNotYetOpenedList!=null){
            List<RdNewProject> list=new ArrayList<>();
            try {
               /* if (hasNotYetOpenedList.get(0).getPlannedLandArea()!=null||hasNotYetOpenedList.get(0).getTotalSurfaceSrea()!=null||
                        hasNotYetOpenedList.get(0).getBuildingType()!=null||hasNotYetOpenedList.get(0).getMasterPlan()!=null||
                        hasNotYetOpenedList.get(0).getPropertyFeePricing()!=null){*/

                            RdNewProject rdNewProject=new RdNewProject();
                            rdNewProject.setDistrictCode(rdNewProjectDTO.getDistrictCode());
                            rdNewProject.setProjectCode(hasNotYetOpenedList.get(0).getCommid());
                            rdNewProject.setProjectName(hasNotYetOpenedList.get(0).getCommName());
                            if(hasNotYetOpenedList.get(0).getPlannedLandArea()!=null){
                                rdNewProject.setPlanPlaceArea(hasNotYetOpenedList.get(0).getPlannedLandArea());
                            }
                            if(hasNotYetOpenedList.get(0).getTotalSurfaceSrea()!=null){
                              rdNewProject.setTotalBuildArea(hasNotYetOpenedList.get(0).getTotalSurfaceSrea());
                             }
                             if(hasNotYetOpenedList.get(0).getBuildingType()!=null){
                                 rdNewProject.setBuildingType(hasNotYetOpenedList.get(0).getBuildingType());
                             }
                             if (hasNotYetOpenedList.get(0).getMasterPlan()!=null){
                                 rdNewProject.setPlaniTotalHouseholds(hasNotYetOpenedList.get(0).getMasterPlan());
                             }
                             if (hasNotYetOpenedList.get(0).getPropertyFeePricing()!=null){
                                 rdNewProject.setPropertyPrice(hasNotYetOpenedList.get(0).getPropertyFeePricing());
                             }
                            rdNewProject.setExhibitionStartDate(rdNewProjectDTO.getExhibitionStartDate());
                            rdNewProject.setExhibitionArea(rdNewProjectDTO.getExhibitionArea());
                            rdNewProject.setComprehensiveArea(rdNewProjectDTO.getComprehensiveArea());
                            rdNewProject.setDemonstrationArea(rdNewProjectDTO.getDemonstrationArea());
                            rdNewProject.setStartDate(rdNewProjectDTO.getStartDate());
                            if(rdNewProjectDTO.getEndDate()!=null){
                                rdNewProject.setEndDate(rdNewProjectDTO.getEndDate());
                            }
                            rdNewProject.setEnable(1);
                            rdNewProject.setCreateBy(accessToken.getUserCode());
                            rdNewProject.setCreateName(rdNewProjectDTO.getCreateName());
                            rdNewProject.setCreateTime(new Date());
                            list.add(rdNewProject);

                        rdNewProjectMapper.insert(rdNewProject);

               // }
            }catch (Exception e){
                return Response.responseFail("该项目没有相应信息，请检查ERP库");
            }
        }
        return Response.response();
    }

    @Override
    public Result edit(RdNewProject rdNewProject, AccessToken accessToken) {
        rdNewProject.setUpdateTime(new Date());
        rdNewProject.setEnable(1);
        rdNewProjectMapper.edit(rdNewProject);
        return Response.response();
    }

    @Override
    public Result synchronousData(Integer id,String regionCode, String projectCode,String syncUsercode,AccessToken accessToken) {

        List<hasNotYetOpenedDTO> hasNotYetOpenedList=managerMapForErpMapper.hasNotYetOpenedList(regionCode,projectCode);
        if(hasNotYetOpenedList!=null){
            try {
                /*if (hasNotYetOpenedList.get(0).getPlannedLandArea()!=null||hasNotYetOpenedList.get(0).getTotalSurfaceSrea()!=null||
                        hasNotYetOpenedList.get(0).getBuildingType()!=null||hasNotYetOpenedList.get(0).getMasterPlan()!=null||
                        hasNotYetOpenedList.get(0).getPropertyFeePricing()!=null){*/
                    RdNewProject rdNewProject=new RdNewProject();
                    rdNewProject.setId(id);
                    rdNewProject.setProjectCode(hasNotYetOpenedList.get(0).getCommid());
                    rdNewProject.setProjectName(hasNotYetOpenedList.get(0).getCommName());
                if(hasNotYetOpenedList.get(0).getPlannedLandArea()!=null){
                    rdNewProject.setPlanPlaceArea(hasNotYetOpenedList.get(0).getPlannedLandArea());
                }
                if(hasNotYetOpenedList.get(0).getTotalSurfaceSrea()!=null){
                    rdNewProject.setTotalBuildArea(hasNotYetOpenedList.get(0).getTotalSurfaceSrea());
                }
                if(hasNotYetOpenedList.get(0).getBuildingType()!=null){
                    rdNewProject.setBuildingType(hasNotYetOpenedList.get(0).getBuildingType());
                }
                if (hasNotYetOpenedList.get(0).getMasterPlan()!=null){
                    rdNewProject.setPlaniTotalHouseholds(hasNotYetOpenedList.get(0).getMasterPlan());
                }
                if (hasNotYetOpenedList.get(0).getPropertyFeePricing()!=null){
                    rdNewProject.setPropertyPrice(hasNotYetOpenedList.get(0).getPropertyFeePricing());
                }
                    rdNewProject.setEnable(1);
                    rdNewProject.setSyncDate(new Date());
                    rdNewProject.setSyncUsercode(syncUsercode);
                    rdNewProjectMapper.edit(rdNewProject);
                    return Response.response("同步完成");
                //}
            }catch (Exception e){
                return Response.responseFail("同步失败");
            }
        }
        return Response.responseFail("同步失败");
    }

    @Override
    public Result del(Integer id,AccessToken accessToken,String updateName) {
        int count = rdNewProjectMapper.deleteUpdate(id,accessToken.getUserCode(),updateName);
        return Response.response(count);
    }

    @Override
    public Result delpiliang(String ids,AccessToken accessToken,String updateName) {
        String[] idString=ids.split(",");
        List<String> rids =  Arrays.asList(idString);
        rdNewProjectMapper.delpingliangtag(rids,accessToken.getUserCode(),updateName);
        return Response.response("删除成功");
    }

    @Override
    public Result synchronousDataAll(String ids, String regionCodeList, String projectCodeList, String syncUsercode, AccessToken accessToken) {

        String[] idsInte=ids.split(",");
        String[] regionCodeInte=regionCodeList.split(",");
        String[] projectCodeInte=projectCodeList.split(",");

        List<String> id = Arrays.asList(idsInte);
        List<String> regionCode = Arrays.asList(regionCodeInte);
        List<String> projectCodeCode = Arrays.asList(projectCodeInte);

        for(int i=0;i<id.size();i++){
            List<hasNotYetOpenedDTO> hasNotYetOpenedList=managerMapForErpMapper.hasNotYetOpenedList(regionCode.get(i),projectCodeCode.get(i));
            if(hasNotYetOpenedList!=null) {
                try {
                   /* if (hasNotYetOpenedList.get(0).getPlannedLandArea()!=null||hasNotYetOpenedList.get(0).getTotalSurfaceSrea()!=null||
                            hasNotYetOpenedList.get(0).getBuildingType()!=null||hasNotYetOpenedList.get(0).getMasterPlan()!=null||
                            hasNotYetOpenedList.get(0).getPropertyFeePricing()!=null){*/
                        RdNewProject rdNewProject=new RdNewProject();
                        rdNewProject.setId(Integer.parseInt(id.get(i)));
                        rdNewProject.setProjectCode(hasNotYetOpenedList.get(0).getCommid());
                        rdNewProject.setProjectName(hasNotYetOpenedList.get(0).getCommName());
                    if(hasNotYetOpenedList.get(0).getPlannedLandArea()!=null){
                        rdNewProject.setPlanPlaceArea(hasNotYetOpenedList.get(0).getPlannedLandArea());
                    }
                    if(hasNotYetOpenedList.get(0).getTotalSurfaceSrea()!=null){
                        rdNewProject.setTotalBuildArea(hasNotYetOpenedList.get(0).getTotalSurfaceSrea());
                    }
                    if(hasNotYetOpenedList.get(0).getBuildingType()!=null){
                        rdNewProject.setBuildingType(hasNotYetOpenedList.get(0).getBuildingType());
                    }
                    if (hasNotYetOpenedList.get(0).getMasterPlan()!=null){
                        rdNewProject.setPlaniTotalHouseholds(hasNotYetOpenedList.get(0).getMasterPlan());
                    }
                    if (hasNotYetOpenedList.get(0).getPropertyFeePricing()!=null){
                        rdNewProject.setPropertyPrice(hasNotYetOpenedList.get(0).getPropertyFeePricing());
                    }
                        rdNewProject.setEnable(1);
                        rdNewProject.setSyncDate(new Date());
                        rdNewProject.setSyncUsercode(syncUsercode);
                        rdNewProjectMapper.edit(rdNewProject);
                    //}
                }catch (Exception e){
                    return Response.responseFail("同步失败");
                }
            }
        }
        return Response.response("同步成功");
    }

    @Override
    public HSSFWorkbook exportAllRdNewProject(AccessToken accessToken, HttpServletResponse response) throws IOException {

        // 获取登录人的角色授权
        Map<String, Object> rolesMap = rdProjectpermissionService.findRoleInfoMap(accessToken.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(accessToken.getUserCode());
                break;
            }else if(paixu.get(i)==4||paixu.get(i)==5){
                organCodeString=managerMapForErpMapper.organCodeString(accessToken.getUserCode(),null);
                if(organCodeString==null||organCodeString.size()==0){
                    return null;
                }
                break;
            }else if(paixu.get(i)==6){
                commIdString=managerMapForErpMapper.commIdString(accessToken.getUserCode());
                if(commIdString==null||commIdString.size()==0){
                    return null;
                }
                break;
            }
        }
        ExportExcelUtil util = new ExportExcelUtil();
        String[] columnNamesweikai = { "区域名称" ,"片区名称"  , "项目名称"  , "规划用地面积（亩）" , "总建筑面积（万㎡）" , "建筑类型","总规划（户）","物业费定价（元/㎡/月）",
                "展厅开放日期" ,"展厅面积（㎡）","综合楼面积（㎡）","示范区面积（㎡）","开放日期","开盘日期"};
        Collection<RdNewProjectVO> listweikai=rdNewProjectMapper.evaluationRdNewProject(new RdNewProjectDTO(),organCodeString,commIdString,principaString);
        for(int i=0;i<listweikai.size();i++){
            if(StringUtil.isNotBlank(((List<RdNewProjectVO>) listweikai).get(i).getBuildingType())){
                String[] buildingType=((List<RdNewProjectVO>) listweikai).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>) listweikai).get(i).setBuildingType(bu);
            }

            if(StringUtil.isNotBlank(((List<RdNewProjectVO>) listweikai).get(i).getPropertyPrice())){
                String[] propertyfeepricing=((List<RdNewProjectVO>) listweikai).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>) listweikai).get(i).setPropertyPrice(pr);
            }
        }
        HSSFWorkbook resultweikai = util.getWorkbook2003("未开盘项目信息", columnNamesweikai,listweikai, response.getOutputStream(), "yyyy-MM-dd HH:mm:ss", null);
        return resultweikai;
    }

}