package com.cftech.activity.market.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.activity.market.model.Market;
import com.cftech.activity.market.model.MarketDto;
import com.cftech.activity.market.service.MarketService;
import com.cftech.activity.market.util.QRCodeUtil;
import com.cftech.base.codingrule.utils.CodingruleUtils;
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.core.util.DateFormatUtils;
import com.cftech.core.util.DateUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.sys.model.User;
import com.cftech.sys.security.UserUtils;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
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
 *
 * 权限字符串说明:
 * 查看:public static final String MARKET_VIEW = "qy:market:view"
 * 查看:public static final String MARKET_EDIT = "qy:market:edit"
 *
 * @author faye
 * @date: 2017-08-25 10:36
 */
@Slf4j
@Controller
@RequestMapping("/a/market/store")
public class StoreMarketController {

    public static final String MARKET_VIEW = "qy:market:store:view";
    public static final String MARKET_EDIT = "qy:market:store:edit";

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

    @Autowired
    private MarketService marketService;
    @Autowired
    private CodingruleUtils codingruleUtils;


    //列表页面
    @RequiresPermissions(value = MARKET_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model,Long activityId) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        model.addAttribute("activityId",activityId);
        return "market/storemarketlist";
    }


    //获取列表数据
    @RequiresPermissions(value = MARKET_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Market market, HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        try{
            Long accountsId = UserUtils.getmpaccounts(request);
            Conds conds = new Conds();

            User user=UserUtils.getStoreUser();
            String storeids=user.getStoreids();
            if(com.cftech.core.util.StringUtils.isNotBlank(storeids)){
                String[] arr=storeids.split(",");
                if(arr.length==0){
                    conds.in("t.storeid",new String[]{""});
                }else{
                    conds.in("t.storeid",arr);
                }
            }else{
                conds.equal("t.storeid","-1");
            }

            if (market.getId()!=null){
                conds.equal("t.id",market.getId());
            }
            if (!StringUtils.isEmpty(market.getStoreName())) {
                conds.like("t.storeName", market.getStoreName());
            }
            if (!StringUtils.isEmpty(market.getName())) {
                conds.like("t.name", market.getName());
            }
            List<MarketDto> list = marketService.fetchActByBelong(conds, null, iDisplayStart, iDisplayLength,null,null,null,false,null);
            Integer counts = marketService.countActByBelong(conds,null,null,null,false);
            rtnJson.put("iTotalRecords", counts);
            rtnJson.put("iTotalDisplayRecords", counts);
            rtnJson.put("aaData", list);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return rtnJson;
    }

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

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = MARKET_VIEW)
    public void exportExcel(Market market,HttpServletRequest request, HttpServletResponse response) {
        Long accountId = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("create_time", OrderType.ASC);
        Conds conds = new Conds();
        if (market.getId()!=null){
            conds.equal("t.id",market.getId());
        }
        if (!StringUtils.isEmpty(market.getStoreName())) {
            conds.like("t.storeName", market.getStoreName());
        }
        if (!StringUtils.isEmpty(market.getName())) {
            conds.like("t.name", market.getName());
        }
        List<MarketDto> list = marketService.fetchActByBelong(conds, null, 0, 0,null,null,null,false,null);
        ExcelKit.$Export(Market.class, response).toExcel(list, "市场活动信息");
    }

    @RequestMapping("/templateExcel")
    @RequiresPermissions(value = MARKET_VIEW)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        ExcelKit.$Export(Market.class, response).toExcel(null, "市场活动信息");
    }

    @RequestMapping("/importExcel")
    @RequiresPermissions(value = MARKET_EDIT)
    public String importExcel(HttpServletRequest request, MultipartFile file, Model model,Long id) {
        Long accountId = UserUtils.getmpaccounts(request);
        if (file == null) {
            return list(request, model,id);
        }
// 构造临时路径来存储上传的文件
        String uploadPath = System.getProperty("java.io.tmpdir");
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        String fileName = file.getOriginalFilename();
        String filePath = uploadPath + File.separator + fileName;
        File storeFile = new File(filePath);
        try {
            file.transferTo(storeFile);
            ExcelKit.$Import().readExcel(storeFile, rowData -> {
                if (!StringUtils.isEmpty(rowData.get(0))) {
                    Market market = new Market();
                    market.setAccountsId(accountId);
                    market.setNumber(rowData.get(0));
                    market.setName(rowData.get(1));
                    market.setExplains(rowData.get(2));
                    market.setBelong(rowData.get(3));
                    market.setType(rowData.get(4));
                    market.setContent(rowData.get(5));
                    market.setStoreid(!StringUtils.isEmpty(rowData.get(6))?Long.valueOf(rowData.get(6)):null);
                    market.setQrcode(rowData.get(7));
                    market.setActstarttime(DateFormatUtils.getDateFormat(rowData.get(8)));
                    market.setActendtime(DateFormatUtils.getDateFormat(rowData.get(9)));
                    market.setSignstarttime(DateFormatUtils.getDateFormat(rowData.get(10)));
                    market.setSignendtime(DateFormatUtils.getDateFormat(rowData.get(11)));
                    market.setSmallimg(rowData.get(12));
                    market.setImg(rowData.get(13));
                    marketService.save(market);
                }
            });
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return list(request, model,id);
    }

    @RequestMapping("/exportSignCode")
    @RequiresPermissions(value = MARKET_VIEW)
    @ResponseBody
    public void exportSignCode(Long id,HttpServletResponse response,HttpServletRequest request){
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("application/zip");
        String activityName="活动签到二维码";
        List<BufferedImage> buffImgs = new ArrayList<BufferedImage>();
        try{
            Market market=marketService.fetchById(id);
            if(market!=null){
                activityName=market.getName();
            }
            String path = request.getContextPath();
            String purl = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/"+"static/mp/dc/service/activity-detail.html?appid="+appid+"&actId="+id+"&isenroll=1&issign=1";
            Conds conds=new Conds();
            conds.equal("t.id",id);
            List<MarketDto> list = marketService.fetchActByBelong(conds, null, 0, 0,null,null,null,false,null);
            for(MarketDto obj:list){
                String formUrl=purl+"&storeId="+obj.getStoreid();
               BufferedImage img= QRCodeUtil.createImage(formUrl,"",true);
               buffImgs.add(img);
            }
            String fileName= URLEncoder.encode(activityName, "UTF-8")+"-"+System.currentTimeMillis()/1000;
            response.setHeader("Content-Disposition", "attachment;fileName="+fileName+".zip");
            ZipOutputStream zos = new ZipOutputStream(response
                    .getOutputStream());
            int i = 0;
            for (BufferedImage buf : buffImgs) {
                ZipEntry entry = new ZipEntry("门店-"+ list.get(i).getStoreName()+i + ".jpg");
                // 设置压缩包的入口
                zos.putNextEntry(entry);
                JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(zos);
                en.encode(buf);
                zos.flush();
                i++;
            }
            zos.close();
            // MatrixToImageWriter.writeToStream(bitMatrix, "jpeg",
            // getResponse()
            // .getOutputStream());
            response.getOutputStream().flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
            }
        }
    }

}
