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

import cn.com.countrygarden.bi.main.controller.BaseController;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dto.businessCenterSubmission.SumSheetDTO;
import cn.com.countrygarden.bi.main.model.AccessToken;
//import cn.com.countrygarden.bi.main.model.businessCenterSubmission.PageData;
import cn.com.countrygarden.bi.main.service.businessCenterSubmission.BusinessCenterSubmissionService;
import cn.com.countrygarden.bi.main.util.ExcelCommon;
import com.github.pagehelper.PageInfo;
import net.sf.ehcache.search.aggregator.Sum;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <pre>
 *
 * </pre>
 *
 * @author wxy
 * @version 1.00.00
 * <p>
 * <p>
 * <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容:
 * </pre>
 */
@RestController
@RequestMapping("/Submission")
public class BusinessCenterSubmissionController extends BaseController{
    @Autowired
    private BusinessCenterSubmissionService service;

    @GetMapping("/getOrganList")
    public Result getOrganList(){
        Result organList = service.getOrganList();
        return organList;
    }

    @GetMapping("/getCommListByOrganCode")
    public Result getCommListByOrganCode(String organCode){
        Result commListByOrganCode = service.getCommListByOrganCode(organCode);
        return commListByOrganCode;
    }

    @GetMapping("/getCommList")
    public Result getCommList(){
        Result commList = service.getCommList();
        return commList;
    }

    @GetMapping("/getUnfinishedCause")
    public Result getUnfinishedCause(){
        Result unfinishedCause = service.getUnfinishedCause();
        return unfinishedCause;
    }

    @PostMapping("/getSumSheetList")
    public Result getSumSheetList(String userCode,Integer pageNum, Integer pageSize, String id,String organCode, String commId, String branchName,
                                  String isPrd, String isDouble, String unfinishedCause, String isDoubleSixMonth, String startTime, String endTime){
        return service.getSumSheetList(userCode,pageNum, pageSize, id,organCode, commId, branchName, isPrd, isDouble, unfinishedCause, isDoubleSixMonth, startTime, endTime);

    }

    @PostMapping("/getUserRole")
    public Result getUserRole(String userCode){
        return service.getUserRole(userCode);
    }

    @PostMapping("/addSumSheet")
    public Result addSumSheet(SumSheetDTO dto){
        AccessToken accessToken = this.getAccessToken();
        Result result = service.addSumSheet(dto, accessToken.getUserCode());
        return result;
    }

    @PostMapping("/updateSumSheet")
    public Result updateSumSheet(SumSheetDTO dto){
        AccessToken accessToken = this.getAccessToken();
        Result result = service.updateSumSheet(dto, accessToken.getUserCode());
        return result;
    }

    @PostMapping("/deleteSumSheet")
    public Result deleteSumSheet(String id){
        AccessToken accessToken = this.getAccessToken();
        Result result = service.deleteSumSheet(id, accessToken.getUserCode());
        return result;
    }

    @RequestMapping("exportExcel")
    public Result exportExcel(HttpServletResponse response,String userCode,Integer pageNum, Integer pageSize, String id,String organCode, String commId, String branchName,
                              String isPrd, String isDouble, String unfinishedCause, String isDoubleSixMonth,
                              String startTime, String endTime){

        try {

            String path = this.getClass().getClassLoader().getResource("/").toURI().getPath() + "/excel/公共资源经营收入分配意见征询汇总表.xlsx";
            File fi = new File(path);
            InputStream in = new FileInputStream(fi);
            XSSFWorkbook wb = new XSSFWorkbook(in);
            // 读取了模板内所有sheet内容
            XSSFSheet sheet = wb.getSheetAt(0);
//            PageData pageData = service.getSumSheetList(pageNum, pageSize, organCode, commId, branchName, isPrd, isDouble, unfinishedCause, isDoubleSixMonth, startTime, endTime);
            Result result = service.getSumSheetList(userCode,pageNum, pageSize, id, organCode, commId, branchName, isPrd, isDouble, unfinishedCause, isDoubleSixMonth, startTime, endTime);
            PageInfo<SumSheetDTO> info =(PageInfo<SumSheetDTO>) result.getData();
            List<SumSheetDTO> list = info.getList();
            Result cause = service.getUnfinishedCause();
            List<Map<String, String>> causeData = (List<Map<String, String>>)cause.getData();
            if (list.isEmpty()){
                ExcelCommon.downloadExcel(wb, "公共资源意见征询上报汇总表", response);
            }else{
                List<ArrayList<Object>> data = new ArrayList<>(list.size());
                for (SumSheetDTO dto : list) {
                    ArrayList<Object> rowData = new ArrayList<>();
                    rowData.add(dto.getOrganName());
                    rowData.add(dto.getCommName());
                    rowData.add(dto.getBranchName());
                    rowData.add(getYesOrNo(dto.getIsPrd()));
                    rowData.add(getYesOrNo(dto.getIsDouble()));

//                    rowData.add(dto.getUnfinishedCause() == null?"":dto.getUnfinishedCause());
//                    rowData.add(dto.getUnfinishedCauseText());
                    String text = "";
                    if(dto.getUnfinishedCause() != null){
                        for (Map<String, String> map : causeData) {
                            String id1 = String.valueOf(map.get("id"));
                            String unfinishedCause1 = dto.getUnfinishedCause();
                            if(id1.equals(unfinishedCause1)){
                                text = map.get("causeName");
                            }
                        }
                    }
                    rowData.add(text);
                    rowData.add(getYesOrNo(dto.getIsDoubleSixMonth()));
                    rowData.add(dto.getIsDoubleSixMonthFlaseCause());
                    rowData.add(dto.getAskForNumAgree2015());
                    rowData.add(dto.getAskForNumDisagree2015());
                    rowData.add(dto.getAskForNumAgree2016());
                    rowData.add(dto.getAskForNumDisagree2016());
                    rowData.add(dto.getAskForNumAgree2017());
                    rowData.add(dto.getAskForNumDisagree2017());
                    rowData.add(dto.getAskForNumAgree2018());
                    rowData.add(dto.getAskForNumDisagree2018());
                    rowData.add(dto.getAskForNumAgree2019());
                    rowData.add(dto.getAskForNumDisagree2019());
                    rowData.add(dto.getAskForNumAgree2020());
                    rowData.add(dto.getAskForNumDisagree2020());
                    rowData.add(dto.getAskForNumAgree2021());
                    rowData.add(dto.getAskForNumDisagree2021());
                    rowData.add(dto.getAskForNumAgree2022());
                    rowData.add(dto.getAskForNumDisagree2022());
                    rowData.add(dto.getAskDateCase());
                    rowData.add(dto.getFinishDoubleDate());
                    rowData.add(dto.getRemark());
                    data.add(rowData);
                }
                getSheet(sheet,data);
                ExcelCommon.downloadExcel(wb,"公共资源意见征询上报汇总表", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result();
    }

    /**
     * 处理工作页
     * @param sheet
     * @param data
     */
    private void getSheet(XSSFSheet sheet,List<ArrayList<Object>> data){
        int a = 4;
        for (int i = 0; i < data.size(); i++) {
            Row row = sheet.createRow(a+i);
            for (int j = 0; j < data.get(i).size(); j++) {
                Cell cell = row.createCell(j);
                Object value = data.get(i).get(j);
                cell.setCellValue(value == null ? "":value.toString());
            }
        }
    }

    /**
     * 转换1/0为是/否
     * @param str
     * @return
     */
    private String getYesOrNo(String str){
        if (str!=null) {
            if (str.equals("0")) {
                str = "否";
            } else if (str.equals("1")) {
                str = "是";
            }
        }else{
            str = "";
        }
        return str;
    }
}
