package com.slodon.b2b2c.controller.live;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.*;
import com.slodon.b2b2c.dao.read.goods.GoodsReadMapper;
import com.slodon.b2b2c.enums.WxLiveGoodsEnum;
import com.slodon.b2b2c.enums.WxLiveUrlEnum;
import com.slodon.b2b2c.errors.WxCodeError;
import com.slodon.b2b2c.goods.example.GoodsExample;
import com.slodon.b2b2c.goods.pojo.Goods;
import com.slodon.b2b2c.live.dto.LiveGoodsInfoDto;
import com.slodon.b2b2c.live.example.LiveGoodsExample;
import com.slodon.b2b2c.live.pojo.LiveGoods;
import com.slodon.b2b2c.live.vo.LivesVO;
import com.slodon.b2b2c.model.live.LiveGoodsModel;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.util.ThumbnailsUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "admin-微信商品管理")
@RestController
@Slf4j
@RequestMapping("v3/live/seller/goods")
public class LiveGoodsController extends BaseController {

    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private LiveGoodsModel liveGoodsModel;
    @Resource
    private GoodsReadMapper goodsReadMapper;

    private String getToken() throws Exception {
        String appId = stringRedisTemplate.opsForValue().get("login_wx_mini_appid");
        String secret = stringRedisTemplate.opsForValue().get("login_wx_mini_appsecret");
        String access_token_resp = HttpClientUtil.httpGet(WxLiveUrlEnum.ACCESS_TOKEN_URL.getUrl() + appId + "&secret=" + secret);
        String access_token = JSON.parseObject(access_token_resp).getString("access_token");
        AssertUtil.notEmpty(access_token, "微信认证失败");
        System.out.println("结果access_token: "+access_token);
        return access_token;
    }

    @ApiOperation("商品添加并提审")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsIds", value = "商品Id集合，用逗号隔开", required = true, paramType = "query")
    })
    @PostMapping("/add")
    public JsonResult addGoodsCreate(HttpServletRequest request, String goodsIds) throws Exception {
        HashMap<String, String> resultMap = new HashMap<>();
        //获取token
        String access_token = getToken();
        Vendor vendor = UserUtil.getUser(request, Vendor.class);
        if (vendor == null || vendor.getVendorId() == null){
            return SldResponse.fail("获取商户id失败");
        }
        AssertUtil.notEmpty(goodsIds, "添加商品ID不能为空,请重试");
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setGoodsIdIn(goodsIds);
        List<Goods> goods = goodsReadMapper.listByExample(goodsExample);
        for (Goods good:goods) {
            addLiveGood(access_token, vendor, good);
        }
        return SldResponse.success(resultMap);
    }

    private void addLiveGood(String access_token, Vendor vendor, Goods good) throws Exception {
        LiveGoodsInfoDto liveGoodsInfoDto = new LiveGoodsInfoDto();
        liveGoodsInfoDto.setVendorId(String.valueOf(vendor.getVendorId()));
        String url = WxLiveUrlEnum.TEMP_UPLOAD.getUrl();
        url = url.replace("ACCESS_TOKEN", access_token).replace("TYPE","image");
        String mainImage = good.getMainImage();
        BufferedImage image = ImageIO.read(new File(mainImage));
//        BufferedImage image = ImageIO.read(new File("D:\\ytf\\coverImg.jpg"));
        BufferedImage bufferedImage = ThumbnailsUtils.resizeImageOne(image, 300, 300);
        String goodName = good.getGoodsName().length()>14?good.getGoodsName().substring(0,13):good.getGoodsName();
        File file = File.createTempFile(goodName, ".jpg");
        ImageIO.write(bufferedImage, "jpg", file);
        String result = FileUploadUtil.postUploadSSL(url, file, file.getName());
        JSONObject jsonObject = JSONObject.parseObject(result);
        liveGoodsInfoDto.setCoverImgUrl(jsonObject.getString("media_id"));
        liveGoodsInfoDto.setLocalGoodsId(String.valueOf(good.getGoodsId()));
        liveGoodsInfoDto.setName(goodName);
        liveGoodsInfoDto.setPrice(String.valueOf(good.getGoodsPrice()));
        liveGoodsInfoDto.setUrl("pages/index/index");
        Map map = new HashMap();
        map.put("goodsInfo",liveGoodsInfoDto);
        url = WxLiveGoodsEnum.ADD.getUrl()+ access_token;
        log.info("json: "+JSON.toJSONString(map));
        String reStr = null;
        reStr = HttpClientUtil.sendJsonPostNew(url, JSON.toJSONString(map));
        jsonObject = JSONObject.parseObject(reStr);
        String errCode = jsonObject.getString("errcode");
        if (!"0".equals(errCode)){
            log.warn("直播间商品添加失败原因："+reStr);
            throw new MallException("商品名称："+good.getGoodsName()+", 失败原因："+WxCodeError.WX_CODE.get(errCode));
        }
        liveGoodsInfoDto.setGoodsId(jsonObject.getInteger("goodsId"));
        liveGoodsInfoDto.setAuditId(jsonObject.getInteger("auditId"));

        liveGoodsModel.addGoodsCreate(liveGoodsInfoDto);
    }

    @ApiOperation("获取直播商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "直播商品名称", paramType = "query"),
            @ApiImplicitParam(name = "auditStatus", value = "直播商品状态", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("/list")
    public JsonResult<PageVO<LiveGoods>> getList(HttpServletRequest request, String name,Integer auditStatus) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);
        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        LiveGoodsExample example = new LiveGoodsExample();
        example.setName(name);
        //获取审核通过商品
        if (auditStatus != null && auditStatus == 2){
            example.setAuditStatus(2);
        }
        if (vendor != null && vendor.getVendorId() != null){
            example.setVendorId(String.valueOf(vendor.getVendorId()));
        }
        List<LiveGoods> livesList = liveGoodsModel.getLivesList(example, pager);
        livesList.stream().map(item->{
            item.setAuditStatusName(getLiveGoodsStatusName(item.getAuditStatus()));
            return item;
        }).collect(Collectors.toList());

        return SldResponse.success(new PageVO<>(livesList, pager));
    }

    @ApiOperation("获取绑定直播商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "直播商品名称", paramType = "query"),
            @ApiImplicitParam(name = "roomId", value = "直播间id", paramType = "query")
    })
    @GetMapping("/list/relation")
    public JsonResult<PageVO<LiveGoods>> getListRelation(HttpServletRequest request, String name, Integer roomId) {
        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        if (roomId == null || roomId == 0){
            return SldResponse.fail("直播间获取失败");
        }
        List<LiveGoods> livesList = liveGoodsModel.getListRelation(name,roomId);

        return SldResponse.success(new PageVO<>(livesList, pager));
    }
    private String getLiveGoodsStatusName(Integer liveStatus){
        switch (liveStatus){
            case 0: return "未审核";
            case 1: return "审核中";
            case 2: return "审核通过";
            case 3: return "审核失败";
            default:return "状态异常";
        }
    };

    @ApiOperation("删除直播间商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品ID", paramType = "query"),
    })
    @GetMapping("/wxDelLive")
    public JsonResult wxDelLiveGood(HttpServletRequest request,Integer goodsId) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveGoodsEnum.DEL.getUrl()+access_token;
            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(new HashMap<>().put("goodsId",goodsId)));
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                return SldResponse.fail(WxCodeError.WX_CODE.get(errCode));
            }
            liveGoodsModel.wxDelLiveGood(goodsId);
            return SldResponse.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("删除失败");
    }

    /**
     * 获取直播商品状态进行更新
     * @return
     */
    public boolean jobUpdateLiveGoodsType() {
        //获取需要修改的ids
        List<Integer> ids = liveGoodsModel.getLivesGoodsIds();
        //每次最多20个所以需要拆分
        List<List<Integer>> lists = new ArrayList<>();
        List<Integer> updateIds = new ArrayList<>();
        for (int i = 0; i <ids.size() ; i++) {
            updateIds.add(ids.get(i));
            //20个插入一组 或 最后一组不满20也插入
            if((i+1)%20==0 || i == ids.size()-1){
                lists.add(updateIds);
                updateIds = new ArrayList<>();
            }
        }

        try {
            String access_token = getToken();
            //校验
            String url = WxLiveGoodsEnum.GET_GOODS_WARE_HOUSE.getUrl()+access_token;
            for (List<Integer> i:lists) {
                Map m = new HashMap<>();
                m.put("goods_ids",i);
                String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(m));
                JSONObject jsonObject = JSONObject.parseObject(reStr);
                String errCode = jsonObject.getString("errcode");
                if (!"0".equals(errCode)){
                    log.warn("直播商品状态更新错误日志："+WxCodeError.WX_CODE.get(errCode));
                    continue;
                }
                //修改商品状态
                updateGoodsType(jsonObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private void updateGoodsType(JSONObject jsonObject) {
        JSONArray roomInfos = jsonObject.getJSONArray("goods");
        List<LiveGoods> liveGoodsList = new ArrayList<>();
        for (int i = 0; i < roomInfos.size(); i++) {
            JSONObject infosJSONObject = roomInfos.getJSONObject(i);
            LiveGoods liveGoods = new LiveGoods();
            liveGoods.setGoodsId(infosJSONObject.getInteger("goods_id"));
            liveGoods.setAuditStatus(infosJSONObject.getInteger("audit_status"));
            liveGoodsList.add(liveGoods);
        }
        liveGoodsModel.updateLivesGoodsType(liveGoodsList);
    }
}
