package com.cftech.workshop.template.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.core.util.DateUtils;
import com.cftech.core.util.OKHttpUtils;
import com.cftech.workshop.template.model.Template;
import com.cftech.workshop.template.service.TemplateService;
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 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 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 TEMPLATE_VIEW = "qy:template:view"
 * 查看:public static final String TEMPLATE_EDIT = "qy:template:edit"
 *
 * @author lisw
 * @date: 2018-07-18 16:45
 */
@Slf4j
@Controller
@RequestMapping("/a/templateMessage")
public class TemplateController {

    public static final String TEMPLATE_VIEW = "qy:templateMessage:view";
    public static final String TEMPLATE_EDIT = "qy:templateMessage:edit";

    @Autowired
    private TemplateService templateService;


    //列表页面
    @RequiresPermissions(value = TEMPLATE_VIEW)
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(HttpServletRequest request, Model model,String meetingId) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        model.addAttribute("meetingId",meetingId);
        return "template/templatelist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = TEMPLATE_VIEW)
    @RequestMapping(value = "/form",method = RequestMethod.GET)
    public String form(HttpServletRequest request, String id, Model model,String meetingId) {
        if (!StringUtils.isEmpty(id)) {
            Template template = templateService.fetchById(id);
            model.addAttribute("data", template);
        }
        model.addAttribute("meetingId",meetingId);
        return "template/templateform";
    }




    //提交数据（新增、修改）
    @RequiresPermissions(value = TEMPLATE_EDIT)
    @RequestMapping(value = "/formData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject formData(Template template, Model model, HttpServletRequest request,String sendTimeStr) {
        JSONObject rtnJson = new JSONObject();
        List<Template> templates =new ArrayList<Template>();
        template.setSendTime(DateUtils.parseDate(sendTimeStr));
        try {
            if (template != null && template.getId() != null) {
                templateService.updateTemplate(template);
                rtnJson.put("errorNo", 0);
            } else {
                template.setDelFlag(false);
                template.setAccountsId(UserUtils.getmpaccounts(request));
                template.setCreateBy(UserUtils.getUser().getId());
                template.setUpdateBy(UserUtils.getUser().getId());
                templateService.saveTemplate(template);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = TEMPLATE_VIEW)
    @RequestMapping(value = "/listData",method = RequestMethod.GET)
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Template template, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        if(!UserUtils.isAdmin()){
            conds.equal("create_by", UserUtils.getUser().getId());
        }
        if (!StringUtils.isEmpty(template.getType())) {
            conds.like("type", template.getType());
        }
        if (!StringUtils.isEmpty(template.getSendTime())) {
            conds.equal("send_time", template.getSendTime());
        }
        conds.equal("meeting_id",template.getMeetingId());
        Sort sort = new Sort("send_time", OrderType.ASC);

        List<Template> list = templateService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        for(Template template1 : list){
            template1.setContent(ESAPI.encoder().decodeForHTML(template1.getContent()));
        }
        Integer counts = templateService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);

        String text = "欢迎预约与使用舍弗勒安亭展厅&amp;&#x23;xff01&#x3b; Welcome to the Schaeffler Anting Showroom booking platform. &amp;lt&#x3b;a href&amp;&#x23;x3d&#x3b;&amp;&#x23;x27&#x3b;https://mp.wx-schaeffler.cn/schaeffler/static/mp/schaeffler/process/video.html&amp;&#x23;x3f&#x3b;appid&amp;&#x23;x3d&#x3b;wx7ded418de1ccae07&amp;&#x23;x27&#x3b;&amp;gt&#x3b;点击预约 Click to make a reservation.&amp;lt&#x3b;/a&amp;gt&#x3b;";
        System.out.println(ESAPI.encoder().decodeForHTML(text));
        return rtnJson;
    }

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

}
