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.*;
import com.platform.service.BrandService;
import com.platform.service.GoodsService;
import com.platform.service.SceneService;
import com.platform.service.SysUserService;
import com.platform.service.custom.MySysUserBrandService;
import com.platform.service.custom.TmBrandTypeService;
import com.platform.utils.*;
import com.platform.vo.BrandBindUserVo;
import com.platform.vo.BrandRspVo;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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 SceneService sceneService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private DepartmentUtils departmentUtils;

    @Autowired
    private TmBrandTypeService tmBrandTypeService;

    @Autowired
    private MySysUserBrandService mySysUserBrandService;

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

    /**
     * 用户绑定品牌
     */
    @ApiOperation(value = "用户绑定品牌")
    @PostMapping("/bindUser")
    @RequiresPermissions("brand:list")
    public Result bindUser(@ApiParam(name = "BrandBindUserVo对象", value = "传入json格式", required = true)
                          @RequestBody List<BrandBindUserVo> brandBindUserVoList) {
        if(CollectionUtils.isEmpty(brandBindUserVoList)){
            return Result.failure("入参缺失");
        }
        brandService.bindUsers(brandBindUserVoList);

        return Result.success();
    }




    /**
     * 查看列表
     */
    @GetMapping("/brandTypeList")
    @RequiresPermissions("brand:list")
    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")
    @RequiresPermissions("brand:list")
    public Result brandBindList(@RequestParam(name = "page") long page,
                           @RequestParam(name = "limit") long limit,
                           String sceneName,String brandName,Integer type,Integer livestreamStatus) {
        List<Long> deptIdList = null;
        Long userId = null;
        //如果不是超级管理员，则只能查询本部门及子部门数据
        if (getUserId() != Constant.SUPER_ADMIN) {
            Long roleId = getUser().getRoleId();
            // 公司员工只能看到已经绑定自身为主播的数据
            if (roleId == 8) {
                userId = getUserId();
            }else{
                if(ObjectUtils.isEmpty(getUser().getDeptId())){
                    return Result.failure("该账号未绑定公司！");
                }
                // 公司管理员
                deptIdList = departmentUtils.getAllSubDeptIds(getUser().getDeptId());
            }
        }
        IPage<BrandEntity> resultPage = brandService.queryBrandBindList(page , limit , sceneName , brandName,
                deptIdList ,type,userId,livestreamStatus);
        if(null == resultPage){
            return Result.failure("获取店铺绑定列表失败");
        }
        List<BrandRspVo> rspBrandList = resultPage.getRecords().parallelStream().map(brandEntity -> {
            BrandRspVo brandRspVo = new BrandRspVo();
            BeanUtils.copyProperties(brandEntity,brandRspVo);
            List<String> nameList = mySysUserBrandService.getBindUserNameList(brandEntity.getId().longValue());
            if (!CollectionUtils.isEmpty(nameList)) {
                brandRspVo.setBindShowerNameList(nameList.stream().collect(Collectors.joining(";")));
            }
            SceneEntity scene = sceneService.queryByScene(brandEntity.getSceneNum());
            brandRspVo.setSceneName(scene.getName());
            brandRspVo.setSceneUrl(scene.getSceneUrl());
            return brandRspVo;
        }).collect(Collectors.toList());
        return Result.success(PageUtilsPlus.page(rspBrandList,resultPage));
    }

    /**
     * 查看信息
     */
    @PostMapping("/info")
    @RequiresPermissions("brand:info")
    public Result info(@RequestBody BrandEntity brandEntity) {
        if(ObjectUtils.isEmpty(brandEntity.getId())){
            return Result.failure("参数有误！");
        }
        BrandEntity brand = brandService.queryObject(brandEntity.getId().intValue());
        BrandRspVo brandRspVo = new BrandRspVo();
        BeanUtils.copyProperties(brand,brandRspVo);
        SceneEntity scene = sceneService.queryByScene(brand.getSceneNum());
        brandRspVo.setSceneUrl(scene.getSceneUrl());
        brandRspVo.setSceneName(scene.getName());
        return Result.success( brandRspVo);
    }



    /**
     * 保存
     */
    @CanUserUpdateRecord
    @RequestMapping("/save")
    @RequiresPermissions("brand:save")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody BrandEntity params) {
        if(ObjectUtils.isEmpty(params.getSceneNum())){
            return Result.failure("场景码为空！");
        }
        SceneEntity scene = sceneService.queryByScene(params.getSceneNum());
        if(ObjectUtils.isEmpty(scene)){
            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 = scene.getSceneUrl().replaceAll("smobile.html", "shop.html");
            brand.setLiveRoomUrl(liveRoomUrl);

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

    /**
     * 修改
     */
    @CanUserUpdateRecord
    @PostMapping("/update")
    @RequiresPermissions("brand:update")
    @Transactional(rollbackFor = Exception.class)
    public Result update(@RequestBody BrandEntity brand) {
        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);
            SceneEntity scene = sceneService.queryByScene(brand.getSceneNum());
            if(ObjectUtils.isEmpty(scene)){
                return Result.failure("场景码错误！");
            }
            // 生成直播间地址
            String liveRoomUrl = scene.getSceneUrl().replaceAll("smobile.html", "shop.html");
            brand.setLiveRoomUrl(liveRoomUrl);
        }

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

    /**
     * 删除
     */
    @CanUserUpdateRecord
    @RequestMapping("/delete")
    @RequiresPermissions("brand:delete")
    @Transactional(rollbackFor = Exception.class)
    public Result delete(@RequestBody Integer[] ids) {
        if(ObjectUtils.isEmpty(ids)){
            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->brandService.sendDataToApi(entity));

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

        brandService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public Result queryAll(@RequestParam Map<String, Object> params) {
        Long userId = getUserId();
        if(Constant.SUPER_ADMIN != userId){
            //通过部门ID过滤数据
            if(null == getDeptId()){
                return Result.success(new ArrayList<>());
            }
            params.put("deptIdList", departmentUtils.getAllSubDeptIds(getDeptId()));
        }

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

        return Result.success(list);
    }

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

        Long userId = getUserId();
        if(Constant.SUPER_ADMIN != userId){
            params.put("idList", mySysUserBrandService.queryBrandIdList(userId));
        }
        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();

            SceneEntity sceneEntity = sceneService.queryByScene(sceneNum);
            sceneName = sceneEntity.getName();

            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(@RequestParam 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(@RequestParam 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("删除热点商品关联失败");
    }

    /**
     * 跳转到场景编辑页面
     */
    @RequestMapping("/goSceneEditUrl")
    public void goSceneEditUrl(HttpServletRequest request, HttpServletResponse response){
        SysUserEntity sysUserEntity = sysUserService.queryObject((long)Constant.SUPER_ADMIN);
        String sceneUrl = request.getParameter("sceneUrl");
        if(!StringUtils.isEmpty(sceneUrl)){
            String sceneNum = sceneUrl.split("\\?m=")[1];
            sceneNum = sceneNum.substring(0, sceneNum.indexOf("&"));

            String scenePath = this.scenePath;
            String editHtml = ResourceUtil.getConfigByName("editHtml");
            String origin = ResourceUtil.getConfigByName("origin");
            HttpRequestorUtil util = new HttpRequestorUtil();

            JSONObject post = new JSONObject();
            post.put("phoneNum", sysUserEntity.getFdkkUser());
            post.put("password", PasswordUtils.decrypt(sysUserEntity.getFdkkPassword(), sysUserEntity.getFdkkUser(), PasswordUtils.getStaticSalt()));

            String result = util.postJson(scenePath + "login", post.toString(), "POST");
            JSONObject object = JSON.parseObject(result);

            if(object.getIntValue("code") == 0){
                String token = object.getJSONObject("data").getString("token");

                try{
                    //登录成功
                    response.sendRedirect(scenePath + editHtml + "?m=" + sceneNum + "&origin=" + origin +
                            "&t=" +System.currentTimeMillis() + "&token=" + token);
                    return;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
