package com.cftech.shop.qrcode.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.core.util.HttpURLConnectionUtil;
import com.cftech.core.util.SystemConfig;
import com.cftech.shop.qrcode.model.WxQrcode;
import com.cftech.shop.qrcode.model.vo.WxQrcodeVO;
import com.cftech.shop.qrcode.service.WxQrcodeService;

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.shop.qrcode.util.QrcodeDown;
import com.cftech.shop.qrcode.util.WxQrcodeUtil;
import com.cftech.sys.security.UserUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * 二维码Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String WXQRCODE_VIEW = "qy:wxQrcode:view"
 * 查看:public static final String WXQRCODE_EDIT = "qy:wxQrcode:edit"
 *
 * @author Neil
 * @date: 2017-12-04 17:56
 */
@Slf4j
@Controller
@RequestMapping("/a/wxQrcode")
public class WxQrcodeController {

    public static final String WXQRCODE_VIEW = "qy:wxQrcode:view";
    public static final String WXQRCODE_EDIT = "qy:wxQrcode:edit";

    @Autowired
    private WxQrcodeService wxQrcodeService;
    @Autowired
    private WxQrcodeUtil wxQrcodeUtil;


    //下载展厅二维码
    @RequestMapping(value = "/downloadcode", method = {RequestMethod.GET, RequestMethod.POST})
    public void downloadcode(Long id, WxQrcode qrcode, String name,HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long accountsId = UserUtils.getmpaccounts(request);
                try {
                    Conds countConds = new Conds();
                    countConds.equal("t.del_flag", 0);
                    int count = wxQrcodeService.count(countConds);
                    JSONObject wxObj = wxQrcodeUtil.createLimitQrcode(accountsId, Long.valueOf(count));
                    if (wxObj.containsKey("ticket")) {
                        qrcode.setTicket(wxObj.getString("ticket"));
                    }
                    qrcode.setId(null);
                    String tempTicket = qrcode.getTicket();
                    qrcode.setCreateBy(UserUtils.getUser().getId());
                    qrcode.setUpdateBy(UserUtils.getUser().getId());
                    qrcode.setSceneId(String.valueOf(count));
                    qrcode.setBindId(0L);
                    qrcode.setDelFlag(false);
                    wxQrcodeService.save(qrcode);
                    QrcodeDown.downPicture(request, response, tempTicket, name);
                } catch (Exception e) {
                    e.printStackTrace();
                }
    }


    //列表页面
    @RequiresPermissions(value = WXQRCODE_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);
        return "wxQrcode/wxQrcodelist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = WXQRCODE_VIEW)
    @RequestMapping(value = "/form",method = {RequestMethod.GET,RequestMethod.POST})
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            WxQrcode wxQrcode = wxQrcodeService.fetchById(id);
            model.addAttribute("data", wxQrcode);

        }
        return "wxQrcode/wxQrcodeform";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = WXQRCODE_EDIT)
    @RequestMapping(value = "/pform",method = {RequestMethod.GET,RequestMethod.POST})
    public String pform(HttpServletRequest request, String id, Model model) {
        return "wxQrcode/wxQrcodePform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = WXQRCODE_EDIT)
    @RequestMapping(value = "/formData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject formData(WxQrcode wxQrcode, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (wxQrcode != null && wxQrcode.getId() != null) {
                wxQrcode.setUpdateBy(UserUtils.getUser().getId());
                wxQrcodeService.update(wxQrcode);
                rtnJson.put("errorNo", 0);
            } else {
                Long sceneId = wxQrcodeUtil.getSceneId(accountsId);
                wxQrcode.setSceneId(String.valueOf(sceneId));
                wxQrcode.setAccountsId(accountsId);
                wxQrcode.setDelFlag(false);
                wxQrcode.setAccountsId(UserUtils.getmpaccounts(request));
                wxQrcode.setCreateBy(UserUtils.getUser().getId());
                wxQrcode.setUpdateBy(UserUtils.getUser().getId());

                JSONObject wxObj = wxQrcodeUtil.createLimitQrcode(accountsId, sceneId);
                if (wxObj.containsKey("ticket")) {
                    wxQrcode.setTicket(wxObj.getString("ticket"));
                    wxQrcodeService.save(wxQrcode);
                    rtnJson.put("errorNo", 2);
                } else {
                    rtnJson.put("errorNo", 1);
                }


            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = WXQRCODE_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, WxQrcode wxQrcode, HttpServletRequest request, @RequestParam(required = false) String isempty) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountsId);
        if (!StringUtils.isEmpty(wxQrcode.getType())) {
            if (!wxQrcode.getType().equals("-1")) {
                conds.equal("t.type", wxQrcode.getType());
            }
        }
        if (!StringUtils.isEmpty(isempty) && isempty.equals("1")) {
            conds.isNull("t.bind_id");
        }

        Sort sort = new Sort("t.create_time", OrderType.DESC);

        List<WxQrcodeVO> list = wxQrcodeService.fetchSearchByPageVO(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = wxQrcodeService.count(0L, conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

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


    //提交数据（新增、修改）
    @RequiresPermissions(value = WXQRCODE_EDIT)
    @RequestMapping(value = "/pformData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject pformData(WxQrcode wxQrcode, Model model, HttpServletRequest request, Long qty) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        String desc = wxQrcode.getDescription();
        String type = wxQrcode.getType();
        try {
            WxQrcode newCode = null;
            for (int i = 0; i < qty; i++) {
                newCode = new WxQrcode();
                Long sceneId = wxQrcodeUtil.getSceneId(accountsId);
                newCode.setSceneId(String.valueOf(sceneId));
                newCode.setAccountsId(accountsId);
                newCode.setDelFlag(false);
                newCode.setAccountsId(UserUtils.getmpaccounts(request));
                newCode.setCreateBy(UserUtils.getUser().getId());
                newCode.setUpdateBy(UserUtils.getUser().getId());
                newCode.setDescription(desc);
                newCode.setType(type);

                JSONObject wxObj = wxQrcodeUtil.createLimitQrcode(accountsId, sceneId);
                if (wxObj.containsKey("ticket")) {
                    newCode.setTicket(wxObj.getString("ticket"));
                    wxQrcodeService.save(newCode);
                }
            }
            rtnJson.put("errorNo", 2);
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = WXQRCODE_VIEW)
    @RequestMapping(value = "/exportQrcode",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public void exportQrcode(int iDisplayStart, int iDisplayLength, WxQrcode wxQrcode, HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) String isempty) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("application/zip");
        List<BufferedImage> buffImgs = new ArrayList<BufferedImage>();
        try{
            Long accountsId = UserUtils.getmpaccounts(request);
            Conds conds = new Conds();
            conds.equal("t.del_flag", Constants.DEL_FLAG_0);
            conds.equal("t.accounts_id", accountsId);
            if (!StringUtils.isEmpty(wxQrcode.getType())) {
                if (!wxQrcode.getType().equals("-1")) {
                    conds.equal("t.type", wxQrcode.getType());
                }
            }
            if (!StringUtils.isEmpty(isempty) && isempty.equals("1")) {
                conds.isNull("t.bind_id");
            }

            Sort sort = new Sort("t.create_time", OrderType.DESC);

            List<WxQrcodeVO> list = wxQrcodeService.fetchSearchByPageVO(conds, sort, iDisplayStart, iDisplayLength);
            String fileName= URLEncoder.encode("二维码信息", "UTF-8")+"-"+System.currentTimeMillis()/1000;
            response.setHeader("Content-Disposition", "attachment;fileName="+fileName+".zip");
            ZipOutputStream zos = new ZipOutputStream(response
                    .getOutputStream());
            int i=1;
            for(WxQrcodeVO obj:list){
                String uri=SystemConfig.p.getProperty("WX_MP_QRCODE_URI")+obj.getTicket();
                String name="";
                String type=obj.getType();
                if(type.equals("0")){
                    name=obj.getStoreName();
                }else if(type.equals("1")){
                    name=obj.getEmpName();
                }else if(type.equals("2")){
                    name=obj.getCarName();
                }
                if(StringUtils.isEmpty(name)){
                    name="未被绑定";
                }
                ZipEntry entry = new ZipEntry(name+String.valueOf(i) + ".png");
                // 设置压缩包的入口
                zos.putNextEntry(entry);
                zos.write(HttpURLConnectionUtil.getByteInputStreamByGet(uri));
                zos.flush();
                i++;
            }
            zos.close();
            response.getOutputStream().flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
            }
        }

    }

}
