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

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jeequan.jeepay.agent.config.SystemYmlConfig;
import com.jeequan.jeepay.agent.ctrl.CommonCtrl;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.db.entity.MchAppEntity;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.service.impl.MchAppService;
import com.jeequan.jeepay.service.impl.MchInfoService;
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;

/**
 * 商户应用管理类
 *
 * @author zhuxiao
 *
 * @date 2021-06-16 09:15
 */
@RestController
@RequestMapping("/api/mchApps")
public class MchAppController extends CommonCtrl {

    @Autowired private MchAppService mchAppService;
    @Autowired private MchInfoService mchInfoService;
    @Autowired private SystemYmlConfig systemYmlConfig;
    @Autowired private IMQSender mqSender;

    /**
     * @Author: ZhuXiao
     * @Description: 应用列表
     * @Date: 9:59 2021/6/16
    */
    @PreAuthorize("hasAuthority('ENT_MCH_APP_LIST')")
    @GetMapping
    public ApiRes list() {
        MchAppEntity mchAppEntity = getObject(MchAppEntity.class);
        mchAppEntity.setAgentNo(getCurrentAgentNo());

        // app融合搜索，appId appName mchNo mchName
        mchAppEntity.addExt("unionSearchId", getValStringDefault("unionSearchId", ""));

        // 可查看自己和全部下级代理数据
        String currentAgentNo = getCurrentAgentNo();
        List<String> subAgentNoList = agentInfoService.queryAllSubAgentNo(currentAgentNo);
        // 自己和下级服务商
        if (CollUtil.isNotEmpty(subAgentNoList)){
            mchAppEntity.setSubAgentNoList(subAgentNoList);
        }

        IPage<MchAppEntity> pages = mchAppService.selectPage(getIPage(true), mchAppEntity);

        return ApiRes.page(pages);
    }

    /**
     * @Author: ZhuXiao
     * @Description: 新建应用
     * @Date: 10:05 2021/6/16
    */
    @PreAuthorize("hasAuthority('ENT_MCH_APP_ADD')")
    @MethodLog(remark = "新建应用")
    @PostMapping
    public ApiRes add() {
        MchAppEntity mchAppEntity = getObject(MchAppEntity.class);
        if (StringUtils.isEmpty(mchAppEntity.getMchNo())) {
            throw new BizException("商户号不能为空");
        }
        MchInfo mchInfo = mchInfoService.getById(mchAppEntity.getMchNo());
        if (mchInfo == null || !mchInfo.getAgentNo().equals(getCurrentAgentNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }
        mchAppEntity.setMchNo(mchInfo.getMchNo());
        mchAppEntity.setAgentNo(getCurrentAgentNo());
        mchAppEntity.setTopAgentNo(mchInfo.getTopAgentNo());
        mchAppEntity.setAppId(SeqKit.getMchAppId());
        //默认设置为审核中
        mchAppEntity.setState(MchAppEntity.AUDIT);
        // 如果当前为默认
        if (mchAppEntity.getDefaultFlag() == CS.YES) {
            mchAppService.update(new LambdaUpdateWrapper<MchAppEntity>()
                    .set(MchAppEntity::getDefaultFlag, CS.NO)
                    .eq(MchAppEntity::getMchNo, mchAppEntity.getMchNo())
            );
        }

        boolean result = mchAppService.save(mchAppEntity);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
        }
        return ApiRes.ok();
    }

    /**
     * @Author: ZhuXiao
     * @Description: 应用详情
     * @Date: 10:13 2021/6/16
     */
    @PreAuthorize("hasAnyAuthority('ENT_MCH_APP_VIEW', 'ENT_MCH_APP_EDIT')")
    @GetMapping("/{appId}")
    public ApiRes detail(@PathVariable("appId") String appId) {
        MchAppEntity mchAppEntity = mchAppService.selectById(appId);

        if (mchAppEntity == null || !mchAppEntity.getAgentNo().equals(getCurrentAgentNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }

        return ApiRes.ok(mchAppEntity);
    }

    /**
     * @Author: ZhuXiao
     * @Description: 更新应用信息
     * @Date: 10:11 2021/6/16
    */
    @PreAuthorize("hasAuthority('ENT_MCH_APP_EDIT')")
    @MethodLog(remark = "更新应用信息")
    @PutMapping("/{appId}")
    public ApiRes update(@PathVariable("appId") String appId) {
        MchAppEntity mchAppEntity = getObject(MchAppEntity.class);
        mchAppEntity.setAppId(appId);

        MchAppEntity dbMchAppEntity = mchAppService.getById(appId);
        if (!dbMchAppEntity.getAgentNo().equals(getCurrentAgentNo())) {
            throw new BizException("无权操作！");
        }
        if (mchAppEntity.getDefaultFlag() != null && !dbMchAppEntity.getDefaultFlag().equals(mchAppEntity.getDefaultFlag())) {
            // 如果修改当前为默认
            if (mchAppEntity.getDefaultFlag() == CS.YES) {
                mchAppService.update(new LambdaUpdateWrapper<MchAppEntity>()
                        .set(MchAppEntity::getDefaultFlag, CS.NO)
                        .eq(MchAppEntity::getMchNo, dbMchAppEntity.getMchNo())
                );
            }else {
                throw new BizException("应用不可修改为非默认！");
            }
        }

        boolean result = mchAppService.updateById(mchAppEntity);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
        }
        return ApiRes.ok();
    }

    /**
     * @Author: ZhuXiao
     * @Description: 删除应用
     * @Date: 10:14 2021/6/16
     */
    @PreAuthorize("hasAuthority('ENT_MCH_APP_DEL')")
    @MethodLog(remark = "删除应用")
    @DeleteMapping("/{appId}")
    public ApiRes delete(@PathVariable("appId") String appId) {
        MchAppEntity mchAppEntity = mchAppService.getById(appId);

        if (!mchAppEntity.getAgentNo().equals(getCurrentAgentNo())) {
            throw new BizException("无权操作！");
        }

        mchAppService.removeByAppId(appId);

        return ApiRes.ok();
    }

    /** 功能描述: 查询系统公钥 */
    @PreAuthorize("hasAnyAuthority('ENT_MCH_APP_ADD', 'ENT_MCH_APP_EDIT')")
    @GetMapping("/sysRSA2PublicKey")
    public ApiRes sysRSA2PublicKey() {
        return ApiRes.ok(systemYmlConfig.getSysRSA2PublicKey());
    }

}
