package com.yonyou.hrcloud.pm.ps.impl;

import com.yonyou.hrcloud.pm.base.model.GradeItem;
import com.yonyou.hrcloud.pm.ps.dao.IExclQueryDao;
import com.yonyou.hrcloud.pm.ps.model.Scheme;
import com.yonyou.hrcloud.pm.ps.model.Sheet;
import com.yonyou.hrcloud.pm.ps.service.IExclQueryService;
import com.yonyou.hrcloud.pm.result.model.Score;

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @Author ZengCL
 * @create 2020/12/9 11:54
 */
@Service
public class ExceQueryImpl implements IExclQueryService {

    @Resource
    public IExclQueryDao iExclQueryDao;
    @Override
    public  List<GradeItem> getGradeByID(String gradeid){
        return iExclQueryDao.getGradeByID(gradeid);
    }

    /**
     * @param request
     * @param response
     * @param datalist
     * @param schemename
     * @return void
     * @author zengcl
     * @description 根据该方案id导出模板
     * @date 2020/12/09
     **/
    @Override
    public void exportTemplateByScheme2Excel(HttpServletRequest request, HttpServletResponse response, List<Map<String, String>> datalist, String schemename, List<GradeItem> gradeItems) {
        String filename = schemename;
        //创建工作簿 /新建工作表
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet(schemename);
        //创建表头
        XSSFRow titlerow = sheet.createRow(0);
        String[] titlesArray = new String[]{"序号","人员编码","姓名","任职组织","部门","考核得分","考核等级"};
        for(int col = 0 ; col < titlesArray.length ; col++ ){
            String title = titlesArray[col];
            XSSFCell cell = titlerow.createCell(col);
            cell.setCellValue(title);

        }

        //设置下拉
        //运输方式
        String[] textList1 = new String[gradeItems.size()];
        GradeItem[] textList2=gradeItems.toArray(new GradeItem[gradeItems.size()]);
        for(int str=0;str<textList2.length;str++){
            textList1[str]=textList2[str].getGradeitemname();
        }

        XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
        XSSFDataValidationConstraint dvConstraint1 = (XSSFDataValidationConstraint) dvHelper
                .createExplicitListConstraint(textList1);
        //下拉列表
        CellRangeAddressList addressList1 = null;
        XSSFDataValidation dataValidation1 = null;
        addressList1 = new CellRangeAddressList(1,65536,6,6);
        dataValidation1 = (XSSFDataValidation) dvHelper.createValidation(
                dvConstraint1, addressList1);
        sheet.addValidationData(dataValidation1);
        //创建数据

        for(int row = 1; row <= datalist.size() ; row ++ ){
            XSSFRow xssfRow = sheet.createRow(row);
            Map<String, String> rowmap = datalist.get(row-1);
            xssfRow.createCell(0).setCellValue(row);
            xssfRow.createCell(1).setCellValue(rowmap.get("staffcode"));
            xssfRow.createCell(2).setCellValue(rowmap.get("staffname"));
            xssfRow.createCell(3).setCellValue(rowmap.get("orgname"));
            xssfRow.createCell(4).setCellValue(rowmap.get("deptname"));
            xssfRow.createCell(5).setCellValue(rowmap.get("numvalue"));
            xssfRow.createCell(6).setCellValue(rowmap.get("text"));
        }

        //创建输出流
        try {
            String agent = request.getHeader("User-Agent").toUpperCase(); //获得浏览器信息并转换为大写
            if (agent.indexOf("MSIE") > 0 || (agent.indexOf("GECKO")>0 && agent.indexOf("RV:11")>0) || agent.indexOf("EDGE") > 0) {  //IE浏览器和Edge浏览器
                filename = URLEncoder.encode(filename, "UTF-8");
            } else{
                filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.reset();
            response.setHeader("Content-disposition", "attachment;filename= " + filename+".xlsx");
            response.setContentType("multipart/form-data");
            response.setContentType("application/octet-stream");
            response.setContentType("application/x-download");// 设置为下载application/x-download
            response.setContentType("charset=UTF-8");// response.setContentType("text/html; charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Cache-Control", "no-store");
            response.setDateHeader("Expires", 0);
            response.setHeader("Pragma", "no-cache");
            response.setCharacterEncoding("UTF-8");//(request.getCharacterEncoding());

            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } /*finally {
			try {
				workbook.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}*/

    }

    @Override
    public  GradeItem getGradeInfoByName(String gradename,String gradeid){
        GradeItem item=iExclQueryDao.getGradeInfoByName(gradename,gradeid);
        return item!=null?item:null;

    }


    @Override
    public String getPsnBycode(String code){
        return iExclQueryDao.getPsnBycode(code);
    }

//    @Override
//    public void udateGrade(Score score) {
//        BigDecimal numvalue =score.getNumvalue().setScale(2);
//        String text =score.getText();
//        String schemeid =score.getSchemeid();
//        String staffid =score.getStaffid();
//        iExclQueryDao.udateGrade(numvalue,text,schemeid,staffid);
//    }

    @Override
    public Boolean checkExistScore(String schemeid, String psncode,String numcode) {
        Score score=iExclQueryDao.queryScoreInfo(schemeid,psncode,numcode);
        return score!=null?true:false;
    }

    @Override
    public Sheet querySheetID(String schemeid, String psncode) {
        Sheet sheet=iExclQueryDao.querySheetID(schemeid,psncode);
        return sheet!=null? sheet:null;
    }

	@Override
	public Scheme querySchemeBySheetID(String schemeid) {
		// TODO Auto-generated method stub
		return iExclQueryDao.querySchemeBySheetID(schemeid);
	}

	@Override
	public void updateScore(Score score) {
		// TODO Auto-generated method stub
		iExclQueryDao.updateScore(score.getSchemeid(),score.getSheetid(),score.getColumncode(),
				score.getStaffid(),score.getNumvalue(),score.getText());
	}


}
