package com.bofeng.wx.controller;

import com.bofeng.Consts;
import com.bofeng.entity.*;
import com.bofeng.service.*;
import com.bofeng.wx.QrCodeService;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.yvan.mvc.Pd;
import com.yvan.platform.JsonWapper;
import lombok.Cleanup;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
public class CustSubController {
    @Autowired
    private WxMpService mpService;

    @Autowired
    private QrCodeService qrCodeService;

    @Autowired
    private UserOpenService userOpenService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserPlaceService userPlaceService;

    @Autowired
    private PlaceService placeService;

    @Autowired
    private SubUserService subUserService;

    @GetMapping("/cust/sub.html")
    public ModelAndView sub(ModelMap model) {

        ParseCurrentOpenId wxToken = userService.currentWxUser();
        if (wxToken.isError()) return wxToken.getErrorResult();

        val currentUser = wxToken.getUser();
        List<SubUser> subUserList = subUserService.getSubUserByCurrentUserId(currentUser.getUserId());

        if (!Consts.USER_TYPE_SALE.equals(currentUser.getUserType()) || subUserList.size() <= 0) {
            model.put("title", "下级分销");
            model.put("message", "没有下级分销");
            model.put("isError", true);
            return new ModelAndView("/prompt/prompt.ftl", model);
        }


        val jw1 = new JsonWapper();
        jw1.set("subUserList", subUserList);

        model.put("subUserList", jw1);

        return new ModelAndView("/cust/sub.ftl", model);
    }

    @GetMapping("/cust/junior_qr.html")
    public ModelAndView juniorQr(@Pd(name = "userId") Long userId, @Pd(name = "placeId") Long placeId,
                                 ModelMap model) throws WxErrorException {
        UserPlace userPlace = userPlaceService.getByUserIdAndPlaceId(userId, placeId);
        Long higherId;
        if (userPlace.getHigherId() > 0) {
            higherId = userPlace.getHigherId();
        } else {
            higherId = userPlace.getUserId();
        }

        model.put("img", "/cust/junior_qr_png?userId=" + higherId + "&placeId=" + placeId);
        model.put("placeName", placeService.getById(placeId).getPlaceName());
        return new ModelAndView("/cust/junior_qr.ftl", model);
    }

    @GetMapping(value = "/cust/junior_qr_png", produces = MediaType.IMAGE_PNG_VALUE)
    public void juniorQrImg(@Pd(name = "userId") String userId, @Pd(name = "placeId") String placeId,
                            HttpServletResponse response) throws IOException, WxErrorException, WriterException {
        val scanParam = new ScanParam();
        scanParam.setType(Consts.USER_TYPE_L2);
        scanParam.setHigherId(userId);
        scanParam.setPlaceId(placeId);
        val ticket = qrCodeService.create(scanParam);
        @Cleanup ServletOutputStream outputStream = response.getOutputStream();
        BitMatrix matrix = new MultiFormatWriter().encode(ticket.getUrl(), BarcodeFormat.QR_CODE, 256, 256);
        MatrixToImageWriter.writeToStream(matrix, MediaType.IMAGE_PNG.getSubtype(), outputStream, new MatrixToImageConfig());
    }


    //获取所属场地列表视图
    @GetMapping("/cust/user_place_list.html")
    public ModelAndView userPlaceList(ModelMap model) {

        ParseCurrentOpenId wxToken = userService.currentWxUser();
        if (wxToken.isError()) return wxToken.getErrorResult();

        UserOpen userOpen = wxToken.getUserOpen();
        User user = wxToken.getUser();

        //查出所属场地列表
        List<Place> placeList = null;
        Long userId = userOpen.getUserId();
        if (Consts.USER_TYPE_SALE.equals(user.getUserType())) {

            placeList = placeService.getByUserId(userId);
        }
        JsonWapper jw = new JsonWapper();
        jw.set("placeList", placeList);
        model.put("placeList", jw);
        model.put("userId", userId);
        return new ModelAndView("/cust/user_place_list.ftl", model);
    }

}
