package com.cftech.workshop.screen.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.sys.model.User;
import com.cftech.sys.service.UserService;
import com.cftech.workshop.agenda.model.Agenda;
import com.cftech.workshop.agenda.service.AgendaService;
import com.cftech.workshop.agenda_customiz.model.Agenda_customiz;
import com.cftech.workshop.agenda_customiz.service.Agenda_customizService;
import com.cftech.workshop.meeting.model.Meeting;
import com.cftech.workshop.meeting.service.MeetingService;
import com.cftech.workshop.screen.model.Screen;
import com.cftech.workshop.screen.model.ScreenDto;
import com.cftech.workshop.screen.model.ScreenRSVP;
import com.cftech.workshop.screen.model.ScreenTopic;
import com.cftech.workshop.screen.service.ScreenService;
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.statistics.model.Speechclik;
import com.cftech.workshop.workshop.model.Workshop;
import com.cftech.workshop.workshop.model.WorkshopDto;
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.RequestMethod;
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.List;


/**
 * Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String SCREEN_VIEW = "qy:screen:view"
 * 查看:public static final String SCREEN_EDIT = "qy:screen:edit"
 *
 * @author byj
 * @date: 2018-10-22 15:41
 */
@Slf4j
@Controller
@RequestMapping("/a/screen")
public class ScreenController {

    public static final String SCREEN_VIEW = "qy:screen:view";
    public static final String SCREEN_EDIT = "qy:screen:edit";

    @Autowired
    private ScreenService screenService;
    @Autowired
    private CodingruleUtils codingruleUtils;
    @Autowired
    private Agenda_customizService agenda_customizService;
    @Autowired
    private AgendaService agendaService;
    @Autowired
    private UserService userService;
    @Autowired
    private MeetingService meetingService;


    //列表页面
    @RequiresPermissions(value = SCREEN_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        //主题
try{


        Conds topicconds = new Conds();
        if(!UserUtils.isAdmin()){
            //conds.equal("create_by", UserUtils.getUser().getId());
            User user = userService.fetchById(UserUtils.getUser().getId());
            if(user!=null){
                topicconds.equal("customiz_id",user.getCustomiz_id());
            }
            Agenda_customiz agenda_customiz = agenda_customizService.fetchById(user.getCustomiz_id());
            if(agenda_customiz!=null){
                model.addAttribute("agenda_customiz",agenda_customiz);
            }
        }
        topicconds.equal("del_flag",0);
        Sort topicsort =  new Sort("sort",OrderType.ASC);
        List<Agenda> listtopic = agendaService.fetchSearchByPage(topicconds,topicsort,0,0);
        if(listtopic.size()>0){
            model.addAttribute("topic",listtopic);
        }
}catch (Exception e){
    e.printStackTrace();
}
        return "screen/screenlist";
    }
    //联动主题
    @RequiresPermissions(value = SCREEN_VIEW)
    @RequestMapping("/listtopic")
    @ResponseBody
    public  JSONObject listtopic(HttpServletRequest request,Long customizId){
        JSONObject jsonObject = new JSONObject();
        Conds topicconds = new Conds();
        if(customizId!=0){
            topicconds.equal("customiz_id",customizId);
            topicconds.equal("del_flag",0);
        }else{
            topicconds.equal("del_flag",0);
        }
        Sort topicsort =  new Sort("sort",OrderType.ASC);
        List<Agenda> listtopic = agendaService.fetchSearchByPage(topicconds,topicsort,0,0);
        if(listtopic.size()>0){
            jsonObject.put("topic",listtopic);
        }
        return jsonObject;
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = SCREEN_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Screen screen = screenService.fetchById(id);
            model.addAttribute("data", screen);
        }
        return "screen/screenform";
    }

    //主题开放
    @RequiresPermissions(value = SCREEN_VIEW)
    @RequestMapping("/screentopiclist")
    public String screentopiclist(HttpServletRequest request, Model model){
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        Conds topicconds = new Conds();
        String isadmin = "1";
        if(!UserUtils.isAdmin()){
            //conds.equal("create_by", UserUtils.getUser().getId());
            User user = userService.fetchById(UserUtils.getUser().getId());
            if(user!=null){
                topicconds.equal("customiz_id",user.getCustomiz_id());
                model.addAttribute("customizId",user.getCustomiz_id());
            }
            Agenda_customiz agenda_customiz = agenda_customizService.fetchById(user.getCustomiz_id());
            if(agenda_customiz!=null){
                model.addAttribute("agenda_customiz",agenda_customiz);
            }
            isadmin = "0";
        }
        model.addAttribute("isadmin",isadmin);
        return "screen/screentopiclist";
    }

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

    //获取列表数据
    @RequiresPermissions(value = SCREEN_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, ScreenDto screenDto, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        if(!UserUtils.isAdmin()){
            //conds.equal("create_by", UserUtils.getUser().getId());
           User user = userService.fetchById(UserUtils.getUser().getId());
            if(user!=null){
                conds.equal("c.id",user.getCustomiz_id());
            }
        }
        conds.equal("s.del_flag", Constants.DEL_FLAG_0);
        conds.equal("s.accounts_id", accountsId);
        if (!StringUtils.isEmpty(screenDto.getCustomiz())) {
            if(!screenDto.getCustomiz().equals("0")){
                conds.like("c.id", screenDto.getCustomiz());
            }
        }
        if (!StringUtils.isEmpty(screenDto.getTopic())) {
            if(!screenDto.getTopic().equals("0")){
                conds.like("a.id", screenDto.getTopic());
            }
        }
        if(!StringUtils.isEmpty(screenDto.getName())){
            conds.like("m.name",screenDto.getName());
        }
        Sort sort = new Sort("s.create_time", OrderType.DESC);

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

    //获取主题列表数据
    @RequiresPermissions(value = SCREEN_VIEW)
    @RequestMapping(value = "/TopiclistData")
    @ResponseBody
    public JSONObject TopiclistData(int iDisplayStart, int iDisplayLength) {
        JSONObject jsonObject = new JSONObject();
        Conds conds = new Conds();
        conds.equal("a.del_flag",0);
        conds.notNull("c.id");
        if(!UserUtils.isAdmin()){
            //conds.equal("create_by", UserUtils.getUser().getId());
            User user = userService.fetchById(UserUtils.getUser().getId());
            if(user!=null){
                conds.equal("c.id",user.getCustomiz_id());
            }
        }
//        if(!screenDto.getCustomiz().equals("0")){
//            conds.equal("a.customiz_id",screenDto.getCustomiz());
//        }
        Sort sort = new Sort("a.sort",OrderType.ASC);
        List<ScreenTopic> list = screenService.selectscreentopic(conds,sort,iDisplayStart,iDisplayLength);
        int count = screenService.countscreentopic(conds);
        jsonObject.put("iTotalRecords", count);
        jsonObject.put("iTotalDisplayRecords", count);
        jsonObject.put("aaData", list);
        return jsonObject;
    }
    //导出Excel
    @RequestMapping(value = "/Exportexcel")
    @RequiresPermissions(value =  SCREEN_VIEW)
    public void Exportexcel(HttpServletRequest request, HttpServletResponse response,ScreenDto screenDto) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("s.del_flag", Constants.DEL_FLAG_0);
        conds.equal("s.accounts_id", accountsId);
        if (!StringUtils.isEmpty(screenDto.getCustomiz())) {
            conds.like("c.customiz_name", screenDto.getCustomiz());
        }
        if (!screenDto.getTopic().equals("0")) {
            conds.like("a.id", screenDto.getTopic());
        }
        if(!StringUtils.isEmpty(screenDto.getName())){
            conds.like("m.name",screenDto.getName());
        }
        Sort sort = new Sort("s.create_time", OrderType.DESC);

        List<Screen> list = screenService.fetchSearchByPage(conds, sort, 0, 0);
        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(ScreenDto.class, response).toExcel(list, "现场投屏");
    }

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

    //下载模板
    @RequestMapping(value = "/templateExcel" , method = {RequestMethod.GET,RequestMethod.POST})
    @RequiresPermissions(value = SCREEN_EDIT)
    @ResponseBody
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        // 生成Excel并使用浏览器下载

        ExcelKit.$Export(ScreenRSVP.class, response).toExcel(null, "预导投屏信息");
    }

    //导入
    @RequestMapping(value = "/importExcel" , method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    @RequiresPermissions(value = SCREEN_EDIT)
    public JSONObject importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        JSONObject retJson = new JSONObject();
        Long accountId = UserUtils.getmpaccounts(request);
        StringBuffer stringBuffer = new StringBuffer();
        if (file == null) {
            retJson.put("errorNo", "1");
            retJson.put("errorMsg", "未选择导入文件");
            return retJson;
        }
        // 构造临时路径来存储上传的文件
        String uploadPath = System.getProperty("java.io.tmpdir");
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        String fileName = file.getOriginalFilename();
        String filePath = uploadPath + File.separator + fileName;
        File storeFile = new File(filePath);
        try {
            file.transferTo(storeFile);


            ExcelKit.$Import().setEmptyCellValue(null).readExcel(storeFile, rowData -> {
                if(!rowData.get(0).equals("")&&!rowData.get(1).equals("")&&!rowData.get(2).equals("")
                        &&!rowData.get(3).equals("")&&!rowData.get(4).equals("")){
                    Screen screen = new Screen();
                    screen.setAccountsId(accountId);
                    //会场
                    Conds condscustomiz = new Conds();
                    condscustomiz.equal("customiz_name",rowData.get(0));
                    condscustomiz.equal("del_flag",0);
                    Agenda_customiz agenda_customiz = agenda_customizService.fetchSearchByConds(condscustomiz);
                    if(agenda_customiz!=null){
                        screen.setCustomiz_id(String.valueOf(agenda_customiz.getId()));
                    }else{
                        return;
                    }
                    //主题
                    Conds condstopic = new Conds();
                    condstopic.equal("agenda_title",rowData.get(1));
                    condstopic.equal("del_flag",0);
                    Agenda agenda = agendaService.fetchSearchByConds(condstopic);
                    if(agenda!=null){
                        screen.setTopic_id(String.valueOf(agenda.getId()));
                    }else{
                        return;
                    }
                    //问题
                    screen.setQuestion(rowData.get(2));
                    //研讨会
                    Conds condsmeeting = new Conds();
                    condsmeeting.equal("title",rowData.get(3));
                    condsmeeting.equal("del_flag",0);
                    Meeting meeting = meetingService.fetchSearchByConds(condsmeeting);
                    if(meeting!=null){
                        screen.setMeetingId(meeting.getId());
                    }else{
                        return;
                    }
                    //昵称
                    screen.setNickname(rowData.get(4));
                    screenService.save(screen);
                }else{
                    return;
                }

            });
        } catch (IOException e) {
//            e.printStackTrace();
            log.error(e.getMessage());
        }
        retJson.put("errorNo", "0");
        retJson.put("errorMsg","导入成功");
        return retJson;
    }

    //上屏
    @RequiresPermissions(value = SCREEN_VIEW)
    @RequestMapping("/updatestatus")
    @ResponseBody
    public JSONObject updatestatus(String id,String agenda_id){
        JSONObject jsonObject = new JSONObject();
        if(!StringUtils.isEmpty(id)&&!StringUtils.isEmpty(agenda_id)){
            Conds condsid = new Conds();
            condsid.equal("id",id);
            condsid.equal("topic_id",agenda_id);
            Screen screenid = screenService.selectbyconds(condsid);
            //判断该会场下面的主题是否开放
            Conds condstopic = new Conds();
            condstopic.equal("id",screenid.getTopic_id());
            condstopic.equal("del_flag",0);
           //condstopic.equal("agenda_id",agenda_id);
            Agenda agenda = agendaService.fetchSearchByConds(condstopic);
            if(agenda.getStatus().equals("0")){  //主题未开放
                jsonObject.put("errorNo",1);
            }else if(agenda.getStatus().equals("1")){  //主题开放
                jsonObject.put("errorNo",0);
                if(screenid.getStatus().equals("0")){ //未上屏
                    //查询是否有已经上屏的
                    Conds conds= new Conds();
                    //conds.equal("id",id);
                    conds.equal("del_flag",0);
                    conds.equal("status",1);
                    conds.equal("topic_id",agenda_id);
                    Screen screen = screenService.selectbyconds(conds);
                    if(screen!=null){  //该会场有上屏的问题
                        screen.setStatus("2");
                        screenService.update(screen);
                    }
                    Screen screen1 = new Screen();
                    screen1.setId(Long.valueOf(id));
                    screen1.setStatus("1");
                    screenService.update(screen1);
                }else if(screenid.getStatus().equals("1")){  //结束
                    screenid.setStatus("2");
                    screenService.update(screenid);
                }
            }else if(agenda.getStatus().equals("2")){ // 主题已关闭
                jsonObject.put("errorNo",2);
            }

        }
        return jsonObject;
    }

    //开放主题
    @RequiresPermissions(value = SCREEN_VIEW)
    @RequestMapping(value = "/openstatue",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject openstatue(String id){
        JSONObject rtnJson = new JSONObject();
        try{
            if(!StringUtils.isEmpty(id)){
                Agenda agenda = agendaService.fetchById(id);
                if(agenda.getStatus().equals("0")){  //未开放变为开放状态
                    Conds conds = new Conds();
                    conds.equal("customiz_id",agenda.getCustomiz_id());
                    conds.equal("status",1);
                    conds.equal("del_flag",0);
                    Agenda agenda1 = agendaService.fetchSearchByConds(conds);
                    if(agenda1!=null){
                        agenda1.setStatus("2");
                        agendaService.update(agenda1);
                    }
                    Agenda agenda2 = new Agenda();
                    agenda2.setId(Long.valueOf(id));
                    agenda2.setStatus("1");
                    agendaService.update(agenda2);
                }else if(agenda.getStatus().equals("1")){//开放状态变为关闭状态
                    agenda.setStatus("2");
                    agendaService.update(agenda);
                }
            }
        }catch (Exception e){
            rtnJson.put("errorNo",1);
            e.printStackTrace();
        }
        rtnJson.put("errorNo",0);
        return rtnJson;
    }

    //投放大屏幕
    @RequestMapping(value = "/selectquestion")
    @ResponseBody
    public JSONObject selectquestion(String customizId){
        JSONObject jsonObject = new JSONObject();
        try {
            if(!StringUtils.isEmpty(customizId)){
                jsonObject.put("errorNo",0);
                Conds conds = new Conds();
                conds.equal("customiz_id",customizId);
                conds.equal("del_flag",0);
                conds.equal("status",1);
                Agenda agenda = agendaService.fetchSearchByConds(conds);
                jsonObject.put("errorNo",0);
                if(agenda != null){  //有开放的主题
                    Conds condsreen = new Conds();
                    condsreen.equal("c.id",agenda.getCustomiz_id());
                    condsreen.equal("s.del_flag",0);
                    condsreen.equal("a.id",agenda.getId());
                    condsreen.equal("s.status",1);
                    condsreen.equal("a.id",agenda.getId());
                    ScreenDto screenDto = screenService.selectquestion(condsreen);
                    if(screenDto!=null){
                        jsonObject.put("data",screenDto);
                    }else{
                        jsonObject.put("data",null);
                    }
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  jsonObject;
    }

}
