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.RdDistrictInfoMapper;
import cn.com.countrygarden.bi.main.dao.districtReport.RdDistrictPrincipalMapper;
import cn.com.countrygarden.bi.main.dao.districtReport.RdDistrictSettledMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.ManagerMapForErpMapper;
import cn.com.countrygarden.bi.main.dto.districtReport.RdDistrictSettledDTO;
import cn.com.countrygarden.bi.main.dto.districtReport.RdDistrictSettledVO;
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.RdDistrictInfo;
import cn.com.countrygarden.bi.main.model.districtReport.RdDistrictSettled;
import cn.com.countrygarden.bi.main.model.dup.DupOrgan;
import cn.com.countrygarden.bi.main.service.districtReport.RdDistrictSettledService;
import cn.com.countrygarden.bi.main.service.districtReport.RdProjectpermissionService;
import cn.com.countrygarden.bi.main.util.ExportExcelUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 片区项目入驻-项目进驻计划-业务逻辑层实现
 *
 * @author 吕伟峰
 * @email www.justintoforest@gamail.com
 * @url 
 * @date 2019-08-14
 */
@Service
@Transactional
public class RdDistrictSettledServiceImpl implements RdDistrictSettledService{
    @Autowired
    private RdDistrictSettledMapper rdDistrictSettledMapper;

    @Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;

    @Autowired
    private RdDistrictInfoMapper rdDistrictInfoMapper;

    @Autowired
    private RdProjectpermissionService rdProjectpermissionService;

    @Autowired
    private RdDistrictPrincipalMapper rdDistrictPrincipalMapper;

    @Override
    public Result queryPageList(RdDistrictSettledDTO rdDistrictSettledDTO, 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){
                //throw new ServiceException("项目进度_项目用户,无法使用此模块");
               /* commIdString=managerMapForErpMapper.commIdStringName(accessToken.getUserCode());
                if(commIdString==null||commIdString.size()==0){
                    return null;
                }*/
                rdDistrictSettledDTO.setCreateBy(accessToken.getUserCode());
                commIdString=null;
                organCodeString=null;
                break;
            }
        }

        if(StringUtils.isNotBlank(rdDistrictSettledDTO.getProjectdate())){
            String[] data=rdDistrictSettledDTO.getProjectdate().split(",");
            rdDistrictSettledDTO.setProjectdateleft(data[0]);
            rdDistrictSettledDTO.setProjectdateright(data[1]);
        }
        Page<Object> pageList = PageHelper.startPage(page, size);
        List<RdDistrictSettledDTO> queryPageList=rdDistrictSettledMapper.queryPageList(rdDistrictSettledDTO,organCodeString,commIdString,principaString);
        PageData data=new PageData(pageList);
        data.setData(pageList.getResult());
        return Response.response(data);
    }

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

    @Override
    public Result settledDTOAddone(String regionCode, String districtCode,String projectName,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(rdDistrictSettledMapper.settledDTOAddone(regionCode,districtCode,projectName,createdBy));
    }

    @Override
    public Result  add(RdDistrictSettled rdDistrictSettled, AccessToken accessToken) {
        DecimalFormat df = new DecimalFormat("#.##");
        Double get_double = Double.parseDouble(df.format(rdDistrictSettled.getEmplacementProjectArea()));
        int count=rdDistrictSettledMapper.districtProjectName(rdDistrictSettled.getProjectName());
        if(count>0){
            throw new ServiceException("项目名不能重复，请核对");
        }
        rdDistrictSettled.setId(null);
        rdDistrictSettled.setEnable(1);
        rdDistrictSettled.setEmplacementProjectArea(get_double);
        rdDistrictSettled.setCreateBy(accessToken.getUserCode());
        rdDistrictSettled.setCreateTime(new Date());
        rdDistrictSettledMapper.insert(rdDistrictSettled);
        return Response.response();
    }

    @Override
    public Result edit(RdDistrictSettled rdDistrictSettled, AccessToken accessToken) {
        DecimalFormat df = new DecimalFormat("#.##");
        Double get_double = Double.parseDouble(df.format(rdDistrictSettled.getEmplacementProjectArea()));
        rdDistrictSettled.setEnable(1);
        rdDistrictSettled.setEmplacementProjectArea(get_double);
        rdDistrictSettled.setUpdateTime(new Date());
        rdDistrictSettledMapper.update(rdDistrictSettled);
        return Response.response();
    }

    @Override
    public Result del(Integer id,AccessToken accessToken,String updateName) {
        int count = rdDistrictSettledMapper.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);
        rdDistrictSettledMapper.delpingliangtag(rids,accessToken.getUserCode(),updateName);
        return Response.response("删除成功");
    }

    @Override
    public Result excelToxls(Integer radio, MultipartFile multipartFile, String fileName, String usname, String userCode, AccessToken accessToken) {
        SimpleDateFormat dFormat = new SimpleDateFormat("yyyy/MM/dd");
        BufferedInputStream bf = null;
        Sheet sheet = null;
        Workbook xwb = null;
        try {

            // 获取登录人的角色授权
            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){
                    organCodeString=managerMapForErpMapper.organCodeString(accessToken.getUserCode(),null);
                    if(organCodeString==null||organCodeString.size()==0){
                        return null;
                    }
                    break;
                }else if (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){
                    //throw new ServiceException("项目进度_项目用户,无法使用此模块");
                    commIdString=managerMapForErpMapper.commIdString(accessToken.getUserCode());
                    if(commIdString==null||commIdString.size()==0){
                        return null;
                    }
                    organCodeString=managerMapForErpMapper.organCodeString(userCode,commIdString);
                    if(organCodeString==null||organCodeString.size()==0){
                        return null;
                    }
                    break;
                }
            }


            CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
            bf = new BufferedInputStream(commonsMultipartFile.getInputStream());
            if (fileName.endsWith("xls")) { // Excel&nbsp;2003
                xwb = new HSSFWorkbook(bf);
            } else if (fileName.endsWith("xlsx")) { // Excel 2007/2010
                xwb = new XSSFWorkbook(bf);
            }
            sheet = xwb.getSheetAt(0);//获取第几个页面0开始
            Row row = null;
            Cell cell;
            RdDistrictSettledDTO rdDistrictSettledDTO=null;
            RdDistrictInfo rdDistrictInfo=null;
            RdDistrictSettled rdDistrictSettled=null;
            List<RdDistrictSettledDTO> districtSettledone=new ArrayList<>();
            for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
                row = sheet.getRow(i+3);
                if(row==null) {
                    break;
                }
                for(int j =0;j<sheet.getRow(i+1).getPhysicalNumberOfCells();j++) {
                    cell = row.getCell(0);
                    if(cell==null) {
                        break;
                    }
                    cell.setCellType(CellType.STRING);
                    String regionName=cell.getStringCellValue();
                    if(StringUtils.isBlank(regionName)){
                        break;
                    }

                    cell = row.getCell(1);
                    cell.setCellType(CellType.STRING);
                    String districtName=cell.getStringCellValue();

                    if(StringUtils.isBlank(districtName)){
                      throw new ServiceException("第" + (i + 4) + "行" + "片区不能为空");
                    }

                  cell =  row.getCell(2);
                    cell.setCellType(CellType.STRING);
                    String projectName=cell.getStringCellValue();

                    if(StringUtils.isBlank(projectName)){
                        throw new ServiceException("第" + (i + 4) + "行" + "项目不能为空");
                    }

                    cell =  row.getCell(3);
                    cell.setCellType(CellType.STRING);
                    String emplacementProjectDate=cell.getStringCellValue();

                    if(StringUtils.isBlank(emplacementProjectDate)){
                        throw new ServiceException("第" + (i + 4) + "行" + "预计进驻时间不能为空");
                    }

                    cell =  row.getCell(4);
                    cell.setCellType(CellType.STRING);
                    String projectPlace=cell.getStringCellValue();

                    if(StringUtils.isBlank(projectPlace)){
                        throw new ServiceException("第" + (i + 4) + "行" + "项目位置不能为空");
                    }

                    cell =  row.getCell(5);
                    cell.setCellType(CellType.STRING);
                    String emplacementProjectArea=cell.getStringCellValue();

                    if(StringUtils.isBlank(emplacementProjectArea)){
                        throw new ServiceException("第" + (i + 4) + "行" + "预计规划面积不能为空");
                    }
                    cell =  row.getCell(6);
                    cell.setCellType(CellType.STRING);
                    String descs=cell.getStringCellValue();

                    DecimalFormat df = new DecimalFormat("#.##");
                    Double get_double = Double.parseDouble(df.format(BigDecimal.valueOf(Double.parseDouble(emplacementProjectArea))));
                    List<DupOrgan> result =managerMapForErpMapper.queryAllRegionRdDistrict(regionName,null,organCodeString);
                    if (result.size()==0||result==null){
                       throw new ServiceException("第" + (i + 4) + "行" + "没有该区域,或者没有该区域权限");
                    }

                    List<RdDistrictInfo> rdDistrictInfoBown=rdDistrictInfoMapper.rdDistrictInfoBownName(regionName,districtName,principaString);
                    rdDistrictSettledDTO=new RdDistrictSettledDTO();
                    Date projectDate = null;
                    if (StringUtils.isNotBlank(emplacementProjectDate)){
                        try {
                            projectDate = dFormat.parse(emplacementProjectDate);
                            rdDistrictSettledDTO.setEmplacementProjectDate(projectDate);
                        }catch (ParseException e) {
                            throw new ServiceException("第" + (i + 4) + "行" + "时间格式错误，请按照  yyyy/MM/dd  格式添加");
                        }catch (Exception e) {
                            throw new ServiceException("第" + (i + 4) + "行" + "时间格式错误，请按照  yyyy/MM/dd  格式添加");
                        }
                    }

                    if (rdDistrictInfoBown.size()==0){
                        throw new ServiceException("第" + (i + 4) + "行" + "没有该片区或者没有该片区权限");
                    }else {
                        rdDistrictSettledDTO.setRegionCode(result.get(0).getOrganCode());
                        rdDistrictSettledDTO.setDistrictCode(rdDistrictInfoBown.get(0).getDistrictCode());
                        rdDistrictSettledDTO.setProjectName(projectName);
                        districtSettledone=rdDistrictSettledMapper.districtSettledone(rdDistrictSettledDTO);
                    }

                    int countMp=rdDistrictInfoMapper.countProjectMp(rdDistrictInfoBown.get(0).getDistrictCode(),projectName);
                    if(countMp==0){
                        throw new ServiceException("第" + (i + 4) + "行" + "该片区下没有这项目名称");
                    }

                    if(districtSettledone.size()==0||districtSettledone==null){
                        /*if (rdDistrictInfoBown.size()==0){
                            rdDistrictInfo=new RdDistrictInfo();
                            rdDistrictInfo.setRegionCode(result.get(0).getOrganCode());
                            rdDistrictInfo.setRegionName(result.get(0).getOrganName());
                            rdDistrictInfo.setDistrictCode(rdDistrictInfo.getRegionCode()+"_"+String.valueOf(new Date().getTime()));
                            rdDistrictInfo.setDistrictName(districtName);
                            rdDistrictInfo.setType(1);
                            rdDistrictInfo.setEnable(1);
                            rdDistrictInfo.setCreateTime(new Date());
                            rdDistrictInfo.setCreateBy(usname);
                            int index=rdDistrictInfoMapper.insert(rdDistrictInfo);
                            if (index>0){*/
                        int count=rdDistrictSettledMapper.districtProjectName(projectName);

                        if(count>0){
                            throw new ServiceException("第" + (i + 4) + "行" + "项目名不能重复，请核对");
                        }
                                rdDistrictSettled=new RdDistrictSettled();
                                rdDistrictSettled.setDistrictCode(rdDistrictInfoBown.get(0).getDistrictCode());
                                rdDistrictSettled.setProjectName(projectName);
                                rdDistrictSettled.setEmplacementProjectDate(rdDistrictSettledDTO.getEmplacementProjectDate());
                                rdDistrictSettled.setProjectPlace(projectPlace);
                                rdDistrictSettled.setEmplacementProjectArea(Double.valueOf(get_double));
                                rdDistrictSettled.setDescs(descs);
                                rdDistrictSettled.setCreateBy(accessToken.getUserCode());
                                rdDistrictSettled.setCreateName(usname);
                                rdDistrictSettled.setCreateTime(new Date());
                                rdDistrictSettled.setEnable(1);
                                rdDistrictSettledMapper.insert(rdDistrictSettled);
                           // }
                        }else {
                        rdDistrictSettled=new RdDistrictSettled();
                        rdDistrictSettled.setId(districtSettledone.get(0).getId());
                        rdDistrictSettled.setProjectName(projectName);
                        rdDistrictSettled.setEmplacementProjectDate(rdDistrictSettledDTO.getEmplacementProjectDate());
                        rdDistrictSettled.setProjectPlace(projectPlace);
                        rdDistrictSettled.setEmplacementProjectArea(Double.valueOf(get_double));
                        rdDistrictSettled.setDescs(descs);
                        rdDistrictSettled.setUpdateTime(new Date());
                        rdDistrictSettled.setUpdateBy(usname);
                        rdDistrictSettled.setEnable(1);
                        rdDistrictSettledMapper.update(rdDistrictSettled);
                        }
                    j+=6;
                }
            }
            return Response.response("导入成功");
        }catch (IOException e1) {
            e1.printStackTrace();
            throw new ServiceException("导入失败！请稍后重试！");
        }
    }

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

        ExportExcelUtil util = new ExportExcelUtil();
        // 获取登录人的角色授权
        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);
        RdDistrictSettledDTO rdDistrictSettledDTO=new RdDistrictSettledDTO();
        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){
                rdDistrictSettledDTO.setCreateBy(accessToken.getUserCode());
                commIdString=null;
                organCodeString=null;
                break;
            }
        }

        String[] columnNames = { "区域名称" ,"片区名称" ,"项目名称" ,"预计进驻时间" ,"项目位置" ,"预计规划面积","备注"};
        Collection<RdDistrictSettledVO> list=rdDistrictSettledMapper.evaluationrdDistrictSettled(rdDistrictSettledDTO,organCodeString,principaString);
        HSSFWorkbook result1 = util.getWorkbook2003("项目进驻计划", columnNames, list, response.getOutputStream(), "yyyy-MM-dd HH:mm:ss", null);
        return result1;
    }

}