package com.bofeng.controller;

import com.bofeng.Consts;
import com.bofeng.entity.Place;
import com.bofeng.entity.ScanParam;
import com.bofeng.entity.User;
import com.bofeng.service.PlaceService;
import com.bofeng.service.UserService;
import com.bofeng.wx.QrCodeService;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
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.Model;
import com.yvan.ModelOps;
import com.yvan.PageDb;
import com.yvan.freemarker.RedirectViewJs;
import com.yvan.mvc.Pd;
import lombok.Cleanup;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
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;
import java.util.Map;

@RestController
@RequiresPermissions(Consts.USER_TYPE_ADMIN)
public class AdminUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private QrCodeService qrCodeService;

    @Autowired
    private PlaceService placeService;

    @GetMapping(value = {"/admin/", "/admin/index.html"})
    public ModelAndView adminUserJump() {
        return new ModelAndView(new RedirectViewJs("/admin/user.html"));
    }

    @GetMapping("/admin/user.html")
    public ModelAndView adminUser() {
        return new ModelAndView("/admin/user.ftl");
    }

    @GetMapping("/admin/user.json")
    public Model<List<User>> getUser(PageDb pageDb) {
        return Model.newSuccess(pageDb, userService.selectAll(pageDb));
    }

    @GetMapping("/admin/get_place_role.json")
    public Model<Map<String, List<Map>>> getPlaceAndRole() {
        List<Place> placeList = placeService.selectAllPlace();
        Map<String, List<Map>> map = Maps.newLinkedHashMap();
        List<Map> places = Lists.newArrayList();
        for (int i = 0; i < placeList.size(); i++) {
            Place place = placeList.get(i);
            Map<String, Object> tempMap = Maps.newLinkedHashMap();
            tempMap.put("placeId", place.getPlaceId());
            tempMap.put("placeName", place.getPlaceName());
            places.add(tempMap);
        }
        map.put("place", places);

        List<Map> roles = Lists.newArrayList();
        Map<String, String> roleMapC = Maps.newLinkedHashMap();
        roleMapC.put("role", "C");
        roleMapC.put("roleName", "收银员");
        Map<String, String> roleMapA = Maps.newLinkedHashMap();
        roleMapA.put("role", "A");
        roleMapA.put("roleName", "场地管理员");
        Map<String, String> roleMapK = Maps.newLinkedHashMap();
        roleMapA.put("role", "W");
        roleMapA.put("roleName", "场地工作员");
        roles.add(roleMapK);
        roles.add(roleMapA);
        roles.add(roleMapC);
        map.put("role", roles);

        return Model.newSuccess(map);
    }

    @PostMapping("/admin/user_addnew.json")
    public ModelOps userInsert(@RequestBody User user) {

        val msg = userService.insert(user);
        if (Strings.isNullOrEmpty(msg)) {
            return ModelOps.newSuccess();
        }
        return ModelOps.newFail(msg);
    }

    @PostMapping("/admin/user_edit.json")
    public ModelOps userEdit(@RequestBody User user) {
        val msg = userService.updateById(user);
        if (Strings.isNullOrEmpty(msg)) {
            return ModelOps.newSuccess();
        }
        return ModelOps.newFail(msg);
    }

    //@PostMapping("/admin/user_bind_qr.png")
    @GetMapping(value = "/admin/user_bind_qr_png", produces = MediaType.IMAGE_PNG_VALUE)
    public void createBindQr(@Pd(name = "placeId") String placeId, HttpServletResponse response) throws WxErrorException, WriterException, IOException {
        val scanParam = new ScanParam();
        scanParam.setType(Consts.USER_TYPE_L1);
        scanParam.setPlaceId(placeId);
        scanParam.setHigherId("0");
        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());
    }


}
