package com.dgtly.wxportal.controller;

import com.dgtly.common.annotation.ApiNoCheckSign;
import com.dgtly.common.annotation.ApiPassToken;
import com.dgtly.common.annotation.Log;
import com.dgtly.common.constant.UserConstants;
import com.dgtly.common.core.controller.BaseController;
import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.core.domain.Ztree;
import com.dgtly.common.core.page.TableDataInfo;
import com.dgtly.common.enums.BusinessType;
import com.dgtly.common.exception.BusinessException;
import com.dgtly.common.utils.StringUtils;
import com.dgtly.framework.util.ShiroUtils;
import com.dgtly.system.domain.SysRole;
import com.dgtly.system.domain.SysUser;
import com.dgtly.wxportal.domain.HomeIconConfig;
import com.dgtly.wxportal.domain.RedisDbParam;
import com.dgtly.wxportal.domain.WxMagnet;
import com.dgtly.wxportal.service.IWxMagnetService;
import com.dgtly.wxportal.utils.JedisPoolUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * 菜单信息
 * 
 * @author dgtly
 */
@Controller
@RequestMapping("/wxportal/magnet")
public class WxMagnetController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(WxMagnetController.class);

    private String prefix = "wxportal/magnet";

    @Autowired
    private IWxMagnetService wxMagnetService;

    @RequiresPermissions("wxportal:magnet:view")
    @GetMapping()
    public String magnet()
    {
        return prefix + "/wxMagnet";
    }



    /**
     * 删除磁贴
     */
    @Log(title = "磁贴管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("wxportal:magnet:remove")
    @PostMapping("/remove/{magnetId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("magnetId") Long magnetId)
    {

        if (wxMagnetService.selectCountRoleMagnetByMagnetId(magnetId) > 0)
        {
            throw new BusinessException("磁贴已分配,不允许删除");
        }
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(wxMagnetService.deleteMagnetById(magnetId));
    }

    /**
     * 新增
     */
    @GetMapping("/add")
    public String add()
    {

        return prefix + "/add";
    }

    /**
     * 新增主题
     */
    @GetMapping("/themeAdd")
    public String themeAdd()
    {

        return prefix + "/themeAdd";
    }

    /**
     * 新增保存磁贴
     */
    @Log(title = "H5磁贴管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("wxportal:magnet:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated WxMagnet wxMagnet)
    {
        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(wxMagnetService.checkMagnetNameUnique(wxMagnet)))
        {
            return error("新增磁贴'" + wxMagnet.getMagnetName() + "'失败，磁贴名称已存在");
        }
        wxMagnet.setCreateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(wxMagnetService.insertMagnet(wxMagnet));
    }

    /**
     * 修改菜单
     */
    @GetMapping("/edit/{magnetId}")
    public String edit(@PathVariable("magnetId") Long magnetId, ModelMap mmap)
    {
        mmap.put("wxMagnet", wxMagnetService.selectMagnetById(magnetId));
        return prefix + "/edit";
    }

    /**
     * 修改保存磁贴信息
     */
    @Log(title = "磁贴信息管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("wxportal:magnet:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated WxMagnet wxMagnet)
    {
        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(wxMagnetService.checkMagnetNameUnique(wxMagnet)))
        {
            return error("修改磁贴'" + wxMagnet.getMagnetName() + "'失败，磁贴名称已存在");
        }
        wxMagnet.setUpdateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(wxMagnetService.updateMagnet(wxMagnet));
    }



    /**
     * 校验磁贴名称
     */
    @PostMapping("/checkMagnetNameUnique")
    @ResponseBody
    public String checkMagnetNameUnique(WxMagnet wxMagnet)
    {
        return wxMagnetService.checkMagnetNameUnique(wxMagnet);
    }



    /**
     * 选择磁贴页面
     */
    @GetMapping("/selectMagnetTree/{roleId}")
    public String selectMagnetTree(@PathVariable("roleId") Long roleId, ModelMap mmap)
    {
        mmap.put("roleId",roleId);
        return prefix + "/roletree";
    }

    /**
     * 上传图片
     */
    @GetMapping("/bgUpload")
    public String bgUpload(String bgUrl,String size,ModelMap mmap)
    {
        mmap.addAttribute("bgUrl",bgUrl);
        mmap.addAttribute("size",size);
        return prefix + "/bgUpload";
    }

    @RequiresPermissions("wxportal:magnet:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WxMagnet wxMagnet)
    {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        List<WxMagnet> magnetList = wxMagnetService.selectMagnetListByRole(wxMagnet,user);
        return getDataTable(magnetList);
    }

    /**
     * 配置首页新增图标配置
     */

    @Log(title = "首页图标配置", businessType = BusinessType.UPDATE)
    @PostMapping("/editHome")
    @ResponseBody
    public AjaxResult editHomeSave(HomeIconConfig homeIconConfig)
    {

        SysUser user = ShiroUtils.getSysUser();
        homeIconConfig.setCreateBy(user.getUserName());
        homeIconConfig.setUpdateBy(user.getUserName());
        wxMagnetService.updateHomeIcon(homeIconConfig);
       return  AjaxResult.success("保存成功!");
    }

    @PostMapping("/getHomeIconInfo")
    @ResponseBody
    public AjaxResult getHoemIconCongif() throws IOException {
        Map<String,Object> iconInfo= wxMagnetService.selectHomeIconInfoById();
        return  AjaxResult.success(iconInfo);
    }


    @Log(title = "redis缓存清除", businessType = BusinessType.UPDATE)
    @PostMapping("/cleanRedisByDb")
    @ResponseBody
    public AjaxResult cleanRedisByDb(@RequestBody RedisDbParam redisDbParam)
    {
        if(redisDbParam.getRedisDb().length==0){
            return AjaxResult.error(201,"redis库未指定！");
        }
        for (int db : redisDbParam.getRedisDb()) {
            try (Jedis jedis = JedisPoolUtil.getResource()) {
                jedis.select(db);
                if(StringUtils.isNotBlank(redisDbParam.getKeyName())){
                    jedis.del(redisDbParam.getKeyName());
                    log.info("清空库" + db+"下的"+redisDbParam.getKeyName());
                }
                else{
                    jedis.flushDB();
                    log.info("清空库" + db);
                }
            }
        }
        return AjaxResult.success("操作成功!");
    }



    /**
     * 加载角色磁贴列表树
     */
    @RequestMapping("/roleMagnetTreeData")
    @ResponseBody
    public List<Ztree> roleMagnetTreeData(SysRole role)
    {
        SysUser user = ShiroUtils.getSysUser();
        List<Ztree> ztrees = wxMagnetService.roleMagnetTreeData(role, user);
        return ztrees;
    }

    /**
     * 更新角色H5磁贴
     */
    @RequestMapping("/upRoleMagnet")
    @Log(title = "角色管理更新H5磁贴", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult upRoleMagnet(String roleId,String magnetIds)
    {
        wxMagnetService.upDateRoleMagnet(roleId, magnetIds);
        return success();
    }

}