package com.hzs.system.sys.controller.manage;

import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.system.sys.ext.SysUserCountryExt;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.system.sys.dto.LoginUser;
import com.hzs.system.sys.service.ISysUserCountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户地区权限控制器
 *
 * @author hzs
 */
@RestController
@RequestMapping("/manage/user-country")
public class SysUserCountryController {

    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private ISysUserCountryService iSysUserCountryService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;

    /**
     * 获取用户地区权限列表
     *
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list() {
        List<SysUserCountryExt> list = iSysUserCountryService.queryUserCountry(SecurityUtils.getUserId());

        // 获取需要翻译的枚举翻译
        Map<Integer, String> transactionMap = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_COUNTRY);
        for (SysUserCountryExt sysUserCountryExt : list) {
            // 处理国家名称国际化
            String name = transactionMap.get(sysUserCountryExt.getPkTransaction());
            sysUserCountryExt.setName(StringUtils.isNotEmpty(name) ? name : sysUserCountryExt.getName());
        }
        return AjaxResult.success(list);
    }

    /**
     * 修改用户地区数据权限
     *
     * @param dataCountry 地区数据ID
     * @return
     */
    @Log(module = EOperationModule.HOME_PAGE, business = EOperationBusiness.CHANGE_COUNTRY, method = EOperationMethod.CHANGE)
    @PostMapping("/change/{dataCountry}")
    public AjaxResult change(@PathVariable("dataCountry") Integer dataCountry) {
        LoginUser loginUser = userTokenService.getLoginUser();

        if (iSysUserCountryService.checkUserCountry(loginUser.getUserId(), dataCountry) > 0) {
            loginUser.setDataCountry(dataCountry);
            // 修改地区数据权限，重新刷新缓存token内容
            userTokenService.refreshToken(loginUser);
            return AjaxResult.success();
        }

        return AjaxResult.error("管理员目前没有该地区数据权限");
    }

}
