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.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")
public class MarketController {

    public static final String MARKET_VIEW = "qy:market:view";
    public static final String MARKET_EDIT = "qy:market: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 accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "market/marketlist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = MARKET_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Long accountsId = UserUtils.getmpaccounts(request);
            Conds conds = new Conds();
            conds.equal("m.del_flag", Constants.DEL_FLAG_0);
            conds.equal("m.accounts_id", accountsId);
            conds.equal("m.id",id);
            List<MarketDto> list = marketService.fetchSearchByPageVo(conds, null, 0, 1,null,null,null);
            Market market =new Market();
            if(list!=null&&list.size()>0){
                market=list.get(0);
            }
            String actStartTimeStr = DateUtils.formatDate(market.getActstarttime(),"yyyy-MM-dd");
            String actEndTimeStr = DateUtils.formatDate(market.getActendtime(),"yyyy-MM-dd");
            String signStartTimeStr = DateUtils.formatDate(market.getSignstarttime(),"yyyy-MM-dd");
            String signEndTimeStr = DateUtils.formatDate(market.getSignendtime(),"yyyy-MM-dd");
            model.addAttribute("actStartTimeStr",actStartTimeStr);
            model.addAttribute("actEndTimeStr",actEndTimeStr);
            model.addAttribute("signStartTimeStr",signStartTimeStr);
            model.addAttribute("signEndTimeStr",signEndTimeStr);
            model.addAttribute("data", market);
        }
        return "market/marketform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = MARKET_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Market market, Model model, HttpServletRequest request,String actStartTimeStr,String actEndTimeStr,String signStartTimeStr,String signEndTimeStr) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            market.setActstarttime(StringUtils.isEmpty(actStartTimeStr)?null:DateUtils.parseDate(actStartTimeStr));
            market.setActendtime(StringUtils.isEmpty(actEndTimeStr)?null:DateUtils.parseDate(actEndTimeStr));
            market.setSignstarttime(StringUtils.isEmpty(signStartTimeStr)?null:DateUtils.parseDate(signStartTimeStr));
            market.setSignendtime(StringUtils.isEmpty(signEndTimeStr)?null:DateUtils.parseDate(signEndTimeStr) );
            if (market != null && market.getId() != null) {
                market.setUpdateBy(UserUtils.getUser().getId());
                marketService.update(market);
                rtnJson.put("errorNo", 0);
            } else {
                market.setNumber(codingruleUtils.getNumber(accountsId, Market.class.getName()));
                market.setAccountsId(accountsId);
                market.setDelFlag(false);
                market.setAccountsId(UserUtils.getmpaccounts(request));
                market.setCreateBy(UserUtils.getUser().getId());
                market.setUpdateBy(UserUtils.getUser().getId());
                marketService.save(market);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @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();
            conds.equal("m.del_flag", Constants.DEL_FLAG_0);
            conds.equal("m.accounts_id", accountsId);
            if (!StringUtils.isEmpty(market.getNumber())) {
                conds.like("m.number", market.getNumber());
            }
            if (!StringUtils.isEmpty(market.getName())) {
                conds.like("m.name", market.getName());
            }
            if (!StringUtils.isEmpty(market.getExplains())) {
                conds.like("m.explains", market.getExplains());
            }
            if (!StringUtils.isEmpty(market.getBrandName())) {
                conds.like("b.name", market.getBrandName());
            }
            if (!StringUtils.isEmpty(market.getStoreName())) {
                conds.like("s.name", market.getStoreName());
            }
            Sort sort = new Sort("m.create_time", OrderType.DESC);

            List<MarketDto> list = marketService.fetchSearchByPageVo(conds, sort, iDisplayStart, iDisplayLength,null,null,null);
            Integer counts = marketService.countVo(conds);
            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(HttpServletRequest request, HttpServletResponse response) {
        Long accountId = UserUtils.getmpaccounts(request);
        Sort sort = new Sort("create_time", OrderType.ASC);
        Conds conds = new Conds();
        conds.equal("del_flag", 0);
        conds.equal("accounts_id", accountId);
        List<Market> list = marketService.fetchSearchByPage(conds, sort, 0, 0);
        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 accountId = UserUtils.getmpaccounts(request);
        if (file == null) {
            return list(request, model);
        }
// 构造临时路径来存储上传的文件
        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);
    }

    @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) {
            }
        }
    }

}
