package com.iformall.controller.app;

import com.iformall.annotation.SystemControllerLog;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.po.WxCouponChannel;
import com.iformall.domain.po.WxMerchant;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxCouponChannelMapper;
import com.iformall.mapper.WxMerchantMapper;
import com.iformall.service.QrCodeService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("wxAppinfo")
public class WxAppinfoController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxMerchantMapper wxMerchantMapper;

    @Autowired
    private QrCodeService qrCodeService;

    @Autowired
    private WxCouponChannelMapper wxCouponChannelMapper;

    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(150);

    @ApiOperation("门店二维码--二维码数据刷数据库")
    @GetMapping("/updateQrCode")
    public void updateQrCode(String p)throws ServletException, IOException {
        if("xlldxx".equals(p)) {
            String pageUrl = "pages/index/index";

            List<WxMerchant> list = wxMerchantMapper.findQrcodeEmptyList();
            logger.info("updateQrCode.count:"+list.size());
            for (WxMerchant merchant : list) {
                fixedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        String param = merchant.getWeappScene();
                        ResultData resultData = qrCodeService.uploadQrcode(merchant.getTenantId(), 1, pageUrl, param, 0, "", "", "店铺详情");
                        Map<String, String> map = (Map) resultData.data;
                        if(map!=null && map.get("url") !=null) {
                            String url = map.get("url");
                            merchant.setQrCode(url);
                            wxMerchantMapper.updateById(merchant);
                        }
                    }
                });
            }
        }
    }

    @ApiOperation("券二维码--二维码数据刷数据库")
    @GetMapping("/updateCouponQrCode")
    public void updateCouponQrCode(String p)throws ServletException, IOException {
        if("xlldxx".equals(p)){
            String pageUrl = "pages/index/index";

            List<WxCouponChannel> list = wxCouponChannelMapper.findQrcodeEmptyList();
            logger.info("updateCouponQrCode.count:"+list.size());
            for (WxCouponChannel couponChannel:list) {
                fixedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        String param = couponChannel.getWeappScene();
                        ResultData resultData = qrCodeService.uploadQrcode(couponChannel.getTenantId(),1,pageUrl,param,0,"","","卷");
                        Map<String,String> map = (Map)resultData.data;
                        if(map!=null && map.get("url") !=null) {
                            String url = map.get("url");
                            couponChannel.setQrCode(url);
                            wxCouponChannelMapper.updateById(couponChannel);
                        }
                    }
                });
            }
        }
    }

    @ApiOperation(value = "下载二维码", produces="application/json;charset=UTF-8", notes = "参数{\"name\":\"String\",\"pageUrl\":\"String\", \"sceneParam\":\"二维码参数\", \"type\":0:有限二维码，1：无限二维码,\"withText\":int(0:不带字, 1:加一行字，2:加两行字),\"text1\":\"String\",\"text2\":\"String\"}")
    @PostMapping("/downQrCode")
    @SystemControllerLog(description = "营销物料--下载二维码")
    public void downQrCode(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> params) throws MallinkException {
        logger.debug("[" + getIpAddr() + "] WxAppinfoController::downQrCode");
        String name = (String) params.get("name");
        String pageUrl = (String) params.get("pageUrl");
        String sceneParam = (String) params.get("sceneParam");
        int type = 1;
        try {
            type = (int) params.get("type");
        } catch (Exception e) {
            type = 1;
        }

        int withText = 0;
        try {
            withText = (int) params.get("withText");
        } catch (Exception e) {
            withText = 0;
        }
        String text1 = (String) params.get("text1");
        String text2 = (String) params.get("text2");
        if (StringUtils.isBlank(pageUrl)) {
            throw new MallinkException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "pageUrl不能为空");
        }
        try {
            qrCodeService.exportQrcode(request, response,
                    getTenantId(), type, pageUrl, sceneParam,
                    withText, text1, text2,
                    name);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new MallinkException(Result.ERROR, "下载异常");
        }
    }




}

