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.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.districtReport.RdDistrictSettled;
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 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("RdDistrictSettledController")
@RequestMapping("/api/rdDistrictSettled")
public class RdDistrictSettledController extends BaseController{
    @Autowired
    private RdDistrictSettledService rdDistrictSettledService;

    @Autowired
    private RdDistrictSettledMapper rdDistrictSettledMapper;

    @Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;

    @Autowired
    private RdProjectpermissionService rdProjectpermissionService;

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

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


    @PostMapping(value = "/add")
    public Result add(RdDistrictSettled rdDistrictSettled,
                      HttpServletRequest request){
        return  rdDistrictSettledService.add(rdDistrictSettled,getAccessToken(request));
    }

    @PutMapping(value = "/edit")
    public Result edit(RdDistrictSettled rdDistrictSettled, HttpServletRequest request){
        return  rdDistrictSettledService.edit(rdDistrictSettled,getAccessToken(request));
    }

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

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

    //导出数据
    @RequestMapping(value = "/evaluationrdDistrictSettled", produces = "multipart/form-data",  method = RequestMethod.GET)
    public void evaluationrdDistrictSettled(RdDistrictSettledDTO rdDistrictSettledDTO, AccessToken accessToken, HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {


        // 获取登录人的角色授权
        Map<String, Object> rolesMap = rdProjectpermissionService.findRoleInfoMap(getAccessToken().getUserCode());

        List<String> organCodeString=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){
                //throw new ServiceException("项目进度_项目用户,无法使用此模块");
                rdDistrictSettledDTO.setCreateBy(getAccessToken().getUserCode());
                organCodeString=null;
                break;
            }
        }

        ExportExcelUtil<RdDistrictSettledVO> util = new ExportExcelUtil<RdDistrictSettledVO>();
        String[] columnNames = { "区域名称" ,"片区名称" ,"项目名称" ,"预计进驻时间" ,"项目位置" ,"预计规划面积","备注"};

       /* String[] idIntegers;
        int[] idArry = null;
        if (ids!=null&&!ids.equals("")) {
            idIntegers=ids.split(",");
            idArry = new int[idIntegers.length];
            for (int i = 0; i < idIntegers.length; i++) {
                idArry[i]=Integer.parseInt(idIntegers[i]);
            }
        }*/
           // List<Integer> perid= Ints.asList(idArry);
            Collection<RdDistrictSettledVO> list=rdDistrictSettledMapper.evaluationrdDistrictSettled(rdDistrictSettledDTO,organCodeString,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);
    }

}