package com.cftech.workshop.agenda.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.core.util.DateUtils;
import com.cftech.workshop.agenda.model.Agenda;
import com.cftech.workshop.agenda.model.AgendaCustomiz;
import com.cftech.workshop.agenda.service.AgendaService;
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.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.speech.model.Speech;
import com.cftech.workshop.speech.service.SpeechService;
import com.cftech.workshop.meeting.service.MeetingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.owasp.esapi.ESAPI;
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 org.springframework.web.util.HtmlUtils;

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


/**
 * Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String AGENDA_VIEW = "qy:agenda:view"
 * 查看:public static final String AGENDA_EDIT = "qy:agenda:edit"
 *
 * @author byj
 * @date: 2018-06-29 14:32
 */
@Slf4j
@Controller
@RequestMapping("/a/agenda")
public class AgendaController {

    public static final String AGENDA_VIEW = "qy:agenda:view";
    public static final String AGENDA_EDIT = "qy:agenda:edit";

    @Autowired
    private AgendaService agendaService;
    @Autowired
    private CodingruleUtils codingruleUtils;
    @Autowired
    private MeetingService meetingService;
    @Autowired
    private SpeechService speechService;
    @Autowired
    private Agenda_customizService agenda_customizService;




    //列表页面
    @RequiresPermissions(value = AGENDA_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model,Long meetingId) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        model.addAttribute("meetingId",meetingId);
        if(meetingId!=0){
            Meeting meeting = meetingService.fetchById(meetingId);
            model.addAttribute("status",meeting.getStatus());
        }
        return "agenda/agendalist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = AGENDA_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model , Long meetingId,String status) {
        if (!StringUtils.isEmpty(id)) {
            Agenda agenda = agendaService.fetchById(id);
            String begantime = DateUtils.formatDate(agenda.getAgenda_time());
            agenda.setContent_agenda(ESAPI.encoder().decodeForHTML(agenda.getContent_agenda()));
            agenda.setContent_agenda_en(ESAPI.encoder().decodeForHTML(agenda.getContent_agenda_en()));
            model.addAttribute("begantime", begantime);
            model.addAttribute("data", agenda);
            Speech speech = speechService.fetchById(agenda.getSpeech_id());
            if(speech!=null){
                if(speech.isDelFlag()==false){
                    model.addAttribute("speech_name",speech.getSpeech_name());
                }

            }
            Agenda_customiz agenda_customiz = agenda_customizService.fetchById(agenda.getCustomiz_id());
            if(agenda_customiz!=null){
                if(agenda_customiz.isDelFlag()==false){
                    model.addAttribute("customiz_name",agenda_customiz.getCustomiz_name());
                }

            }
        }
        if(!StringUtils.isEmpty(status)){
            model.addAttribute("status",status);
            Conds conds = new Conds();
            conds.equal("del_flag",0);
            conds.equal("workshop_id",meetingId);
            Sort sort = new Sort("sort",OrderType.ASC);
            List<Agenda_customiz> agenda_customiz = agenda_customizService.fetchSearchByPage(conds,sort,0,0);
            if(agenda_customiz!=null&& agenda_customiz.size()>0){
                model.addAttribute("agenda_customiz",agenda_customiz);
            }
        }
        model.addAttribute("meetingId",meetingId);
        return "agenda/agendaform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = AGENDA_EDIT)
    @RequestMapping(value = "/formData",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject formData(Agenda agenda, Model model, HttpServletRequest request,String agendaStr) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        Date startDate = DateUtils.parseDate(agendaStr);
        if (!StringUtils.isEmpty(agendaStr)) {
           agenda.setAgenda_time(startDate);
        }
        try {
            if (agenda != null && agenda.getId() != null) {
                agenda.setUpdateBy(UserUtils.getUser().getId());
                agenda.setAgenda_time(startDate);
                agendaService.update(agenda);
                rtnJson.put("errorNo", 0);
            } else {
                agenda.setNumber(codingruleUtils.getNumber(accountsId, Agenda.class.getName()));
                agenda.setAccountsId(accountsId);
                agenda.setDelFlag(false);
                agenda.setAccountsId(UserUtils.getmpaccounts(request));
                agenda.setCreateBy(UserUtils.getUser().getId());
                agenda.setUpdateBy(UserUtils.getUser().getId());
                agendaService.save(agenda);
                meetingService.synMobileMenu();
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = AGENDA_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, AgendaCustomiz agendaCustomiz, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("a.del_flag", Constants.DEL_FLAG_0);
        conds.equal("a.accounts_id", accountsId);
        if (!StringUtils.isEmpty(agendaCustomiz.getWorkshop_id())) {
            conds.equal("a.workshop_id", agendaCustomiz.getWorkshop_id());
        }
        if(!StringUtils.isEmpty(agendaCustomiz.getAgenda_title())){
            conds.like("a.agenda_title",agendaCustomiz.getAgenda_title());
        }
        Sort sort = new Sort("c.id ASC,a.sort",OrderType.ASC);
        List<AgendaCustomiz> list = agendaService.agendaCustomizs(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = agendaService.agendaCustomizcount(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

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

        return rtnJosn;
    }

}
