package com.platform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.platform.annotation.CanUserUpdateRecord;
import com.platform.entity.BrandEntity;
import com.platform.entity.GoodsEntity;
import com.platform.entity.Result;
import com.platform.entity.SysUserBrand;
import com.platform.service.BrandService;
import com.platform.service.GoodsService;
import com.platform.service.custom.MySysUserBrandService;
import com.platform.service.custom.TmBrandTypeService;
import com.platform.service.impl.ZhiHouseService;
import com.platform.utils.*;
import com.platform.vo.BrandBindUserVo;
import com.platform.vo.BrandRequestVo;
import com.platform.vo.BrandRspVo;
import com.platform.vos.CurrentUserLoginVo;
import com.platform.vos.TbUser;
import com.platform.xss.SQLFilter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.bouncycastle.jcajce.provider.symmetric.DES;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Controller
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-19 17:59:15
 */
@Api(tags = "管理后台店铺操作相关接口")
@RestController
@RequestMapping("brand")
@Slf4j
public class BrandController extends AbstractController{
    @Autowired
    private BrandService brandService;

    @Autowired
    private ZhiHouseService zhiHouseService;

    @Autowired
    private GoodsService goodsService;


    @Autowired
    private TmBrandTypeService tmBrandTypeService;

    @Autowired
    private MySysUserBrandService mySysUserBrandService;

    @Value("${scenePath}")
    private String scenePath;

    /**
     * 用户绑定品牌
     */
    @ApiOperation(value = "用户绑定品牌")
    @PostMapping("/bindUser")
    public Result bindUser(@ApiParam(name = "BrandBindUserVo对象", value = "传入json格式", required = true)
                          @RequestBody BrandRequestVo brandRequestVo) {
        if(brandRequestVo == null || brandRequestVo.getBrandId() == null){
            return Result.failure("brandId入参缺失");
        }
        brandService.bindUsers(brandRequestVo.getBrandId(),brandRequestVo.getBrandList());

        return Result.success();
    }




    /**
     * 查看列表
     */
    @GetMapping("/brandTypeList")
    public Result brandTypeList() {
        Map<String , Object> map = new HashMap<>();
        map.put("list" , tmBrandTypeService.getAllList());
        return Result.success(map);
    }


    /**
     * 店铺绑定情况列表 Long pageNum , Long pageSize , String key , long deptId , Integer bindStatus
     */
    @ApiOperation(value = "店铺绑定情况列表")
    @GetMapping("/brandBindList")
    public Result brandBindList(@RequestParam(name = "page") long page,@RequestHeader String token,
                           @RequestParam(name = "limit") long limit,String order,String sidx,
                           String sceneName,String brandName,Integer type,Integer livestreamStatus) {
        //log.info("开始刷新列表..........."+System.currentTimeMillis());
        Long userId = null;
        //如果不是超级管理员，则只能查询本部门及子部门数据
        List<Long> roleIdList = getUser().getRoleIdList();
        if (!roleIdList.contains(1L) && !roleIdList.contains(5L)  ) {
            // 公司员工只能看到已经绑定自身为主播的数据
            if (roleIdList.contains(8L) || roleIdList.contains(9L)) {
                userId = getUserId();
            }else{
                if(ObjectUtils.isEmpty(getUser().getCompanyId())){
                    return Result.failure("该账号未绑定公司！");
                }
            }
        }
        String orderBy = null;
        if(!StringUtils.isEmpty(sidx) && !StringUtils.isEmpty(order)){
            orderBy = SQLFilter.humpToLine(sidx) + " "+ order;
        }
        IPage<BrandEntity> resultPage = brandService.queryBrandBindList(page , limit , sceneName , brandName,
                getDeptId() ,type,userId,livestreamStatus,orderBy);
        if(null == resultPage){
            return Result.failure("获取店铺绑定列表失败");
        }
        List<BrandRspVo> rspBrandList = resultPage.getRecords().parallelStream().map(brandEntity -> {
            BrandRspVo brandRspVo = new BrandRspVo();
            BeanUtils.copyProperties(brandEntity,brandRspVo);
            List<SysUserBrand> brandBindUserIdList = mySysUserBrandService.getBrandBindUserIdList(brandEntity.getId());
            List<Long> userIds = brandBindUserIdList.parallelStream().map(SysUserBrand::getUserId).collect(Collectors.toList());
            if(userIds.size() >0){
                List<String> nameList = zhiHouseService.getBindUserNameList(userIds,token);
                if (!CollectionUtils.isEmpty(nameList)) {
                    brandRspVo.setBindShowerNameList(nameList.stream().collect(Collectors.joining(";")));
                }
            }
            JSONObject jsonObject = zhiHouseService.queryBySceneNum(brandEntity.getSceneNum(),token);
            if(!ObjectUtils.isEmpty(jsonObject)){
                brandRspVo.setSceneName(jsonObject.getString("sceneName"));
                brandRspVo.setSceneUrl(jsonObject.getString("webSite"));
            }
            return brandRspVo;
        }).collect(Collectors.toList());

        //log.info("结束刷新列表..........."+System.currentTimeMillis());
        return Result.success(PageUtilsPlus.page(rspBrandList,resultPage));
    }

    /**
     * 查看信息
     */
    @PostMapping("/info")
    public Result info(@RequestBody BrandEntity brandEntity,@RequestHeader String token) {
        if(ObjectUtils.isEmpty(brandEntity.getId())){
            return Result.failure("参数有误！");
        }
        BrandEntity brand = brandService.queryObject(brandEntity.getId().intValue());
        BrandRspVo brandRspVo = new BrandRspVo();
        BeanUtils.copyProperties(brand,brandRspVo);
        JSONObject jsonObject = zhiHouseService.queryBySceneNum(brand.getSceneNum(),token);
        if(!ObjectUtils.isEmpty(jsonObject)){
            brandRspVo.setSceneUrl(jsonObject.getString("webSite"));
            brandRspVo.setSceneName(jsonObject.getString("sceneName"));
        }
        return Result.success( brandRspVo);
    }



    /**
     * 保存
     */
    @CanUserUpdateRecord
    @RequestMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody BrandEntity params,@RequestHeader String token) {
        if(ObjectUtils.isEmpty(params.getSceneNum())){
            return Result.failure("场景码为空！");
        }
        JSONObject jsonObject = zhiHouseService.queryBySceneNum(params.getSceneNum(),token);
        if(ObjectUtils.isEmpty(jsonObject)){
            return Result.failure("场景码错误！");
        }

        try {
            // 判断直播间名称是否重复
            Map<String,Object> paramsMap = new HashMap<>();
            paramsMap.put("name",params.getName());
            List<BrandEntity> entities = brandService.queryList(paramsMap);
            if(!ObjectUtils.isEmpty(entities)){
                return Result.failure("直播间名称重复！");
            }
            BrandEntity brand = brandService.queryByScene(params.getSceneNum());
            if(!ObjectUtils.isEmpty(brand)){
                return Result.failure("该场景已经绑定直播间！");
            }
            brand = new BrandEntity();
            BeanUtils.copyProperties(params,brand);
            brand.setCreateUserId(getUserId());
            if (ObjectUtils.isEmpty(brand.getType())) {
                brand.setType(0);
            }
            // 生成直播间地址
            String liveRoomUrl = jsonObject.getString("webSite").replaceAll("smobile.html", "shop.html");
            if(getCompanyId() == null && jsonObject.get("companyId") !=null  ){
                brand.setCreateUserDeptId(jsonObject.getLong("companyId"));
            }
            brand.setLiveRoomUrl(liveRoomUrl);

            brandService.save(brand,true);
            //生成微信分享二维码
            brandService.generalWxShareQrCode(brand , true);
            brand.setToken(token);
            brandService.sendDataToApi(brand);
            zhiHouseService.generateDefaultLiveRoom(params.getSceneNum(),true);
        } catch (BeansException e) {
            e.printStackTrace();
            return Result.failure(ObjectUtils.isEmpty(e.getMessage())?"该场景已经绑定直播间！":e.getMessage());
        }
        return Result.success("新增商铺成功",null);
    }

    /**
     * 修改
     */
    @CanUserUpdateRecord
    @PostMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public Result update(@RequestBody BrandEntity brand,@RequestHeader String token) {
        if(ObjectUtils.isEmpty(brand.getId())){
            return Result.failure("id 为空！");
        }
        BrandEntity oldDbBrand = brandService.queryObject(brand.getId().intValue());
        if(ObjectUtils.isEmpty(oldDbBrand)){
            log.error("获取数据失败:{}",brand.getId());
            return Result.failure("获取数据失败！");
        }
        // 判断直播间名称是否重复
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("name",brand.getName());
        List<BrandEntity> entities = brandService.queryList(paramsMap);
        if (!ObjectUtils.isEmpty(entities) && entities.get(0).getId().compareTo(brand.getId()) != 0) {
            return Result.failure("场景名称重复！");
        }
        //上送的场景码和数据库的不一致，说明场景码数据有变更
        if (!org.apache.commons.lang3.StringUtils.equals(brand.getSceneNum(), oldDbBrand.getSceneNum())
                || org.apache.commons.lang3.StringUtils.isBlank(oldDbBrand.getShareWxQrCode())) {
            //场景码有变更 将新场景的分享二维码更新
            String wxShareQrCodeUrl = brandService.generalWxShareQrCode(brand, false);
            brand.setShareWxQrCode(wxShareQrCodeUrl);
            JSONObject jsonObject = zhiHouseService.queryBySceneNum(brand.getSceneNum(),token);
            if(ObjectUtils.isEmpty(jsonObject)){
                return Result.failure("场景码错误！");
            }
            // 生成直播间地址
            String liveRoomUrl = jsonObject.getString("webSite").replaceAll("smobile.html", "shop.html");
            brand.setLiveRoomUrl(liveRoomUrl);
            if(getCompanyId() == null && jsonObject.get("companyId") !=null  ){
                brand.setCreateUserDeptId(jsonObject.getLong("companyId"));
            }
        }

        brand.setAppListPicUrl(brand.getAppListPicUrl());
        brandService.update(brand);
        brand.setToken(token);
        brandService.sendDataToApi(brand);
        return Result.success();
    }

    /**
     * 删除
     */
    @CanUserUpdateRecord
    @RequestMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public Result delete(@RequestBody Integer[] ids,@RequestHeader String token) {
        //log.info("开始删除..........."+System.currentTimeMillis());
        if(ObjectUtils.isEmpty(ids)){
            return Result.success();
        }
        Map<String,Object> brandIds = new HashMap<>();
        brandIds.put("idList",Arrays.asList(ids));
        List<BrandEntity> entities = brandService.queryList(brandIds);
        if(ObjectUtils.isEmpty(entities)){
            return Result.success();
        }


        // 判断场景是否绑定商品，如果绑定商品，不允许删除；
        Map<String, Object> params = new HashMap<>();
        params.put("brandIdList", Arrays.asList(ids));
        params.put("isDelete", 0);
        List<GoodsEntity> goodsEntities = goodsService.queryList(params);
        if (!ObjectUtils.isEmpty(goodsEntities)) {
            return Result.failure("该场景或者直播间已经设置了商品，不允许删除！");
        }
        //获取数据，推送给api
        Arrays.stream(ids).map(id-> brandService.queryObject(id)).forEach(entity->{
            entity.setToken(token);
            brandService.sendDataToApi(entity);
        });

        // 删除绑定关系
        mySysUserBrandService.deleteByBrandIds(ids);


        for (BrandEntity entity : entities) {
            zhiHouseService.generateDefaultLiveRoom(entity.getSceneNum(),false);
        }

        brandService.deleteBatch(ids);
       // log.info("结束删除..........."+System.currentTimeMillis());
        return Result.success();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public Result queryAll(@RequestBody Map<String, Object> params) {
        List<Long> roleIds = getUser().getRoleIdList();
        if(!roleIds.contains(5) && !roleIds.contains(1)){
            //通过部门ID过滤数据
            if(null == getDeptId()){
                return Result.success(new ArrayList<>());
            }
            params.put("deptIdList", getDeptId());
            if(roleIds.contains(8L)){
                params.put("createUserId",getUser().getId());
            }
        }

        List<BrandEntity> list = brandService.queryList(params);

        return Result.success(list);
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAllHot")
    public Result queryAllHot(@RequestBody Map<String, Object> params,@RequestHeader String token) throws Exception {
        //查询列表数据
        Query query = new Query(params);

        List<Long> roleIdList = getUser().getRoleIdList();
        if(!roleIdList.contains(1L) && !roleIdList.contains(5L)){
            params.put("idList", mySysUserBrandService.queryBrandIdList(getUserId()));
        }
        HttpRequestorUtil util = new HttpRequestorUtil();
        List<BrandEntity> list = brandService.queryList(params);
        String getResult = "";
        JSONArray array = null;
        JSONObject jsonObject = null;
        List<Map> resultList = new ArrayList<>();
        Map map = null;
        //场景码
        String sceneNum = "";
        //场景名称
        String sceneName = "";
        //热点类型
        String type = "";
        //热点中多个商品数组
        JSONArray pageArray = null;
        JSONObject pageObject = null;

        String scenePath = this.scenePath;
        String sceneData = ResourceUtil.getConfigByName("sceneData");

        for(BrandEntity entity : list){
            BrandEntity brand = brandService.queryObject(entity.getId().intValue());
            if(brand == null){
                continue;
            }
            sceneNum = brand.getSceneNum();

            JSONObject sceneEntity = zhiHouseService.queryBySceneNum(sceneNum,token);
            if(!ObjectUtils.isEmpty(sceneEntity)){
                sceneName = sceneEntity.getString("sceneName");
            }
            getResult = util.doGet(sceneData + "data/data" + sceneNum + "/hot.json");
            if(StringUtils.isEmpty(getResult)){
                continue;
            }
            array = JSONObject.parseArray(getResult);

            for (int i = 0; i < array.size(); i++) {
                map = new HashMap();
                map.put("brandId", brand.getId());
                map.put("brandName", brand.getName());
                map.put("sceneName", sceneName);
                map.put("sceneNum", sceneNum);

                jsonObject = array.getJSONObject(i);
                map.put("hotName", jsonObject.getString("label"));
                map.put("sid", jsonObject.getString("sid"));

                if(jsonObject.containsKey("media")){
                    type = jsonObject.getString("media").replace("\"", "").replace("[", "").replace("]", "");
                    if("photo".equals(type)){
                        map.put("hotData", sceneData + "images/images" + sceneNum + "/hot" + jsonObject.getString("sid") +".jpg");
                    }

                    if("audio".equals(type)){
                        map.put("hotData", sceneData + "images/images" + sceneNum + "/hot" + jsonObject.getString("sid") +".mp3");
                    }

                    if("video".equals(type)){
                        map.put("hotData", sceneData + "images/images" + sceneNum + "/hot" + jsonObject.getString("sid") +".mp4");
                    }
                }

                map.put("pageSid", "");
                map.put("pageName", "");

                //获取热点中卡夹的内容
                pageArray = jsonObject.getJSONArray("pages");
                if(pageArray != null && pageArray.size() > 0){
                    for (int j = 0; j < pageArray.size(); j++) {
                        //有卡夹，创建新的map添加到list
                        map = new HashMap();
                        map.put("brandName", brand.getName());
                        map.put("sceneName", sceneName);
                        map.put("sceneNum", sceneNum);
                        map.put("hotName", jsonObject.getString("label"));
                        map.put("sid", jsonObject.getString("sid"));

                        pageObject = pageArray.getJSONObject(j);
                        map.put("pageSid", pageObject.getString("sid"));
                        map.put("pageName", pageObject.getString("label"));
                        if(pageObject.containsKey("media")){
                            type = pageObject.getString("media").replace("\"", "").replace("[", "").replace("]", "");
                            if("photo".equals(type)){
                                map.put("hotData", sceneData + "images/images" + sceneNum + "/hot" + jsonObject.getString("sid") + "_" + pageObject.getString("sid") +".jpg");
                            }

                            if("audio".equals(type)){
                                map.put("hotData", sceneData + "images/images" + sceneNum + "/hot" + jsonObject.getString("sid") + "_" + pageObject.getString("sid") +".mp3");
                            }

                            if("video".equals(type)){
                                map.put("hotData", sceneData + "images/images" + sceneNum + "/hot" + jsonObject.getString("sid") + "_" + pageObject.getString("sid") +".mp4");
                            }
                        }
                        resultList.add(map);
                    }
                    continue;
                }

                resultList.add(map);
            }

        }

        List<Map> page = PageUtils.startPage(resultList, query.getPage(), query.getLimit());
        //分页后查询热点关联的商品，减少查询次数
        GoodsEntity goodsEntity = null;
        StringBuilder goodsNames = null;
        StringBuilder goodsId = null;
        String origin = ResourceUtil.getConfigByName("origin");
        if(page != null){

            for(Map mapData : page){
                JSONObject post = new JSONObject();
                post.put("hotId", mapData.get("sid"));
                post.put("pageSid", mapData.get("pageSid"));
                post.put("origin", origin);
                String result = util.postJson(scenePath + "hot/shop/findGoodIdByHotId", post.toString(), "POST");
                JSONObject object = JSON.parseObject(result);

                mapData.put("goodsId", "");
                mapData.put("goodsNames", "");
                if(object.getIntValue("code") == 0){
                    array = object.getJSONArray("data");
                    if(array.size() > 0){
                        goodsEntity = goodsService.queryObject(array.getJSONObject(0).getIntValue("goodId"));
                        if(goodsEntity != null){
                            mapData.put("goodsId", goodsEntity.getId());
                            mapData.put("goodsNames", goodsEntity.getName());
                        }
                    }
                }
            }
        }

        PageUtils pageUtil = new PageUtils(page, resultList.size(), query.getLimit(), query.getPage());
        return Result.success( pageUtil);
    }

    /**
     * 保存热点与商品关联
     */
    @CanUserUpdateRecord
    @RequestMapping("/saveGoodsHot")
    public Result saveGoodsHot(@RequestBody Map<String, Object> params) throws Exception {
        String scenePath = this.scenePath;
        String origin = ResourceUtil.getConfigByName("origin");

        HttpRequestorUtil util = new HttpRequestorUtil();

        JSONObject post = new JSONObject();
        post.put("hotId", params.get("sid"));
        post.put("sceneNum", params.get("sceneNum"));
        post.put("goodsIds", params.get("goodsIds"));
        post.put("pageSid", params.get("pageSid"));
        post.put("origin", origin);
        String result = util.postJson(scenePath + "hot/shop/saveHotShop", post.toString(), "POST");
        JSONObject object = JSON.parseObject(result);

        if(object.getIntValue("code") == 0){
            return Result.success();
        }

        return Result.failure("添加商品与热点关联失败");
    }

    /**
     * 删除热点商品关联
     */
    @CanUserUpdateRecord
    @RequestMapping("/deleteGoodsHot")
    public Result deleteGoodsHot(@RequestBody Map<String, Object> params) throws Exception {
        String scenePath = this.scenePath;
        String origin = ResourceUtil.getConfigByName("origin");

        HttpRequestorUtil util = new HttpRequestorUtil();

        JSONObject post = new JSONObject();
        post.put("hotId", params.get("sid"));
        post.put("pageSid", params.get("pageSid"));
        post.put("origin", origin);
        String result = util.postJson(scenePath + "hot/shop/deleteGoodsHot", post.toString(), "POST");
        JSONObject object = JSON.parseObject(result);

        if(object.getIntValue("code") == 0){
            return Result.success();
        }
        return Result.failure("删除热点商品关联失败");
    }
}
