package com.cftech.workshop.statistics.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.cms.exhibi_inquiries.model.Exhibi_inquiries;
import com.cftech.cms.exhibi_inquiries.model.Exhibi_inquiriesDto;
import com.cftech.workshop.meeting.model.Meeting;
import com.cftech.workshop.meeting.service.MeetingService;
import com.cftech.workshop.sample.model.Sample;
import com.cftech.workshop.sample.model.SampleClick;
import com.cftech.workshop.sample.service.SampleService;
import com.cftech.workshop.statistics.model.*;
import com.cftech.workshop.statistics.service.StatisticsService;
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.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import com.cftech.workshop.workshop.model.Workshop;
import com.cftech.workshop.workshop.service.WorkshopService;
import lombok.extern.slf4j.Slf4j;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

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


/**
 * Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String STATISTICS_VIEW = "qy:statistics:view"
 * 查看:public static final String STATISTICS_EDIT = "qy:statistics:edit"
 *
 * @author byj
 * @date: 2018-07-13 13:23
 */
@Slf4j
@Controller
@RequestMapping("/a/statistics")
public class StatisticsController {

    public static final String STATISTICS_VIEW = "qy:statistics:view";
    public static final String STATISTICS_EDIT = "qy:statistics:edit";

    @Autowired
    private StatisticsService statisticsService;
    @Autowired
    private CodingruleUtils codingruleUtils;
    @Autowired
    private SampleService sampleService; //样本
    @Autowired
    private WorkshopService workshopService; //预导入名

    @Autowired
    private MeetingService meetingService;


    //列表页面
    @RequiresPermissions(value = STATISTICS_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "statistics/statisticslist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = STATISTICS_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model , String meetingId,String type) {
        model.addAttribute("meetingId",meetingId);
        String result = null;
        if(type.equals("0")){
            if(!StringUtils.isEmpty(meetingId)){

                Meeting meeting = meetingService.fetchById(meetingId);

                //查出某个研讨会下面的预导入名单
                Conds condsws = new Conds();

                condsws.equal("wsid",meetingId);
                condsws.equal("del_flag",0);
                condsws.equal("status",2);
                //Sort sortws = new Sort("create_time",OrderType.DESC);
                //某研讨会预导入名单总人数
               // int sumws = workshopService.count(condsws);
                //按行业分类
                Sort sort = new Sort("counts",OrderType.DESC);
                List<WorkshopType> listwstype = statisticsService.selecttypeworkshop(condsws,sort,0,0);
                JSONArray pieValue = new JSONArray();
                JSONArray barType = new JSONArray();
                JSONArray barValue = new JSONArray();
                for(WorkshopType workshopType : listwstype){
                    barType.add(workshopType.getPeopletype());
                    barValue.add(workshopType.getCounts());
                    JSONObject pieObject = new JSONObject();
                    pieObject.put("name",workshopType.getPeopletype());
                    pieObject.put("value",workshopType.getCounts());
                    pieValue.add(pieObject);
                }
                model.addAttribute("meetingName",meeting.getTitle());
                model.addAttribute("barType",barType);
                model.addAttribute("barValue",barValue);
                model.addAttribute("pieValue",pieValue);
                result = "statistics/statisticsform";
            }

        }else if(type.equals("1")){
            if (!StringUtils.isEmpty(meetingId)) {
                Meeting meeting = meetingService.fetchById(meetingId);
                Conds conds = new Conds();
                if(!UserUtils.isAdmin()){
                    conds.equal("s.create_by", UserUtils.getUser().getId());
                }
                conds.equal("s.del_flag",0);
                conds.equal("s.workshop_id",meetingId);
                Sort sort = new Sort("clicks",OrderType.DESC);
                List<Sampleclick> list = statisticsService.countsampleclicks(conds,sort,0,0);
                JSONArray pieValue = new JSONArray();
                JSONArray barType = new JSONArray();
                JSONArray barValue = new JSONArray();
                JSONArray barValue1 = new JSONArray();
                JSONArray pieValue1 = new JSONArray();
                for(Sampleclick sampleclick : list){
                    //某个研讨会下面某个样本的名称
                    barType.add(sampleclick.getSample_title());
                    barValue.add(sampleclick.getCounts());
                    barValue1.add(sampleclick.getClicks()); //点击量
                    JSONObject pieObject = new JSONObject();
                    pieObject.put("name",sampleclick.getSample_title());
                    pieObject.put("value",sampleclick.getCounts());
                    pieValue.add(pieObject);
                    JSONObject pieObject1 = new JSONObject();
                    pieObject1.put("name",sampleclick.getSample_title());
                    pieObject1.put("value",sampleclick.getClicks());
                    pieValue1.add(pieObject1);

                }
                model.addAttribute("meetingName",meeting.getTitle());
                model.addAttribute("barType",barType);
                model.addAttribute("barValue",barValue);
                model.addAttribute("pieValue",pieValue);
                model.addAttribute("barValue1",barValue1);
                model.addAttribute("pieValue1",pieValue1);
                model.addAttribute("meetingId",meetingId);
                result ="statistics/samplestaticform";

            }
        }else if(type.equals("2")){
            if(!StringUtils.isEmpty(meetingId)){
                Meeting meeting = meetingService.fetchById(meetingId);
                Conds conds = new Conds();

                conds.equal("s.del_flag",0);
                conds.equal("s.workshop_id",meetingId);
                Sort sort = new Sort("clicks",OrderType.DESC);
                List<Speechclik> list = statisticsService.countspeechclicks(conds,sort,0,0);
                JSONArray pieValue = new JSONArray();
                JSONArray barType = new JSONArray();
                JSONArray barValue = new JSONArray();
                JSONArray barValue1 = new JSONArray();
                JSONArray pieValue1 = new JSONArray();
                for(Speechclik speechclik : list){
                    //某个研讨会下面某个演讲的名称
                    barType.add(speechclik.getSpeech_name());
                    barValue.add(speechclik.getCounts());
                    barValue1.add(speechclik.getClicks()); //点击量
                    JSONObject pieObject = new JSONObject();
                    pieObject.put("name",speechclik.getSpeech_name());
                    pieObject.put("value",speechclik.getCounts());
                    pieValue.add(pieObject);
                    JSONObject pieObject1 = new JSONObject();
                    pieObject1.put("name",speechclik.getSpeech_name());
                    pieObject1.put("value",speechclik.getClicks());
                    pieValue1.add(pieObject1);

                }
                model.addAttribute("meetingName",meeting.getTitle());
                model.addAttribute("barType",barType);
                model.addAttribute("barValue",barValue);
                model.addAttribute("pieValue",pieValue);
                model.addAttribute("barValue1",barValue1);
                model.addAttribute("pieValue1",pieValue1);
                model.addAttribute("meetingId",meetingId);
                result ="statistics/speechstaticform";
            }

        }else if(type.equals("3")){
            if(!StringUtils.isEmpty(meetingId)){
                Meeting meeting = meetingService.fetchById(meetingId);
                Conds conds = new Conds();
                conds.equal("a.del_flag",0);
                conds.equal("a.workshop_id",meetingId);
                Sort sort = new Sort("score",OrderType.ASC);
                List<Agendascore> list = statisticsService.countagendascore(conds,sort,0,0);
                JSONArray pieValue = new JSONArray();
                JSONArray barType = new JSONArray();
                JSONArray barValue = new JSONArray();
                for(Agendascore agendascore : list){
                    barType.add(agendascore.getAgenda_title());
                    barValue.add(agendascore.getScore());
                    JSONObject pieObject = new JSONObject();
                    pieObject.put("name",agendascore.getAgenda_title());
                    pieObject.put("value",agendascore.getScore());
                    pieValue.add(pieObject);
                }
                model.addAttribute("meetingName",meeting.getTitle());
                model.addAttribute("barType",barType);
                model.addAttribute("barValue",barValue);
                model.addAttribute("pieValue",pieValue);
                result = "statistics/agendascorform";
            }

        }
        return result;
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = STATISTICS_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Statistics statistics, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (statistics != null && statistics.getId() != null) {
                statistics.setUpdateBy(UserUtils.getUser().getId());
                statisticsService.update(statistics);
                rtnJson.put("errorNo", 0);
            } else {
                statistics.setNumber(codingruleUtils.getNumber(accountsId, Statistics.class.getName()));
                statistics.setAccountsId(accountsId);
                statistics.setDelFlag(false);
                statistics.setAccountsId(UserUtils.getmpaccounts(request));
                statistics.setCreateBy(UserUtils.getUser().getId());
                statistics.setUpdateBy(UserUtils.getUser().getId());
                statisticsService.save(statistics);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = STATISTICS_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Statistics statistics, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", accountsId);
        if(!UserUtils.isAdmin()){
            conds.equal("m.create_by", UserUtils.getUser().getId());
        }
        if (!StringUtils.isEmpty(statistics.getWs_title())) {
            conds.like("m.title", statistics.getWs_title());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

        List<Statistics> list = statisticsService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = statisticsService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //获取样本点击量列表数据
    @RequiresPermissions(value = STATISTICS_VIEW)
    @RequestMapping(value = "/listDataSignClick")
    @ResponseBody
    public JSONObject listDataSignClick(int iDisplayStart, int iDisplayLength, HttpServletRequest request,String meetingId) {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        conds.equal("wsid",meetingId);
        conds.equal("del_flag",0);
        conds.equal("status",2);
        Sort sort = new Sort("counts",OrderType.DESC);
        List<WorkshopType> listwstype = statisticsService.selecttypeworkshop(conds,sort,iDisplayStart,iDisplayLength);
        List<WorkshopType> listwstypes = statisticsService.selecttypeworkshop(conds,sort,0,0);
        rtnJson.put("iTotalRecords", listwstypes.size());
        rtnJson.put("iTotalDisplayRecords", listwstypes.size());
        rtnJson.put("aaData", listwstype);
        return rtnJson;
    }

    //获取样本点击量列表数据
    @RequiresPermissions(value = STATISTICS_VIEW)
    @RequestMapping(value = "/exportlistDataSignClick")
    @ResponseBody
    public JSONObject exportlistDataSignClick(HttpServletResponse response,String meetingId) {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        conds.equal("wsid",meetingId);
        conds.equal("del_flag",0);
        conds.equal("status",2);
        Sort sort = new Sort("counts",OrderType.DESC);
        List<WorkshopType> listwstypes = statisticsService.selecttypeworkshop(conds,sort,0,0);
        ExcelKit.$Export(WorkshopType.class, response).toExcel(listwstypes, "客户结构签到人员");
        return rtnJson;
    }


    //获取样本点击量列表数据
    @RequiresPermissions(value = STATISTICS_VIEW)
    @RequestMapping(value = "/listDataAgentSignClick")
    @ResponseBody
    public JSONObject listDataAgentSignClick(int iDisplayStart, int iDisplayLength, HttpServletRequest request,String meetingId) {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        conds.equal("a.del_flag",0);
        conds.equal("a.workshop_id",meetingId);
        Sort sort = new Sort("score",OrderType.DESC);
        List<Agendascore> listwstype = statisticsService.countagendascore(conds,sort,iDisplayStart,iDisplayLength);
        List<Agendascore> listwstypes = statisticsService.countagendascore(conds,sort,0,0);
        rtnJson.put("iTotalRecords", listwstypes.size());
        rtnJson.put("iTotalDisplayRecords", listwstypes.size());
        rtnJson.put("aaData", listwstype);
        return rtnJson;
    }

    //获取样本点击量列表数据
    @RequiresPermissions(value = STATISTICS_VIEW)
    @RequestMapping(value = "/exportlistDataAgentSignClick")
    @ResponseBody
    public JSONObject exportlistDataAgentSignClick(HttpServletResponse response,String meetingId) {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        conds.equal("a.del_flag",0);
        conds.equal("a.workshop_id",meetingId);
        Sort sort = new Sort("score",OrderType.DESC);
        List<Agendascore> listwstypes = statisticsService.countagendascore(conds,sort,0,0);
        ExcelKit.$Export(Agendascore.class, response).toExcel(listwstypes, "会议议程评分");
        return rtnJson;
    }


    //获取样本点击量列表数据
    @RequiresPermissions(value = STATISTICS_VIEW)
    @RequestMapping(value = "/listDataSampleClick")
    @ResponseBody
    public JSONObject listDataSampleClick(int iDisplayStart, int iDisplayLength, HttpServletRequest request,String meetingId) {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        if(!UserUtils.isAdmin()){
            conds.equal("s.create_by", UserUtils.getUser().getId());
        }
        conds.equal("s.del_flag",0);
        conds.equal("s.workshop_id",meetingId);
        Sort sort = new Sort("clicks",OrderType.DESC);
        List<Sampleclick> list = statisticsService.countsampleclicks(conds,sort,iDisplayStart,iDisplayLength);
        List<Sampleclick> list1 = statisticsService.countsampleclicks(conds,sort,0,0);
        rtnJson.put("iTotalRecords", list1.size());
        rtnJson.put("iTotalDisplayRecords", list1.size());
        rtnJson.put("aaData", list);
        return rtnJson;
    }
    @RequestMapping("/exportExcelSampleClick")
    @RequiresPermissions(value =  STATISTICS_VIEW)
    public void exportExcelSampleClick(HttpServletRequest request, HttpServletResponse response,String meetingId) {
        Conds conds = new Conds();
        if(!UserUtils.isAdmin()){
            conds.equal("s.create_by", UserUtils.getUser().getId());
        }
        conds.equal("s.del_flag",0);
        conds.equal("s.workshop_id",meetingId);
        Sort sort = new Sort("clicks",OrderType.DESC);
        List<Sampleclick> list = statisticsService.countsampleclicks(conds,sort,0,0);
        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(Sampleclick.class, response).toExcel(list, "样本内容点击量");
    }

    //获取样本查看率列表数据
    @RequiresPermissions(value = STATISTICS_VIEW)
    @RequestMapping(value = "/listDataSampleCount")
    @ResponseBody
    public JSONObject listDataSampleCount(int iDisplayStart, int iDisplayLength, HttpServletRequest request,String meetingId) {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        if(!UserUtils.isAdmin()){
            conds.equal("s.create_by", UserUtils.getUser().getId());
        }
        conds.equal("s.del_flag",0);
        conds.equal("s.workshop_id",meetingId);
        Sort sort = new Sort("clicks",OrderType.DESC);
        List<Sampleclick> list = statisticsService.countsampleclicks(conds,sort,iDisplayStart,iDisplayLength);
        rtnJson.put("iTotalRecords", list.size());
        rtnJson.put("iTotalDisplayRecords", list.size());
        rtnJson.put("aaData", list);
        return rtnJson;
    }
    @RequestMapping(value = "/exportExcelSampleCount")
    @RequiresPermissions(value =  STATISTICS_VIEW)
    public void exportExcelSampleCount(HttpServletRequest request, HttpServletResponse response,String meetingId) {
        Conds conds = new Conds();
        if(!UserUtils.isAdmin()){
            conds.equal("s.create_by", UserUtils.getUser().getId());
        }
        conds.equal("s.del_flag",0);
        conds.equal("s.workshop_id",meetingId);
        Sort sort = new Sort("clicks",OrderType.DESC);
        List<Sampleclick> list = statisticsService.countsampleclicks(conds,sort,0,0);
        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(Samplecont.class, response).toExcel(list, "样本内容查看率");
    }



    //嘉宾关注点击数据
    @RequiresPermissions(value = STATISTICS_VIEW)
    @RequestMapping(value = "/listDataSpeechClick")
    @ResponseBody
    public JSONObject listDataSpeechClick(int iDisplayStart, int iDisplayLength, HttpServletRequest request,String meetingId) {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        if(!UserUtils.isAdmin()){
            conds.equal("s.create_by", UserUtils.getUser().getId());
        }
        conds.equal("s.del_flag",0);
        conds.equal("s.workshop_id",meetingId);
        Sort sort = new Sort("clicks",OrderType.DESC);
        List<Speechclik> list = statisticsService.countspeechclicks(conds,sort,iDisplayStart,iDisplayLength);
        List<Speechclik> list1 = statisticsService.countspeechclicks(conds,sort,0,0);
        rtnJson.put("iTotalRecords", list1.size());
        rtnJson.put("iTotalDisplayRecords", list1.size());
        rtnJson.put("aaData", list);
        return rtnJson;
    }
    @RequestMapping(value = "/exportExcelSpeechClick")
    @RequiresPermissions(value =  STATISTICS_VIEW)
    public void exportExcelSpeechClick(HttpServletRequest request, HttpServletResponse response,String meetingId) {
        Conds conds = new Conds();
        if(!UserUtils.isAdmin()){
            conds.equal("s.create_by", UserUtils.getUser().getId());
        }
        conds.equal("s.del_flag",0);
        conds.equal("s.workshop_id",meetingId);
        Sort sort = new Sort("clicks",OrderType.DESC);
        List<Speechclik> list = statisticsService.countspeechclicks(conds,sort,0,0);
        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(Speechclik.class, response).toExcel(list, "演讲嘉宾点击量");
    }

    //嘉宾关注率据
    @RequiresPermissions(value = STATISTICS_VIEW)
    @RequestMapping(value = "/listDataSpeechCount")
    @ResponseBody
    public JSONObject listDataSpeechCount(int iDisplayStart, int iDisplayLength, HttpServletRequest request,String meetingId) {
        JSONObject rtnJson = new JSONObject();
        Conds conds = new Conds();
        if(!UserUtils.isAdmin()){
            conds.equal("s.create_by", UserUtils.getUser().getId());
        }
        conds.equal("s.del_flag",0);
        conds.equal("s.workshop_id",meetingId);
        Sort sort = new Sort("clicks",OrderType.DESC);
        List<Speechclik> list = statisticsService.countspeechclicks(conds,sort,iDisplayStart,iDisplayLength);
        List<Speechclik> list1 = statisticsService.countspeechclicks(conds,sort,0,0);
        rtnJson.put("iTotalRecords", list1.size());
        rtnJson.put("iTotalDisplayRecords", list1.size());
        rtnJson.put("aaData", list);
        return rtnJson;
    }
    @RequestMapping(value = "/exportExcelSpeechCount")
    @RequiresPermissions(value =  STATISTICS_VIEW)
    public void exportExcelSpeechCount(HttpServletRequest request, HttpServletResponse response,String meetingId) {
        Conds conds = new Conds();
        if(!UserUtils.isAdmin()){
            conds.equal("s.create_by", UserUtils.getUser().getId());
        }
        conds.equal("s.del_flag",0);
        conds.equal("s.workshop_id",meetingId);
        Sort sort = new Sort("clicks",OrderType.DESC);
        List<Speechclik> list = statisticsService.countspeechclicks(conds,sort,0,0);
        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(Speechcont.class, response).toExcel(list, "演讲嘉宾关注率");
    }

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

}
