package com.cftech.cms.exhibi.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;

import com.cftech.cms.exhibi.model.Exhibi;
import com.cftech.cms.exhibi.service.ExhibiService;
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.core.util.MpTokenUtil;
import com.cftech.core.util.SystemConfig;
import com.cftech.shop.qrcode.service.WxQrcodeService;
import com.cftech.shop.qrcode.util.WxQrcodeUtil;
import com.cftech.sys.security.UserUtils;
import com.esotericsoftware.minlog.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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 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.util.List;


/**
 * Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String EXHIBI_VIEW = "qy:exhibi:view"
 * 查看:public static final String EXHIBI_EDIT = "qy:exhibi:edit"
 *
 * @author byj
 * @date: 2018-06-12 16:14
 */
@Slf4j
@Controller
@RequestMapping("/a/exhibi")
public class ExhibiController {

    public static final String EXHIBI_VIEW = "qy.exhibi.view";
    public static final String EXHIBI_EDIT = "qy.exhibi.edit";
    public static final String appid = SystemConfig.p.getProperty("WX_MP_SERVER_APPID");

    @Autowired
    private ExhibiService exhibiService;
    @Autowired
    private CodingruleUtils codingruleUtils;
    @Autowired
    private WxQrcodeService wxQrcodeService;

    @Autowired
    private MpTokenUtil mpTokenUtil;

    @Autowired
    private WxQrcodeUtil wxQrcodeUtil;


    //列表页面
    @RequiresPermissions(value = EXHIBI_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 "exhibi/exhibilist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = EXHIBI_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.GET,RequestMethod.POST})
    public String form(HttpServletRequest request, Long id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Exhibi exhibi = exhibiService.fetchById(id);
            exhibi.setContent_exhibi(ESAPI.encoder().decodeForHTML(exhibi.getContent_exhibi()));
            exhibi.setContent_exhibi_en(ESAPI.encoder().decodeForHTML(exhibi.getContent_exhibi_en()));
            model.addAttribute("data", exhibi);
        }
        return "exhibi/exhibiform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = EXHIBI_EDIT)
    @RequestMapping(value = "/formData",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject formData(Exhibi exhibi, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (exhibi != null && exhibi.getId() != null) {
                exhibi.setUpdateBy(UserUtils.getUser().getId());
                //是否发布
                exhibiService.update(exhibi);
                rtnJson.put("errorNo", 0);
            } else {
                /*if(exhibi.getReleas().equals("0")){ //发布
                    Conds conds = new Conds();
                    conds.equal("exhibi_type",exhibi.getExhibi_type());
                    conds.equal("releas",exhibi.getReleas()); //发布 0:发布  1:未发布
                    conds.equal("del_flag",0);
                    int relea = exhibiService.count(conds);
                    if(relea>0){ //该分类下面已经有展会发布
                        rtnJson.put("errorNo",3);
                        return rtnJson;
                    }
                }*/
                exhibi.setNumber(codingruleUtils.getNumber(accountsId, Exhibi.class.getName()));
                exhibi.setAccountsId(accountsId);
                exhibi.setDelFlag(false);
                exhibi.setAccountsId(UserUtils.getmpaccounts(request));
                exhibi.setCreateBy(UserUtils.getUser().getId());
                exhibi.setUpdateBy(UserUtils.getUser().getId());
                exhibi.setReleas("1");
                exhibi.setReading(Long.valueOf(0));
                exhibi.setFabulous(Long.valueOf(0));
                exhibi.setSelects(Long.valueOf(0));
                exhibi.setReviews(Long.valueOf(0));
                exhibiService.save(exhibi);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            log.error("保存展会失败",e);
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = EXHIBI_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Exhibi exhibi, 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(exhibi.getNumber())) {
            conds.like("number", exhibi.getNumber());
        }
        if (!StringUtils.isEmpty(exhibi.getExhibi_title())) {
            conds.like("exhibi_title", exhibi.getExhibi_title());
        }
        if (!StringUtils.isEmpty(exhibi.getExhibi_title_en())) {
            conds.like("exhibi_title_en", exhibi.getExhibi_title_en());
        }
        if (!StringUtils.isEmpty(exhibi.getExhibi_number())) {
            conds.like("exhibi_number", exhibi.getExhibi_number());
        }
        if (!StringUtils.isEmpty(exhibi.getExhibi_number_en())) {
            conds.like("exhibi_number_en", exhibi.getExhibi_number_en());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

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

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

    //修改发布
    @RequiresPermissions(value = EXHIBI_EDIT)
    @RequestMapping(value = "/updaterelease",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject updaterelease(String releas,String id){
        JSONObject jsonObject = new JSONObject();
       try {
           if(!StringUtils.isEmpty(releas)&&!StringUtils.isEmpty(id)){
               Exhibi exhibi = new Exhibi();
               boolean flag = true;
               if(releas.equals("1")){ //未发布改为发布
                   Conds conds = new Conds();
                   conds.equal("id",id);
                   conds.equal("del_flag",0);
                   Exhibi exhibi1 = exhibiService.fetchSearchByConds(conds);
                   if(exhibi!=null){
                       /*Conds conds1 = new Conds();
                       conds1.notEqual("id",id);
                       conds1.equal("releas","0");
                       conds1.equal("del_flag",0);
                       conds1.equal("exhibi_type",exhibi1.getExhibi_type());
                       Sort sort = new Sort("create_time",OrderType.DESC);
                      List<Exhibi> list = exhibiService.fetchSearchByPage(conds1,sort,0,0);
                       if(list.size()>0){  //同一类型发布展会发布1条以上
                            jsonObject.put("errorNo",2);
                           flag = false;
                       }else{*/
                           exhibi.setId(Long.valueOf(id));
                           exhibi.setReleas("0");
                           flag = exhibiService.update(exhibi);
                      // }
                   }

               }else{  //发布改为未发布
                   exhibi.setId(Long.valueOf(id));
                   exhibi.setReleas("1");
                   flag = exhibiService.update(exhibi);
               }
               if(flag == true){
                   jsonObject.put("errorNo",0);
               }
           }
       }catch (Exception e){
           e.printStackTrace();
           jsonObject.put("errorNo",1);
       }
        return jsonObject;
    }

    //下载二维码
    @RequiresPermissions(value = EXHIBI_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)){
            Exhibi exhibi = exhibiService.fetchById(Long.valueOf(id));
            if(StringUtils.isEmpty(exhibi.getQr_code())){ //该展会已经生成可二维码
                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"));
                    }
                    String tempTicket="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+qrcode.getTicket();
                    qrcode.setId(null);
                    qrcode.setCreateBy(UserUtils.getUser().getId());
                    qrcode.setType("exhibi");
                    qrcode.setUpdateBy(UserUtils.getUser().getId());
                    qrcode.setSceneId(String.valueOf(count));
                    qrcode.setBindId(exhibi.getId());
                    qrcode.setDelFlag(false);
                    exhibiService.addcode(qrcode,exhibi);
                    downPicture(request,response,tempTicket,exhibi.getExhibi_title());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else{
                downPicture(request,response,"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+exhibi.getQr_code(),exhibi.getExhibi_title());
            }
        }
    }

    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();
    }

}
