package com.yami.shop.distribution.api.controller;


import cn.hutool.json.JSONObject;
import com.yami.shop.bean.app.dto.ResourcesInfoDto;
import com.yami.shop.bean.model.QrcodeTicket;
import com.yami.shop.common.bean.Domain;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.IdUtil;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.config.WxConfig;
import com.yami.shop.distribution.comment.service.DistributionUserService;
import com.yami.shop.service.AttachFileService;
import com.yami.shop.service.QrcodeTicketService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Objects;

/**
 * @author LGH
 */
@RestController
@RequestMapping("/p/distribution/qrCode")
@Api(tags="生成二维码接口")
@AllArgsConstructor
public class DistributionQrCodeController {


    private final QrcodeTicketService qrcodeTicketService;

    private final WxConfig wxConfig;

    private final IdUtil idUtil;

    private DistributionUserService distributionUserService;
    private AttachFileService attachFileService;
    private ShopConfig shopConfig;

    @GetMapping("/invitation")
    @ApiOperation(value="分销员邀请二维码", notes="分销员的邀请二维码带有cardNo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "scene", value = "二维码携带的参数", required = true, dataType = "String"),
            @ApiImplicitParam(name = "page", value = "获取二维码后跳转的页面", required = true, dataType = "String")
    })

    public ResponseEntity<FileSystemResource> qrCodeCreate(String page,String scene) throws WxErrorException {
    	File file = wxConfig.getWxMaService().getQrcodeService().createWxaCodeUnlimit(scene, page);
        return ResponseEntity
                .ok()
                .contentLength(file.length())
                .contentType(MediaType.IMAGE_PNG)
                .body(new FileSystemResource(file));
    }


    @GetMapping("/invitationPath")
    @ApiOperation(value="分销员邀请二维码", notes="分销员的邀请二维码带有cardNo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "要保存的内容", required = true, dataType = "String"),
            @ApiImplicitParam(name = "type", value = "类型：1. 小程序团购商品 2.小程序分销商品二维码", required = true, dataType = "Integer")
    })

    public ResponseEntity<ResourcesInfoDto> qrCodeCreatePath(String content, Integer type) throws WxErrorException {

        String page;
        if(Objects.equals(type, 1) || Objects.equals(type, 2)) {
            page = "pages/prod/prod";
        }else if(Objects.equals(type, 3))  {
            page = "pages/snapUpDetail/snapUpDetail";
        } else {
            throw new GlobalException("无法获取页面信息");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", type);
        jsonObject.put("content", content);

        String ticket = idUtil.nextShortId();
        QrcodeTicket qrcodeTicket = new QrcodeTicket();
        qrcodeTicket.setContent(jsonObject.toString());
        qrcodeTicket.setCreateTime(new Date());
        qrcodeTicket.setType(type);
        qrcodeTicket.setTicket(ticket);
        qrcodeTicket.setTicketUrl(page);
        qrcodeTicketService.save(qrcodeTicket);
        File file = wxConfig.getWxMaService().getQrcodeService().createWxaCodeUnlimit(ticket, page);
        ResourcesInfoDto resourcesInfoDto = null;
        try {
            //获取输入流
            FileInputStream fis = new FileInputStream(file);

            //新的 byte 数组输出流，缓冲区容量1024byte
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            //缓存
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            //改变为byte[]
            byte[] data = bos.toByteArray();
            //
            bos.close();
            String fileName = attachFileService.uploadFile(data,file.getName());
            Domain domain = shopConfig.getDomain();
            String resourcesUrl = domain.getResourcesDomainName();

            resourcesInfoDto = new ResourcesInfoDto();
            resourcesInfoDto.setResourcesUrl(resourcesUrl);
            resourcesInfoDto.setFilePath(fileName);
            return ResponseEntity.ok(resourcesInfoDto);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok().build();
    }

}
