package com.cftech.workshop.meeting.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.core.util.DateUtils;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.SystemConfig;
import com.cftech.mp.wechat.model.Qrcode;
import com.cftech.mp.wechat.service.QrcodeService;
import com.cftech.shop.qrcode.service.WxQrcodeService;
import com.cftech.shop.qrcode.util.WxQrcodeUtil;
import com.cftech.workshop.meeting.model.Meeting;
import com.cftech.workshop.meeting.service.MeetingService;
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.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.mp.api.wxaccount.JwAccountAPI;
import org.mp.api.wxaccount.model.WxQrcode;
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.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;


/**
 * Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String MEETING_VIEW = "qy:meeting:view"
 * 查看:public static final String MEETING_EDIT = "qy:meeting:edit"
 *
 * @author lisw
 * @date: 2018-06-28 15:20
 */
@Slf4j
@Controller
@RequestMapping("/a/meeting")
public class MeetingController {

    public static final String MEETING_VIEW = "qy:meeting:view";
    public static final String MEETING_EDIT = "qy:meeting:edit";

    public static final String appid = SystemConfig.p.getProperty("WX_MP_SERVER_APPID");

    @Autowired
    private MeetingService meetingService;
    @Autowired
    private CodingruleUtils codingruleUtils;
    @Autowired
    private WxQrcodeService wxQrcodeService;

    @Autowired
    private MpTokenUtil mpTokenUtil;

    @Autowired
    private WxQrcodeUtil wxQrcodeUtil;


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

    //编辑页面（新增、修改）
    @RequiresPermissions(value = MEETING_VIEW)
    @RequestMapping(value = "/form", method = {RequestMethod.GET, RequestMethod.POST})
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Meeting meeting = meetingService.fetchById(id);
            meeting.setContentBriefInfo(ESAPI.encoder().decodeForHTML(meeting.getContentBriefInfo()));
            meeting.setContentBriefEnInfo(ESAPI.encoder().decodeForHTML(meeting.getContentBriefEnInfo()));
            String startTimeStr = DateUtils.formatDate(meeting.getStartTime(), "yyyy-MM-dd");
            String endTimeStr = DateUtils.formatDate(meeting.getEndTime(), "yyyy-MM-dd");
            model.addAttribute("startTimeStr", startTimeStr);
            model.addAttribute("endTimeStr", endTimeStr);
            model.addAttribute("data", meeting);
        }
        return "meeting/meetingform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = MEETING_EDIT)
    @RequestMapping(value = "/formData", method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject formData(Meeting meeting, Model model, HttpServletRequest request,String closetime) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        if (!StringUtils.isEmpty(meeting.getStartTimeStr()) && !StringUtils.isEmpty(meeting.getEndTimeStr())) {
            Date startDate = DateUtils.parseDate(meeting.getStartTimeStr());
            Date endDate = DateUtils.parseDate(meeting.getEndTimeStr());
            meeting.setStartTime(startDate);
            meeting.setEndTime(endDate);
        }
        try {
            if (meeting != null && meeting.getId() != null) {
                if(closetime!=null){
                    Date close_data =DateUtils.parseDate(closetime);
                    meeting.setClosing_date(close_data);
                }
                meeting.setUpdateBy(UserUtils.getUser().getId());
                String servise = String.valueOf(meeting.getService());
                System.out.print(servise);
                meetingService.update(meeting);
                rtnJson.put("errorNo", 0);
            } else {
                meeting.setNumber(codingruleUtils.getNumber(accountsId, Meeting.class.getName()));
                meeting.setAccountsId(accountsId);
                meeting.setDelFlag(false);
                meeting.setAccountsId(UserUtils.getmpaccounts(request));
                meeting.setCreateBy(UserUtils.getUser().getId());
                meeting.setUpdateBy(UserUtils.getUser().getId());
                meeting.setStatus("0");
                meetingService.save(meeting);
                meetingService.synMobileMenu();
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = MEETING_VIEW)
    @RequestMapping(value = "/listData", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Meeting meeting, 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(meeting.getNumber())) {
            conds.like("number", meeting.getNumber());
        }
        if (!StringUtils.isEmpty(meeting.getTitle())) {
            conds.like("title", meeting.getTitle());
        }
        if (!StringUtils.isEmpty(meeting.getTitleEn())) {
            conds.like("title_en", meeting.getTitleEn());
        }
        if (!StringUtils.isEmpty(meeting.getCover())) {
            conds.like("cover", meeting.getCover());
        }
        if (!StringUtils.isEmpty(meeting.getWxCover())) {
            conds.like("wx_cover", meeting.getWxCover());
        }
        if (!StringUtils.isEmpty(meeting.getContentBriefInfo())) {
            conds.like("content_brief_info", meeting.getContentBriefInfo());
        }
        if (!StringUtils.isEmpty(meeting.getStartTime())) {
            conds.equal("start_time", meeting.getStartTime());
        }
        if (!StringUtils.isEmpty(meeting.getEndTime())) {
            conds.equal("end_time", meeting.getEndTime());
        }
        if (!StringUtils.isEmpty(meeting.getQrCode())) {
            conds.like("qr_code", meeting.getQrCode());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

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

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

    //下载二维码
    @RequiresPermissions(value = MEETING_EDIT)
    @RequestMapping(value = "/downloadcode", method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadcode(String id , com.cftech.shop.qrcode.model.WxQrcode qrcode, HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject jsonObject = new JSONObject();
        Long accountsId = UserUtils.getmpaccounts(request);

        String accessToken = mpTokenUtil.getToken(accountsId);
        WxQrcode wxqrcode=null;
        if(!StringUtils.isEmpty(id)){
            Meeting meeting = meetingService.fetchById(Long.valueOf(id));
            if(StringUtils.isEmpty(meeting.getQrCode())){ //该研讨会已经生成可二维码
                try {
                    Conds conds = new Conds();
                    conds.equal("t.del_flag",0);
                    int count = wxQrcodeService.count(conds);
                    JSONObject wxObj = wxQrcodeUtil.createLimitQrcode(accountsId, Long.valueOf(count));
                    if (wxObj.containsKey("ticket")) {
                        qrcode.setTicket(wxObj.getString("ticket"));
                    }
                    qrcode.setId(null);
                    String tempTicket="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+qrcode.getTicket();
                    qrcode.setCreateBy(UserUtils.getUser().getId());
                    qrcode.setType("meeting");
                    qrcode.setUpdateBy(UserUtils.getUser().getId());
                    qrcode.setSceneId(String.valueOf(count));
                    qrcode.setBindId(meeting.getId());
                    qrcode.setDelFlag(false);
                    meetingService.addcode(qrcode,meeting);
                    downPicture(request,response,tempTicket,meeting.getTitle());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else{
                downPicture(request,response,"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+meeting.getQrCode(),meeting.getTitle());
            }
        }
    }


    public void downPicture(HttpServletRequest request,HttpServletResponse response,String urls,String title) throws IOException {

        String prefix ="jpg";
//获取文件

        URL url = new URL(urls);
        URLConnection conn = url.openConnection();
//设置超时间为3秒
        conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//输出流
        InputStream fs = conn.getInputStream();

        int  bytesRead = 0;
        byte[] image = new byte[8192 ];
        response.setHeader("Content-Type","application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename="+new String(title.getBytes("gb2312"), "ISO8859-1" )+"."+prefix);
        try {
            while ((bytesRead = fs.read(image, 0, 8192)) != -1) {
                response.getOutputStream().write(image,0,bytesRead);

            }
            fs.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

}
