package com.cftech.questionnaire.core.paper.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.core.poi.ExcelKit;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.questionnaire.core.paper.model.*;
import com.cftech.questionnaire.core.paper.service.PaperLogService;
import com.cftech.questionnaire.core.paper.service.PaperService;
import com.cftech.sys.security.UserUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 问卷记录Controller
 *
 * 权限字符串说明:
 * 查看:public static final String PAPER_VIEW = "qy:paper:view"
 * 查看:public static final String PAPER_EDIT = "qy:paper:edit"
 *
 * @author wxf
 * @date: 2017-05-25 10:27
 */
@Slf4j
@Controller
@RequestMapping("/a/paperlog")
public class PaperLogController {

    public static final String PAPER_VIEW = "qy:paper:view";
    public static final String PAPER_EDIT = "qy:paper:edit";

    @Autowired
    private PaperLogService paperService;

    @Autowired
    private PaperService paperService1;




    //列表页面
    @RequiresPermissions(value = PAPER_VIEW)
    @RequestMapping(value = "/list",method = {RequestMethod.POST,RequestMethod.GET})
    public String list(HttpServletRequest request, Model model,String paper_id) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        model.addAttribute("paper_id",paper_id);
        return "paper/paperloglist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = PAPER_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.POST,RequestMethod.GET})
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            PaperLog paper = paperService.fetchById(id);
            model.addAttribute("data", paper);
        }
        return "paper/paperlogform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = PAPER_EDIT)
    @RequestMapping(value = "/formData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject formData(PaperLog paper, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (paper != null && paper.getId() != null) {
                paper.setUpdateBy(UserUtils.getUser().getId());
                paperService.update(paper);
                rtnJson.put("errorNo", 0);
            } else {
                paper.setAccountsId(accountsId);
                paper.setDelFlag(false);
                paper.setAccountsId(UserUtils.getmpaccounts(request));
                paper.setCreateBy(UserUtils.getUser().getId());
                paper.setUpdateBy(UserUtils.getUser().getId());
                paperService.save(paper);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = PAPER_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, PaperLogDto paper, HttpServletRequest request , String paper_id) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("p.del_flag", Constants.DEL_FLAG_0);
       // conds.equal("accounts_id", accountsId);
        Sort sort = new Sort("pl.create_time", OrderType.DESC);
        if(!UserUtils.isAdmin()){
            conds.equal("p.create_by", UserUtils.getUser().getId());
        }
        if(!StringUtils.isEmpty(paper.getSurMemberName())){
            conds.like("m.surname",paper.getSurMemberName());
        }
        if(!StringUtils.isEmpty(paper.getMemberName())){
            conds.like("m.name",paper.getMemberName());
        }
        if(!StringUtils.isEmpty(paper.getPaperTitle())){
            conds.like("p.paper_title",paper.getPaperTitle());
        }
        if(!StringUtils.isEmpty(paper.getSubjectName())){
            conds.like("s.subject_name",paper.getSubjectName());
        }
        if(!StringUtils.isEmpty(paper_id)){
            conds.equal("p.id",paper_id);
        }
        List<PaperLogDto> list = paperService.fetchPaperLogList(conds, iDisplayStart, iDisplayLength,sort);
        Integer counts = paperService.fetchPaperLogListCount(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }


    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = PAPER_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, PaperLogDto paper) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("p.del_flag", Constants.DEL_FLAG_0);
        // conds.equal("accounts_id", accountsId);
        Sort sort = new Sort("pl.create_time", OrderType.DESC);
        if(!UserUtils.isAdmin()){
            conds.equal("p.create_by", UserUtils.getUser().getId());
        }
        if(!StringUtils.isEmpty(paper.getSurMemberName())){
            conds.like("m.surname",paper.getSurMemberName());
        }
        if(!StringUtils.isEmpty(paper.getMemberName())){
            conds.like("m.name",paper.getMemberName());
        }
        if(!StringUtils.isEmpty(paper.getPaperTitle())){
            conds.like("p.paper_title",paper.getPaperTitle());
        }
        if(!StringUtils.isEmpty(paper.getSubjectName())){
            conds.like("s.subject_name",paper.getSubjectName());
        }
        List<PaperLogDto> list = paperService.fetchPaperLogList(conds, 0, 0,sort);
        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(PaperLogDto.class, response).toExcel(list, "问卷记录信息");
    }

    //删除数据
    @RequiresPermissions(value = PAPER_EDIT)
    @RequestMapping(value = "/delete",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            paperService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

    //列表页面
    @RequiresPermissions(value = PAPER_VIEW)
    @RequestMapping(value = "/listpaperanswer",method = {RequestMethod.POST,RequestMethod.GET})
    public String listpaperanswer(Model model,Long paper_id) {
        if(!StringUtils.isEmpty(paper_id)){
            Conds conds1 = new Conds();
            conds1.equal("id",paper_id);
            conds1.equal("del_flag",0);
            PaperBaseEntity paperBaseEntity =  paperService1.fetchSearchByConds(conds1);
            if(paperBaseEntity!= null){
                model.addAttribute("title",paperBaseEntity.getPaperTitle());
            }
            Conds conds = new Conds();
            conds.equal("po.del_flag",0);
            conds.equal("po.paper_id",paper_id);
            List<PaperAnswer> list = paperService.searchpaperanswer(conds,paper_id);
            JSONArray jsonArray = new JSONArray();
            if(list!=null&&list.size()>0){
                for(int i = 0 ; i<list.size();i++){
                    jsonArray.add(list.get(i));
                }
            }
                model.addAttribute("list",jsonArray);
                model.addAttribute("papperId",paper_id);
            }
        return "paper/paperanswerlist";
    }

    @RequestMapping(value = "/exportpaperanswer")
    @RequiresPermissions(value = PAPER_VIEW)
    public void exportpaperanswer(HttpServletResponse rs,Long paperId){
        if(!StringUtils.isEmpty(paperId)){
            //查询某问卷
            Conds conds1 = new Conds();
            conds1.equal("id",paperId);
            conds1.equal("del_flag",0);
            PaperBaseEntity paperBaseEntity =  paperService1.fetchSearchByConds(conds1);

            //查询某问卷下面的所有的题目
            String title = paperBaseEntity.getPaperTitle();
            Conds conds = new Conds();
            conds.equal("paper_id",paperId);
            conds.equal("del_flag",0);
            List<PaperSubject> paperSubjects = paperService1.selectPaperSubject(conds);
            if(paperSubjects!=null && paperSubjects.size()>0){
                HSSFWorkbook wb = new HSSFWorkbook();
                HSSFSheet sheet = wb.createSheet(title);  //创建table工作薄
                HSSFRow row = sheet.createRow(0);//创建一行
                /**
                 * 居中样式
                 */
                HSSFCellStyle style = wb.createCellStyle();
                style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
                HSSFCellStyle styleLeft = wb.createCellStyle();
                styleLeft.setAlignment(HorizontalAlignment.CENTER); // 创建一个居左格式

                int rowCount = 0;
                HSSFCell cell = row.createCell(rowCount);
                cell.setCellStyle(style);
                cell.setCellValue(title);
                //合并单元格
                CellRangeAddress callRangeAddress = new CellRangeAddress(rowCount,rowCount,0,5);//起始行,结束行,起始列,结束列
                sheet.addMergedRegion(callRangeAddress);
                rowCount++;
                for(int i =0;i<paperSubjects.size();i++){
                    Long subjectId =paperSubjects.get(i).getId();
                    Conds optionsConds = new Conds();
                    optionsConds.equal("po.del_flag",0);
                    optionsConds.equal("po.paper_id",paperId);
                    optionsConds.equal("po.subject_id",subjectId);
                    List<PaperAnswer> list = paperService.searchpaperanswer(optionsConds,paperId);
                    if(list!=null && list.size()>0){
                        //填充题目单元格
                        String subjectName = paperSubjects.get(i).getSubjectName();
                        HSSFRow rowSubject = sheet.createRow(rowCount);//创建一行
                        HSSFCell cellSubject = rowSubject.createCell(0);
                        cellSubject.setCellStyle(styleLeft);
                        cellSubject.setCellValue((i+1)+"."+subjectName);
                        CellRangeAddress callRangeAddressSubject = new CellRangeAddress(rowCount,rowCount,0,5);//起始行,结束行,起始列,结束列
                        sheet.addMergedRegion(callRangeAddressSubject);
                        rowCount++;
                        HSSFRow rowOptionTitle = sheet.createRow(rowCount);//创建一行
                        CellRangeAddress callRangeAddressX = new CellRangeAddress(rowCount,rowCount,0,1);//起始行,结束行,起始列,结束列
                        sheet.addMergedRegion(callRangeAddressX);
                        CellRangeAddress callRangeAddressR = new CellRangeAddress(rowCount,rowCount,2,3);//起始行,结束行,起始列,结束列
                        sheet.addMergedRegion(callRangeAddressR);
                        CellRangeAddress callRangeAddressB = new CellRangeAddress(rowCount,rowCount,4,5);//起始行,结束行,起始列,结束列
                        sheet.addMergedRegion(callRangeAddressB);
                        HSSFCell cellTitleX = rowOptionTitle.createCell(0);
                        cellTitleX.setCellStyle(style);
                        cellTitleX.setCellValue("选项");
                        HSSFCell cellTitleR = rowOptionTitle.createCell(2);
                        cellTitleR.setCellStyle(style);
                        cellTitleR.setCellValue("选择人数");
                        HSSFCell cellTitleB = rowOptionTitle.createCell(4);
                        cellTitleB.setCellStyle(style);
                        cellTitleB.setCellValue("百分比(%)");
                        rowCount++;
                        for(PaperAnswer paperAnswer1 : list){
                            HSSFRow rowOptionOTitle = sheet.createRow(rowCount);//创建一行
                            CellRangeAddress callRangeAddressOX = new CellRangeAddress(rowCount,rowCount,0,1);//起始行,结束行,起始列,结束列
                            sheet.addMergedRegion(callRangeAddressOX);
                            CellRangeAddress callRangeAddressOR = new CellRangeAddress(rowCount,rowCount,2,3);//起始行,结束行,起始列,结束列
                            sheet.addMergedRegion(callRangeAddressOR);
                            CellRangeAddress callRangeAddressOB = new CellRangeAddress(rowCount,rowCount,4,5);//起始行,结束行,起始列,结束列
                            sheet.addMergedRegion(callRangeAddressOB);
                            HSSFCell cellTitleOX = rowOptionOTitle.createCell(0);
                            cellTitleOX.setCellStyle(style);
                            cellTitleOX.setCellValue(paperAnswer1.getOption_name());
                            HSSFCell cellTitleOR = rowOptionOTitle.createCell(2);
                            cellTitleOR.setCellStyle(style);
                            cellTitleOR.setCellValue(paperAnswer1.getCounts());
                            HSSFCell cellTitleOB = rowOptionOTitle.createCell(4);
                            cellTitleOB.setCellStyle(style);
                            cellTitleOB.setCellValue(paperAnswer1.getPercentage());
                            rowCount++;
                        }

                    }
                }
                try {
                    String prefix = "xls";
                    rs.reset();
                    rs.setContentType("multipart/form-data"); //自动识别
                    rs.setHeader("Content-Type","application/octet-stream");
                    rs.setHeader("Content-Disposition","attachment;filename="+new String(title.getBytes("gb2312"), "ISO8859-1" )+"."+prefix);
                    //文件流输出到rs里
                    wb.write(rs.getOutputStream());
                    rs.getOutputStream().flush();
                    rs.getOutputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
