package cn.com.countrygarden.bi.main.controller.reportCityData;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dto.reportCityData.CcdrDto;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.reportCityData.CityCompanyDataService;
import cn.com.countrygarden.bi.main.util.DateUtil;
import cn.com.countrygarden.bi.main.util.ExcelCompanyDataUtil;
import cn.com.countrygarden.bi.main.util.ExtensionReportUtils;
import cn.com.countrygarden.bi.main.util.OSSUtils;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cityCompanyDataMrg")
public class CityCompanyDataController {

    @Autowired
    CityCompanyDataService cityCompanyDataService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private OSSUtils ossUtils;

    /**
     * 获取城市公司数据列表
     *
     * @param ccdrDto
     * @return
     * @author Song.xy
     * @authDate 2019/01/16
     */
    @RequestMapping(value = "/cityCompanyDataList", produces = "application/json;charset=utf-8")
    public Object cityCompanyDataList(CcdrDto ccdrDto) {
        try {
            return Response.response(cityCompanyDataService.queryData(ccdrDto));
        } catch (Exception e) {
            e.printStackTrace();
            Result result = new Result();
            result.setCode(500);
            result.setMessage(e.getMessage());
            return result;
        }
    }

    //根据ID获取单条数据
    @RequestMapping(value = "/getCityCompanyData", produces = "application/json;charset=utf-8")
    public Result getCityCompanyData(@RequestParam(value = "ccdrId", required = false, defaultValue = "") Integer ccdrId) {
        try {
            Result data = cityCompanyDataService.getData(ccdrId);
            return cityCompanyDataService.getData(ccdrId);
        } catch (Exception e) {
            e.printStackTrace();
            Result result = new Result();
            result.setCode(500);
            result.setMessage(e.getMessage());
            return result;
        }
    }


    /**
     * 修改城市公司上报数据
     * @param ccdrDto
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateCityCompanyData", produces = "application/json;charset=utf-8")
    public Result updateCityCompanyData(@RequestBody CcdrDto ccdrDto, HttpServletRequest request) {
        Result result = new Result();
        try {
            String accessToken = request.getParameter("AccessToken");
            AccessToken token = null;
            if (accessToken != null) {
                token = accessTokenService.findByToken(accessToken);
                if (token == null) {
                    result.setResultCode(500);
                    result.setResultMsg("登录失效！");
                } else {
                    return cityCompanyDataService.updateData(ccdrDto, token);
                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setResultCode(500);
            result.setResultMsg(e.getMessage());
            return result;
        }
    }

    /**
     * 新增数据
     * @param ccdrDto
     * @return
     */
    @RequestMapping(value = "/addCityCompanyData", produces = "application/json;charset=utf-8")
    public Result addCityCompanyData(@RequestBody CcdrDto ccdrDto, HttpServletRequest request) {
        Result result = new Result();
        try {
            String accessToken = request.getParameter("AccessToken");
            AccessToken token = null;
            if (accessToken != null){
                token = accessTokenService.findByToken(accessToken);
                if(token==null){
                    result.setResultCode(500);
                    result.setResultMsg("登录失效！");
                }else{
                    return cityCompanyDataService.addData(ccdrDto,token);
                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            return result.setResultCode(500);
        }
    }

    /**
     * 删除城市上报数据
     * @param ccdrId
     * @return
     */
    @RequestMapping(value = "/deleteCityCompanyData", produces = "application/json;charset=utf-8")
    public Result deleteCityCompanyData(@RequestParam(value = "ccdrId", required = false, defaultValue = "") Integer ccdrId) {
        try {
            return cityCompanyDataService.deleteData(ccdrId);
        } catch (Exception e) {
            e.printStackTrace();
            Result result = new Result();
            result.setCode(500);
            result.setMessage(e.getMessage());
            return result;
        }
    }

    //删除子对象接口
    @RequestMapping(value = "/deleteChildObject", produces = "application/json;charset=utf-8")
    public Result deleteChildObject(@RequestParam(value = "ccsrId", required = false, defaultValue = "") Long ccsrId
            , @RequestParam(value = "ccsjId", required = false, defaultValue = "") Long ccsjId
            , @RequestParam(value = "cclId", required = false, defaultValue = "") Long cclId
            , @RequestParam(value = "fileId", required = false, defaultValue = "") Long fileId){
        Result result = new Result();
        if(ccsrId != null){
            try {
                return cityCompanyDataService.deleteCcsr(ccsrId);
            } catch (Exception e) {
                e.printStackTrace();
                result.setResultCode(500);
                result.setResultMsg(e.getMessage());
                return result;
            }
        }
        if(ccsjId != null){
            try {
                return cityCompanyDataService.deleteCcsj(ccsjId);
            } catch (Exception e) {
                e.printStackTrace();
                result.setResultCode(500);
                result.setResultMsg(e.getMessage());
                return result;
            }
        }
        if(cclId != null){
            try {
                return cityCompanyDataService.deleteCcl(cclId);
            } catch (Exception e) {
                e.printStackTrace();
                result.setResultCode(500);
                result.setResultMsg(e.getMessage());
                return result;
            }
        }
        if(fileId != null){
            try {
                return cityCompanyDataService.deleteCcuf(fileId);
            } catch (Exception e) {
                e.printStackTrace();
                result.setResultCode(500);
                result.setResultMsg(e.getMessage());
                return result;
            }
        }
        result.setResultCode(500);
        result.setResultMsg("未获取到删除对象ID！");
        return result;
    }

    /**
     * 城市公司数据上报导出
     * @param response
     * @param ccdrDto
     * @return
     */
    @RequestMapping(value = "/exportExcelForCompanyData")
    public Result exportExcelForCompanyData(HttpServletResponse response, CcdrDto ccdrDto) {
        try {
            // 获取城市上报数据列表
            List<CcdrDto> list = cityCompanyDataService.getDataList(ccdrDto);
            Map<String,Integer> sizeMap = cityCompanyDataService.getTheMaxSize(list);
            List<ArrayList<Object>> data = new ArrayList<>(list.size());

            if (!list.isEmpty()){
                list.forEach(s->{
                    ArrayList<Object> rowData = new ArrayList<>();

                    //城市公司名称
                    rowData.add(s.getCityCompanyName());
                    //城市公司编
                    rowData.add(s.getCityCompanyCode());
                    //省级行政区域
                    rowData.add(s.getProvince());
                    //市级行政区域
                    rowData.add(s.getCity());
                    //区级行政区域
                    rowData.add(s.getBorough());
                    //乡级行政区域
                    rowData.add(s.getRegion());
                    //营业执照的物业公司全称
                    rowData.add(s.getPropertyName());
                    //NC 账套全称
                    rowData.add(s.getNcSystemAccount());
                    //NC 账套编码
                    rowData.add(s.getNcSystemNumber());
                    //NC 人力组织编码
                    rowData.add(s.getNcPersonNumber());
                    //接管时间
                    rowData.add(s.getManageTime());
                    //接管时项目数量
                    rowData.add(s.getManageProjectNumber());
                    //接管时在管项目总建筑面积
                    rowData.add(s.getManageProjectArea());

                    //股东占比情况
                     for(int i=0;i<sizeMap.get("theMaxSizeCcsr");i++){
                        if( s.getCcsrDtoList()!=null && s.getCcsrDtoList().size()>0 && s.getCcsrDtoList().size()>i){
                            //股东名称
                            rowData.add(s.getCcsrDtoList().get(i).getShareholderName());
                            //股东占比
                            rowData.add(s.getCcsrDtoList().get(i).getShareholderRatio());
                        }else{
                            rowData.add("");
                            rowData.add("");
                        }
                     }

                    //股东方对接人信息
                    for(int i=0;i<sizeMap.get("theMaxSizeCcsj");i++){
                        if( s.getCcsjDtoList()!=null && s.getCcsjDtoList().size()>0 && s.getCcsjDtoList().size()>i){
                            //股东对接人姓名
                            rowData.add(s.getCcsjDtoList().get(i).getJointName());
                            //股东对接人联系方式
                            rowData.add(s.getCcsjDtoList().get(i).getJointTel());
                        }else{
                            rowData.add("");
                            rowData.add("");
                        }
                    }

                    //对赌基数可收费面积（㎡）
                    rowData.add(s.getValuationChargeArea());
                    //对赌基数 扣除非经常性损益净利润（元）
                    rowData.add(s.getValuationNetProfit());
                    //对赌基数 营业收入（元）
                    rowData.add(s.getValuationSalesRevenue());
                    //对赌基数 其他
                    rowData.add(s.getValuationOther());
                    //投决会经营指标第一年 可收费管理面积（㎡）
                    rowData.add(s.getFirstChargeArea());
                    //投决会经营指标第一年 扣除非经常性损益净利润（元）
                    rowData.add(s.getFirstNetPofit());
                    //投决会经营指标第一年 营业收入（元）
                    rowData.add(s.getFirstSalesRevenue());
                    //投决会经营指标第一年 其他
                    rowData.add(s.getFirstOther());
                    //投决会经营指标第二年 可收费管理面积（㎡）
                    rowData.add(s.getSecondChargeArea());
                    //投决会经营指标第二年 扣除非经常性损益净利润（元）
                    rowData.add(s.getSecondNetPofit());
                    //投决会经营指标第二年 营业收入（元）
                    rowData.add(s.getSecondSalesRevenue());
                    //投决会经营指标第二年 其他
                    rowData.add(s.getSecondOther());
                    //投决会经营指标第三年 可收费管理面积（㎡）
                    rowData.add(s.getThirdlyChargeArea());
                    //投决会经营指标第三年 扣除非经常性损益净利润（元）
                    rowData.add(s.getThirdlyNetPofit());
                    //投决会经营指标第三年 营业收入（元）
                    rowData.add(s.getThirdlySalesRevenue());
                    //投决会经营指标第三年 其他
                    rowData.add(s.getThirdlyOther());
                    //投决会经营指标第四年 可收费管理面积（㎡）
                    rowData.add(s.getFourthlyChargeArea());
                    //投决会经营指标第四年 扣除非经常性损益净利润（元）
                    rowData.add(s.getFourthlyNetPofit());
                    //投决会经营指标第四年 营业收入（元）
                    rowData.add(s.getFourthlySalesRevenue());
                    //投决会经营指标第四年 其他
                    rowData.add(s.getFourthlyOther());
                    //投决会经营指标第五年 可收费管理面积（㎡）
                    rowData.add(s.getFifthChargeArea());
                    //投决会经营指标第五年 扣除非经常性损益净利润（元）
                    rowData.add(s.getFifthNetPofit());
                    //投决会经营指标第五年 营业收入（元）
                    rowData.add(s.getFifthSalesRevenue());
                    //投决会经营指标第五年 其他
                    rowData.add(s.getFifthOther());

                    //对赌条款约定1
                    rowData.add(s.getValuationAdjustmentMechanismFirst());
                    //对赌条款约定2
                    rowData.add(s.getValuationAdjustmentMechanismSecond());
                    //对赌条款约定3
                    rowData.add(s.getValuationAdjustmentMechanismThirdly());

                    //城市公司负责人信息
                    for(int i=0;i<sizeMap.get("theMaxSizeCcl");i++){
                        if( s.getCclDtoList()!=null && s.getCclDtoList().size()>0 && s.getCclDtoList().size()>i){
                            //城市负责人姓名
                            rowData.add(s.getCclDtoList().get(i).getLeaderName());
                            //城市负责人联系电话
                            rowData.add(s.getCclDtoList().get(i).getLeaderTel());
                        }else{
                            rowData.add("");
                            rowData.add("");
                        }
                    }

                    data.add(rowData);
                });
            }
            ExcelCompanyDataUtil.exportCompanyData(DateUtil.dateToStrOfFormat(new Date(),"yyyy/MM/dd")+"城市上报数据","sheet1",
                   data,sizeMap,response);
            return new Result();
        } catch (Exception e) {
            e.printStackTrace();
            Result result = new Result();
            result.setCode(500);
            result.setResultMsg(e.getMessage());
            return result;
        }
    }

    /**
     * 模板下载
     * @param response
     * @return
     */
    @RequestMapping(value = "/downLoadtExcelForCompanyData")
    public Result downLoadExcelForCompanyData(HttpServletResponse response) {
        try {
            // 获取城市上报数据列表
            Map<String,Integer> sizeMap = Maps.newHashMap();
            sizeMap.put("theMaxSizeCcsr",1);
            sizeMap.put("theMaxSizeCcsj",1);
            sizeMap.put("theMaxSizeCcl",1);
            List<ArrayList<Object>> data = new ArrayList<>(46);
            ExcelCompanyDataUtil.exportCompanyData("城市公司数据上报模板","sheet1",
                    data,sizeMap,response);
            return new Result();
        } catch (Exception e) {
            e.printStackTrace();
            Result result = new Result();
            result.setCode(500);
            result.setResultMsg(e.getMessage());
            return result;
        }
    }

    @PostMapping(value = "/upload", produces = "application/json;charset=utf-8")
    public Object uploadFile(@RequestParam(value = "uploadfile", defaultValue = "", required = true) MultipartFile multipartFile){

        try {
            if (multipartFile == null || multipartFile.isEmpty()){
                return Response.responseFail("请选择需要上传的文件");
            }
            return Response.response(ExtensionReportUtils.uploadFile(multipartFile, ossUtils));
        }catch (Exception e){
            e.printStackTrace();
            return Response.responseFail(e.getMessage());
        }
    }

    /**
     * 导入
     * @param excelFile
     * @return
     */
    @RequestMapping(value = "/importCompanyData", method = RequestMethod.POST)
    public Result importCompanyData(MultipartFile excelFile, @RequestParam String AccessToken, HttpServletRequest request) {
        Result result = new Result();
        try {
            String accessToken = request.getParameter("AccessToken");
            cn.com.countrygarden.bi.main.model.AccessToken token = null;
            if (accessToken != null){
                token = accessTokenService.findByToken(accessToken);
                if(token==null){
                    result.setResultCode(500);
                    result.setResultMsg("登录失效！");
                }
            }
            Map<String, Object> resultMap = cityCompanyDataService.importExcelForCompanyData(excelFile,token);
            result.setResultMsg((String) resultMap.get("returnMsg"));
            result.setResultCode((Integer) resultMap.get("returnCode"));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setResultMsg(e.getMessage());
            return result.setResultCode(500);
        }
    }
}
