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

import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSONArray;
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.toolkit.Wrappers;
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.interfaces.paychannel.ISqbApiService;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.DBApplicationConfig;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchAppEntity;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.db.entity.MchConfig;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.MchAppService;
import com.jeequan.jeepay.service.impl.MchConfigService;
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.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商户配置管理类
 *
 * @author zx
 *
 * @date 2021-06-16 09:15
 */
@RestController
@RequestMapping("/api/mchConfig")
public class MchConfigController extends CommonCtrl {

    @Autowired private MchConfigService mchConfigService;
    @Autowired private MchInfoService mchInfoService;
    @Autowired private MchAppService mchAppService;

    /**
     * @Author: zx
     * @Description: 查询商户配置
     * @Date: 9:59 2021/6/16
    */
    @PreAuthorize("hasAuthority('ENT_MCH_CONFIG_PAGE')")
    @GetMapping
    public ApiRes list() {

        String groupKey = getValString("groupKey");

        String mchNo = getValStringRequired("mchNo");
        String mchAppId = getValString("mchAppId");
        String mchApplyId = getValString("mchApplyId");

        LambdaQueryWrapper<MchConfig> queryWrapper = MchConfig.gw()
                .eq(MchConfig::getMchNo, mchNo)
                .eq(!ObjUtil.isEmpty(mchAppId), MchConfig::getMchAppId, mchAppId)
                .eq(!ObjUtil.isEmpty(mchApplyId), MchConfig::getMchApplyId, mchApplyId);
        if (StringUtils.isNotBlank(groupKey)) {
            queryWrapper.eq(MchConfig::getGroupKey, groupKey);
        }

        List<MchConfig> list = mchConfigService.list(queryWrapper);
        return ApiRes.ok(list);
    }

    /**
     * @Author: zx
     * @Description: 根据configKey查询商户配置
     * @Date: 9:59 2021/6/16
     */
    @PreAuthorize("hasAuthority('ENT_MCH_CONFIG_PAGE')")
    @GetMapping("/{configKey}")
    public ApiRes get(@PathVariable("configKey") String configKey) {

        MchConfig mchConfig = mchConfigService.getOne(MchConfig.gw().eq(MchConfig::getMchNo, getValStringRequired("mchNo")).eq(MchConfig::getConfigKey, configKey));
        return ApiRes.ok(mchConfig);
    }

    /**
     * @author: zx
     * @Description: 批量更新商户配置信息
     * @Date: 10:11 2021/6/16
     */
    @PreAuthorize("hasAuthority('ENT_MCH_CONFIG_PAGE')")
    @MethodLog(remark = "批量更新商户配置信息")
    @PutMapping("/{groupKey}")
    public ApiRes updateBatch(@PathVariable("groupKey") String groupKey) {

        String params = getValStringRequired("configData");

        List<MchConfig> mchConfigList = JSONArray.parseArray(params, MchConfig.class);

        String mchNo = getValStringRequired("mchNo");
        String mchAppId = getValString("mchAppId");
        String mchApplyId = getValString("mchApplyId");

        int update = mchConfigService.updateBatch(mchConfigList, mchNo, mchAppId, mchApplyId, groupKey);
        if(update <= 0) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
        }

        return ApiRes.ok();
    }


    /**
     * 收钱吧 商户激活配置参数
     * @return
     */
    @PreAuthorize("hasAuthority('ENT_MCH_CONFIG_PAGE')")
    @PostMapping("/activation")
    public ApiRes activation() {
        JSONObject paramJSON = getReqParamJSON();
        String mchAppId = paramJSON.getString("mchAppId");
        // 应用信息
        MchAppEntity mchAppEntity = mchAppService.getById(mchAppId);
        if (mchAppEntity == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        // 商户信息 [商户类型必须为特约商户]
        MchInfo mchInfo = mchInfoService.getById(mchAppEntity.getMchNo());
        if (mchInfo == null || mchInfo.getType() == CS.MCH_TYPE_NORMAL) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        paramJSON.put("mchNo", mchInfo.getMchNo());
        ISqbApiService sqbpayApiService = SpringBeansUtil.getBean(CS.IF_CODE.SQBPAY + "ApiService", ISqbApiService.class);

        JSONObject activationRes = sqbpayApiService.activation(paramJSON);
        return ApiRes.ok(activationRes);
    }

    /** 收银台地址 **/
    @PreAuthorize("hasAnyAuthority('ENT_MCH_CASHIER_URL')")
    @PostMapping("/createCashier")
    public ApiRes createCashier() {

        //获取请求参数
        String appId = getValString("appId");
        String mchNo = getValString("mchNo");
        String storeId = getValStringRequired("storeId");

        // 当前没有传入应用，那么使用默认应用
        if(StringUtils.isBlank(appId)){
            appId = mchAppService.getDefaultApp(mchNo).getAppId();
        }

        MchAppEntity mchAppEntity = mchAppService.getById(appId);
        if(mchAppEntity == null || mchAppEntity.getState() != CS.PUB_USABLE || !mchAppEntity.getAppId().equals(appId)){
            throw new BizException("商户应用不存在或不可用");
        }

        DBApplicationConfig dbApplicationConfig = sysConfigService.getDBApplicationConfig();
        try {
            String payUrl = dbApplicationConfig.genCashierPayUrl(appId, storeId+"");
            return ApiRes.ok(payUrl);
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
    }

    @PostMapping("/config")
    public ApiRes setConfig() {
        String applyId = getValStringRequired("applyId");
        String configKey = getValStringRequired("configKey");
        String configVal = getValStringRequired("configVal");

        MchConfig config = mchConfigService.lambdaQuery()
                .eq(MchConfig::getConfigKey, configKey)
                .eq(MchConfig::getMchApplyId, applyId)
                .one();

        if (config == null) {
            MchConfig.Option option = MchConfig.Option.getFirstByConfigKey(configKey);
            Assert.notNull(option, "未知的配置项");

            MchApplyment mchApplyment = mchApplymentService.getById(applyId);
            MchConfig newData = new MchConfig();
            newData.setMchNo(mchApplyment.getMchNo())
                    .setConfigKey(configKey)
                    .setMchAppId(mchApplyment.getAutoConfigMchAppId())
                    .setMchApplyId(mchApplyment.getApplyId())
                    .setConfigName(option.getConfigName())
                    .setGroupKey(option.getGroupKey())
                    .setType(option.getType())
                    .setConfigVal(configVal);

            mchConfigService.save(newData);
        } else {
            LambdaUpdateWrapper<MchConfig> uWrapper = Wrappers.lambdaUpdate();
            uWrapper.eq(MchConfig::getConfigKey, configKey)
                    .eq(MchConfig::getMchApplyId, applyId)
                    .set(MchConfig::getConfigVal, configVal);

            mchConfigService.update(uWrapper);
        }

        return ApiRes.ok();
    }

//    public static void main(String[] args) throws UnsupportedEncodingException {
////        String s = HttpUtil.get(s1);M
////
////        System.out.println(s1);
//
////        RestTemplate restTemplate = new RestTemplate();
////        String forObject = restTemplate.getForObject("https://whois.pconline.com.cn/ipJson.jsp?ip=111.175.29.61&json=true", String.class);
////        System.out.println(forObject);
//
////        Map<String, Object> map = new HashMap<>();
////        map.put("ip", "111.175.29.61");
////        map.put("json", "true");
//        String url = "https://whois.pconline.com.cn/ipJson.jsp";
////        System.out.println(url);
//
//
//        HttpResponse execute = HttpUtil.createGet(url)
//                .form("ip", "111.175.29.61")
//                .form("json", "true")
//                .header("User-Agent", "11111")
//                .execute();
//
//        String body = execute.body().replace("\n", "");
//        JSONObject jsonObject = JSON.parseObject(body);
//        System.out.println(body);
//    }
}
