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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.PayInterfaceConfig;
import com.jeequan.jeepay.db.entity.PayInterfaceDefine;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.PayInterfaceConfigService;
import com.jeequan.jeepay.service.impl.PayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 支付接口定义管理类
 *
 * @author zhuxiao
 * @since 2021-04-27 15:50
 */
@RestController
@RequestMapping("api/payIfDefines")
public class PayInterfaceDefineController extends CommonCtrl {

    @Autowired private PayOrderService payOrderService;
    @Autowired private PayInterfaceConfigService payInterfaceConfigService;

    /**
     * @author ZhuXiao
     * @Description: list
     * @since 15:51 2021/4/27
    */
    @PreAuthorize("hasAuthority('ENT_PC_IF_DEFINE_LIST')")
    @GetMapping
    public ApiRes list() {

        PayInterfaceDefine queryRecord = getObject(PayInterfaceDefine.class);

        LambdaQueryWrapper<PayInterfaceDefine> lambdaQueryWrapper = PayInterfaceDefine.gw();
        lambdaQueryWrapper.eq(queryRecord.getState() != null , PayInterfaceDefine::getState, queryRecord.getState());
        lambdaQueryWrapper.eq(queryRecord.getIsSupportApplyment() != null , PayInterfaceDefine::getIsSupportApplyment, queryRecord.getIsSupportApplyment());
        lambdaQueryWrapper.eq(queryRecord.getIsSupportCheckBill() != null , PayInterfaceDefine::getIsSupportCheckBill, queryRecord.getIsSupportCheckBill());
        lambdaQueryWrapper.eq(queryRecord.getIsOpenCheckBill() != null , PayInterfaceDefine::getIsOpenCheckBill, queryRecord.getIsOpenCheckBill());
        lambdaQueryWrapper.eq(queryRecord.getIsSupportCashout() != null , PayInterfaceDefine::getIsSupportCashout, queryRecord.getIsSupportCashout());
        lambdaQueryWrapper.eq(queryRecord.getIsOpenCashout() != null , PayInterfaceDefine::getIsOpenCashout, queryRecord.getIsOpenCashout());

        lambdaQueryWrapper.orderByAsc(PayInterfaceDefine::getCreatedAt);
        List<PayInterfaceDefine> list = payInterfaceDefineService.list(lambdaQueryWrapper);
        return ApiRes.ok(list);
    }

    /**
     * 分页查询
     * @return
     */
    @GetMapping("/listPage")
    public ApiRes listPage() {

        PayInterfaceDefine queryRecord = getObject(PayInterfaceDefine.class);

        LambdaQueryWrapper<PayInterfaceDefine> lambdaQueryWrapper = PayInterfaceDefine.gw();
        lambdaQueryWrapper.eq(queryRecord.getState() != null , PayInterfaceDefine::getState, queryRecord.getState());
        lambdaQueryWrapper.eq(queryRecord.getIsSupportApplyment() != null , PayInterfaceDefine::getIsSupportApplyment, queryRecord.getIsSupportApplyment());
        lambdaQueryWrapper.eq(queryRecord.getIsSupportCheckBill() != null , PayInterfaceDefine::getIsSupportCheckBill, queryRecord.getIsSupportCheckBill());
        lambdaQueryWrapper.eq(queryRecord.getIsOpenCheckBill() != null , PayInterfaceDefine::getIsOpenCheckBill, queryRecord.getIsOpenCheckBill());
        lambdaQueryWrapper.eq(queryRecord.getIsSupportCashout() != null , PayInterfaceDefine::getIsSupportCashout, queryRecord.getIsSupportCashout());
        lambdaQueryWrapper.eq(queryRecord.getIsOpenCashout() != null , PayInterfaceDefine::getIsOpenCashout, queryRecord.getIsOpenCashout());

        lambdaQueryWrapper.orderByAsc(PayInterfaceDefine::getCreatedAt);
        Page<PayInterfaceDefine> page = payInterfaceDefineService.page(getIPage(), lambdaQueryWrapper);
        return ApiRes.ok(page);
    }


    /**
     * @author ZhuXiao
     * @Description: detail
     * @since 15:51 2021/4/27
    */
    @PreAuthorize("hasAnyAuthority('ENT_PC_IF_DEFINE_VIEW', 'ENT_PC_IF_DEFINE_EDIT')")
    @GetMapping("/{ifCode}")
    public ApiRes detail(@PathVariable("ifCode") String ifCode) {
        return ApiRes.ok(payInterfaceDefineService.getById(ifCode));
    }

    /**
     * @author ZhuXiao
     * @Description: add
     * @since 15:51 2021/4/27
    */
    @PreAuthorize("hasAuthority('ENT_PC_IF_DEFINE_ADD')")
    @PostMapping
    @MethodLog(remark = "新增支付接口")
    public ApiRes add() {
        PayInterfaceDefine payInterfaceDefine = getObject(PayInterfaceDefine.class);

        // 查询if_code是否已存在
        PayInterfaceDefine define = payInterfaceDefineService.getById(payInterfaceDefine.getIfCode());
        if (define != null) {
            throw new BizException("当前接口代码已存在，请求改后重试");
        }

        JSONArray jsonArray = new JSONArray();
        String[] wayCodes = getValStringRequired("wayCodeStrs").split(",");
        for (String wayCode : wayCodes) {
            JSONObject object = new JSONObject();
            object.put("wayCode", wayCode);
            jsonArray.add(object);
        }
        payInterfaceDefine.setWayCodes(jsonArray);

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

    /**
     * @author ZhuXiao
     * @Description: update
     * @since 15:51 2021/4/27
    */
    @PreAuthorize("hasAuthority('ENT_PC_IF_DEFINE_EDIT')")
    @PutMapping("/{ifCode}")
    @MethodLog(remark = "更新支付接口")
    public ApiRes update(@PathVariable("ifCode") String ifCode) {
        PayInterfaceDefine payInterfaceDefine = getObject(PayInterfaceDefine.class);
        payInterfaceDefine.setIfCode(ifCode);

        JSONArray jsonArray = new JSONArray();
        String[] wayCodes = getValStringRequired("wayCodeStrs").split(",");
        for (String wayCode : wayCodes) {
            JSONObject object = new JSONObject();
            object.put("wayCode", wayCode);
            jsonArray.add(object);
        }
        payInterfaceDefine.setWayCodes(jsonArray);

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

    /**
     * @author ZhuXiao
     * @Description: delete
     * @since 15:52 2021/4/27
    */
    @PreAuthorize("hasAuthority('ENT_PC_IF_DEFINE_DEL')")
    @DeleteMapping("/{ifCode}")
    @MethodLog(remark = "删除支付接口")
    public ApiRes delete(@PathVariable("ifCode") String ifCode) {

        // 校验该支付方式是否有服务商或商户配置参数或者已有订单
        if (payInterfaceConfigService.count(PayInterfaceConfig.gw().eq(PayInterfaceConfig::getIfCode, ifCode)) > 0
                || payOrderService.count(PayOrder.gw().eq(PayOrder::getIfCode, ifCode)) > 0) {
            throw new BizException("该支付接口已有服务商或商户配置参数或已发生交易，无法删除！");
        }

        boolean result = payInterfaceDefineService.removeById(ifCode);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_DELETE);
        }
        return ApiRes.ok();
    }

    /** 查询克隆模式的信息， 比如数量名称等 **/
    @PreAuthorize("hasAnyAuthority('ENT_PC_IF_DEFINE_EDIT')")
    @GetMapping("/cloneInfos/{ifCode}")
    public ApiRes cloneInfos(@PathVariable("ifCode") String ifCode) {

        long count = payInterfaceDefineService.count(PayInterfaceDefine.gw().likeRight(PayInterfaceDefine::getIfCode, (ifCode + "_") ));

        PayInterfaceDefine result = new PayInterfaceDefine();
        result.setIfCode(ifCode + "_" + (count + 1));
        result.setIfName(payInterfaceDefineService.getById(ifCode).getIfName() + "_副本" + (count + 1));

        return ApiRes.ok(result);
    }

    /** 同步参数到所有副本 **/
    @PreAuthorize("hasAnyAuthority('ENT_PC_IF_DEFINE_EDIT')")
    @PutMapping("/syncConfigInfo2CloneIfCodes/{ifCode}")
    public ApiRes syncConfigInfo2CloneIfCodes(@PathVariable("ifCode") String ifCode) {

        List<PayInterfaceDefine> clonedList = payInterfaceDefineService.list(PayInterfaceDefine.gw().select(PayInterfaceDefine::getIfCode).likeRight(PayInterfaceDefine::getIfCode, (ifCode + "_") ));

        if(clonedList.isEmpty()){
            throw new BizException("不存在副本列表！");
        }

        // ifCode列表
        List<String> cloneListByIfcode = new ArrayList<>();
        for (PayInterfaceDefine payInterfaceDefineItem : clonedList) {
            cloneListByIfcode.add(payInterfaceDefineItem.getIfCode());
        }

        // 当前接口信息
        PayInterfaceDefine payInterfaceDefine = payInterfaceDefineService.getById(ifCode);

        // 更新的项目： 支持部分和参数部分， 其他的不做更新
        PayInterfaceDefine updateRecord = new PayInterfaceDefine();
        updateRecord.setIsMchMode(payInterfaceDefine.getIsMchMode());
        updateRecord.setIsIsvMode(payInterfaceDefine.getIsIsvMode());
        updateRecord.setIsSupportApplyment(payInterfaceDefine.getIsSupportApplyment());
        updateRecord.setIsSupportCheckBill(payInterfaceDefine.getIsSupportCheckBill());
        updateRecord.setIsSupportCashout(payInterfaceDefine.getIsSupportCashout());
        updateRecord.setConfigPageType(payInterfaceDefine.getConfigPageType());
        updateRecord.setIsvParams(payInterfaceDefine.getIsvParams());
        updateRecord.setIsvsubMchParams(payInterfaceDefine.getIsvsubMchParams());
        updateRecord.setNormalMchParams(payInterfaceDefine.getNormalMchParams());
        updateRecord.setWayCodes(payInterfaceDefine.getWayCodes());
        updateRecord.setChannelFeeCalModel(payInterfaceDefine.getChannelFeeCalModel());

        // 更新
        payInterfaceDefineService.update(updateRecord, PayInterfaceDefine.gw().in(PayInterfaceDefine::getIfCode, cloneListByIfcode));
        return ApiRes.ok();
    }

    @GetMapping("/getPayIfDefines")
    public ApiRes getPayIfDefines() {

        PayInterfaceDefine queryRecord = getObject(PayInterfaceDefine.class);

        LambdaQueryWrapper<PayInterfaceDefine> lambdaQueryWrapper = PayInterfaceDefine.gw();
        lambdaQueryWrapper.eq(queryRecord.getState() != null , PayInterfaceDefine::getState, queryRecord.getState());
        lambdaQueryWrapper.eq(queryRecord.getIsSupportApplyment() != null , PayInterfaceDefine::getIsSupportApplyment, queryRecord.getIsSupportApplyment());
        lambdaQueryWrapper.eq(queryRecord.getIsSupportCheckBill() != null , PayInterfaceDefine::getIsSupportCheckBill, queryRecord.getIsSupportCheckBill());
        lambdaQueryWrapper.eq(queryRecord.getIsOpenCheckBill() != null , PayInterfaceDefine::getIsOpenCheckBill, queryRecord.getIsOpenCheckBill());
        lambdaQueryWrapper.eq(queryRecord.getIsSupportCashout() != null , PayInterfaceDefine::getIsSupportCashout, queryRecord.getIsSupportCashout());
        lambdaQueryWrapper.eq(queryRecord.getIsOpenCashout() != null , PayInterfaceDefine::getIsOpenCashout, queryRecord.getIsOpenCashout());

        lambdaQueryWrapper.orderByAsc(PayInterfaceDefine::getCreatedAt);
        Page<PayInterfaceDefine> page = payInterfaceDefineService.page(getIPage(), lambdaQueryWrapper);
        return ApiRes.ok(page);
    }

}
