package com.jeequan.jeepay.mch.ctrl.merchant;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.DBApplicationConfig;
import com.jeequan.jeepay.core.model.DBWxMpConfig;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.db.entity.MchWxmpUser;
import com.jeequan.jeepay.db.entity.SysUserEntity;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 微信公众号提醒配置类
 *
 * @author zx
 *
 * @date 2021-10-15 09:15
 */
@RestController
@RequestMapping("/api/wxmp")
public class WxMpUserController extends CommonCtrl {

    @Autowired private MchInfoService mchInfoService;
    @Autowired private SysConfigService sysConfigService;
    @Autowired private MchWxmpUserService mchWxmpUserService;
    @Autowired private SysUserService sysUserService;
    @Autowired private SysUserMchStoreRelaService sysUserMchStoreRelaService;

    /**
     * @Author: zx
     * @Description: 商户创建微信公众号接收者的显示信息
     * @Date: 2021-10-15 09:15
    */
    @GetMapping("/getWxmpInfo")
    public ApiRes getWxmpInfo() {

        MchInfo mchInfo = mchInfoService.getById(getCurrentUser().getSysUser().getBelongInfoId());

        DBApplicationConfig applicationConfig = sysConfigService.getDBApplicationConfig();
        DBWxMpConfig wxMpConfig = sysConfigService.getDBWxMpConfig();
        if(wxMpConfig == null){
            throw new BizException("未正确配置微信公众号消息配置项");
        }

        String mchAuthRedirectUrl = StringUtils.isBlank(wxMpConfig.getMchAuthRedirectUrl()) ? DBWxMpConfig.DEFAULT_WX_AUTH_DOMAIN : wxMpConfig.getMchAuthRedirectUrl();

        JSONObject result = new JSONObject();
        String authUrl = DBWxMpConfig.mchAuthUrl
                .replace("{{mchAuthRedirectUrl}}", mchAuthRedirectUrl)
                .replace("{{mchNo}}", mchInfo.getMchNo())
                .replace("{{sysUserId}}", String.valueOf(getCurrentUser().getSysUserId()))
                .replace("{{appId}}", wxMpConfig.getWxAppId())
                .replace("{{paySiteUrl}}", applicationConfig.getPaySiteUrl());

        result.put("authQr", applicationConfig.genScanImgUrl(authUrl));
        result.put("authUrl", authUrl);
        result.put("wxmpQr", wxMpConfig.getWxmpUrl());

        return ApiRes.ok(result);
    }

    /**
     * @Author: zx
     * @Description: 微信公众号取消关注
     * @Date: 2021-10-15 09:15
     */
    @GetMapping("/unAuth")
    public ApiRes unAuth() {

        LambdaUpdateWrapper<MchWxmpUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MchWxmpUser::getMchNo, getCurrentMchNo());
        updateWrapper.set(MchWxmpUser::getSendStatus, MchWxmpUser.SEND_STATE_CLOSE);
        boolean updateResult = mchWxmpUserService.update(updateWrapper);
        if (!updateResult) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
        }

        return ApiRes.ok();
    }

    /**
     * @author: zx
     * @date: 2021-12-28 09:15
     * @describe: 微信公众号消息接收者列表
     */
    @PreAuthorize("hasAuthority('ENT_MCH_WXMP_USER_LIST')")
    @GetMapping
    public ApiRes pages() {

        String mchNo = getCurrentMchNo();
        SysUserEntity sysUserEntity = sysUserService.getById(getCurrentUser().getSysUserId());

        LambdaQueryWrapper<MchWxmpUser> gw = MchWxmpUser.gw();
        gw.eq(MchWxmpUser::getMchNo, mchNo);

        // 店员只能看自己的授权信息
        if (sysUserEntity.getUserType() == SysUser.UEST_TYPE_CASHIER) {
            gw.eq(MchWxmpUser::getSysUserId, sysUserEntity.getSysUserId());
        }
        // 店长只能看自己门店下的授权信息
        if (sysUserEntity.getUserType() == SysUser.UEST_TYPE_DIRECTOR) {
            List<String> storeIdList = getCurrentUser().getStoreIdList();
            Set<Long> sysUserIdSet = sysUserMchStoreRelaService.selectSysUserIdsByStoreIdList(storeIdList);
            gw.in(CollUtil.isNotEmpty(sysUserIdSet), MchWxmpUser::getSysUserId, sysUserIdSet);
        }

        if (StringUtils.isNotBlank(getValString("nickname"))) {
            gw.like(MchWxmpUser::getNickname, getValString("nickname"));
        }

        IPage<MchWxmpUser> page = mchWxmpUserService.page(getIPage(), gw);


        //返回数据
        return ApiRes.page(page);
    }

    /**
     * @author: zx
     * @date: 2021-12-28 09:15
     * @describe: 微信公众号消息接收者修改
     */
    @PreAuthorize("hasAuthority('ENT_MCH_WXMP_USER_EDIT')")
    @MethodLog(remark = "微信公众号消息接收者修改")
    @PutMapping("/{userId}")
    public ApiRes update(@PathVariable("userId") Long userId) {
        MchWxmpUser mchWxmpUser = getObject(MchWxmpUser.class);
        mchWxmpUser.setUserId(userId);

        MchWxmpUser dbRecord = mchWxmpUserService.getById(userId);
        if (!getCurrentMchNo().equals(dbRecord.getMchNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }

        SysUserEntity sysUserEntity = sysUserService.getById(getCurrentUser().getSysUserId());
        // 店员只能看自己的授权信息
        if (sysUserEntity.getUserType() == SysUser.UEST_TYPE_CASHIER && !dbRecord.getSysUserId().equals(sysUserEntity.getSysUserId())) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }
        // 店长只能看自己门店下的授权信息
        if (sysUserEntity.getUserType() == SysUser.UEST_TYPE_DIRECTOR) {
            List<String> storeIdList = getCurrentUser().getStoreIdList();
            Set<Long> sysUserIdSet = sysUserMchStoreRelaService.selectSysUserIdsByStoreIdList(storeIdList);
            if (!sysUserIdSet.contains(dbRecord.getSysUserId())) {
                return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
            }
        }

        if(!mchWxmpUserService.updateById(mchWxmpUser)) {
            return ApiRes.fail(ApiCodeEnum.SYSTEM_ERROR, "更新失败");
        }

        return ApiRes.ok();
    }

    /**
     * @author: zx
     * @date: 2021-12-28 09:15
     * @describe: 微信公众号消息接收者删除
     */
    @PreAuthorize("hasAuthority('ENT_MCH_WXMP_USER_DELETE')")
    @MethodLog(remark = "微信公众号消息接收者删除")
    @DeleteMapping("/{userId}")
    public ApiRes delete(@PathVariable("userId") Long userId) {
        MchWxmpUser dbRecord = mchWxmpUserService.getById(userId);
        if (!getCurrentMchNo().equals(dbRecord.getMchNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }

        SysUserEntity sysUserEntity = sysUserService.getById(getCurrentUser().getSysUserId());
        // 店员只能看自己的授权信息
        if (sysUserEntity.getUserType() == SysUser.UEST_TYPE_CASHIER && !dbRecord.getSysUserId().equals(sysUserEntity.getSysUserId())) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }
        // 店长只能看自己门店下的授权信息
        if (sysUserEntity.getUserType() == SysUser.UEST_TYPE_DIRECTOR) {
            List<String> storeIdList = getCurrentUser().getStoreIdList();
            Set<Long> sysUserIdSet = sysUserMchStoreRelaService.selectSysUserIdsByStoreIdList(storeIdList);
            if (!sysUserIdSet.contains(dbRecord.getSysUserId())) {
                return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
            }
        }

        if(mchWxmpUserService.removeById(userId)) {
            return ApiRes.ok();
        }

        return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_DELETE);
    }


}
