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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.core.entity.TransferSubject;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 转账对象信息
 */
@RestController
@Slf4j
@RequestMapping("/api/aqf")
public class AqfController extends CommonCtrl {

    @Autowired
    private TransferSubjectService transferSubjectService;

    @Autowired
    private TransferInterfaceConfigService transferInterfaceConfigService;

    @Autowired
    private IsvInfoService isvInfoService;

    @Autowired
    private AgentInfoService agentInfoService;

    @Autowired
    private MchInfoService mchInfoService;
    @Autowired
    private PackageOrderService packageOrderService;
    @Autowired
    private ProductInfoService productInfoService;

    /**
     * 新增付款方账户信息
     *
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ApiRes addTransferSubject() {
        TransferSubjectEntity transferSubject = getObject(TransferSubjectEntity.class);
        // 通过产品开通记录获取应用信息
        String openOrderId = transferSubject.getOpenOrderId();
        Assert.notNull(openOrderId, "产品开通记录不能为空");
        PackageOrder packageOrder = packageOrderService.getById(openOrderId);
        Assert.notNull(packageOrder, "未获取到产品开通记录");
        ProductInfo productInfo = productInfoService.getDetailById(packageOrder.getProductId());
        Assert.notNull(productInfo, "未获取到产品信息");

        // 安全发的产品code
        if (!"API_ANQUANFA_CP_PAY".equals(productInfo.getApiCode())) {
            log.info("所选产品code为{}, 不属于安全发", productInfo.getApiCode());
            throw new BizException("所选产品不支持该操作");
        }

        transferSubject.setAppId(packageOrder.getAppId());

        getValStringRequired("mchNo");
        // 当前登录用户信息
        transferSubject.setId("SUB" + DateUtil.format(new Date(), "yyMMdd") + RandomUtil.randomNumbers(6));
        SysUser sysUser = getCurrentUser().getSysUser();
        transferSubject.setSubjectType("FQ");
        transferSubject.setTransApplyId(UUID.randomUUID().toString().replace("-", "").substring(0, 32));

        if (StringUtils.isEmpty(transferSubject.getAgentNo())) {
            //获取服务商信息
            MchInfo mchInfo = mchInfoService.getById(transferSubject.getMchNo());
            transferSubject.setAgentNo(mchInfo.getAgentNo());
        }
        if (StringUtils.isEmpty(transferSubject.getIsvNo())){
            //获取渠道信息
            AgentInfo agentInfo = agentInfoService.getById(transferSubject.getAgentNo());
            transferSubject.setIsvNo(agentInfo.getIsvNo());
        }
        transferSubject.setCreatedUid(sysUser.getSysUserId());
        boolean save = transferSubjectService.save(transferSubject);
        if (save) {
            return ApiRes.ok();
        } else {
            return ApiRes.customFail("新增失败！");
        }
    }

    /**
     * 查询
     */
    @GetMapping("/getPageList")
    public ApiRes pageTransferSubject() {
        TransferSubjectEntity transferSubject = getObject(TransferSubjectEntity.class);
        // 时间搜索
        transferSubject.buildQueryDateRange();
        IPage<TransferSubjectEntity> pageList = transferSubjectService.getPageList(getIPage(), transferSubject);
        return ApiRes.page(pageList);
    }

    /**
     * 查询详情
     */
    @GetMapping(value = "/{id}")
    public ApiRes getByIdTransferSubject(@PathVariable("id") String id) {
        TransferSubjectEntity byId = transferSubjectService.getById(id);
        return ApiRes.ok(byId);
    }

    /**
     * 修改
     */
    @PutMapping(value = "/{id}")
    public ApiRes updateTransferSubject(@PathVariable("id") String id) {
        TransferSubjectEntity transferSubject = getObject(TransferSubjectEntity.class);
        getValStringRequired("mchNo");
        transferSubject.setId(id);
        if (StringUtils.isEmpty(transferSubject.getAgentNo())) {
            //获取服务商信息
            MchInfo mchInfo = mchInfoService.getById(transferSubject.getMchNo());
            transferSubject.setAgentNo(mchInfo.getAgentNo());
        }
        if (StringUtils.isEmpty(transferSubject.getIsvNo())){
            //获取渠道信息
            AgentInfo agentInfo = agentInfoService.getById(transferSubject.getAgentNo());
            transferSubject.setIsvNo(agentInfo.getIsvNo());
        }
        boolean resut = transferSubjectService.updateById(transferSubject);
        if (resut) {
            return ApiRes.ok();
        } else {
            return ApiRes.customFail("修改失败！");
        }
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public ApiRes deleteTransferSubject(@PathVariable("id") String id) {
        boolean resut = transferSubjectService.removeById(id);
        if (resut) {
            return ApiRes.ok();
        } else {
            return ApiRes.customFail("删除失败！");
        }
    }

    /**
     * 新增收款方账户信息
     */
    @PostMapping("/addJs")
    public ApiRes addJsTransferSubject() {
        TransferSubjectEntity transferSubject = getObject(TransferSubjectEntity.class);
        getValStringRequired("mchNo");
        // 当前登录用户信息
        transferSubject.setId("SUB" + DateUtil.format(new Date(), "yyMMdd") + RandomUtil.randomNumbers(6));
        SysUser sysUser = getCurrentUser().getSysUser();
        transferSubject.setSubjectType("JS");
        transferSubject.setTransIfCode(CS.IF_CODE.ALIAQF);
        transferSubject.setCreatedUid(sysUser.getSysUserId());
        if (StringUtils.isEmpty(transferSubject.getAgentNo())) {
            //获取服务商信息
            MchInfo mchInfo = mchInfoService.getById(transferSubject.getMchNo());
            transferSubject.setAgentNo(mchInfo.getAgentNo());
        }
        if (StringUtils.isEmpty(transferSubject.getIsvNo())){
            //获取渠道信息
            AgentInfo agentInfo = agentInfoService.getById(transferSubject.getAgentNo());
            transferSubject.setIsvNo(agentInfo.getIsvNo());
        }
        boolean save = transferSubjectService.save(transferSubject);
        if (save) {
            return ApiRes.ok();
        } else {
            return ApiRes.customFail("新增失败！");
        }
    }

    @GetMapping("/getBatchData")
    public ApiRes getBatchData() {
        String transferSubjects = getValStringRequired("transferSubjects");
        List<TransferSubjectEntity> transferSubjectEntityList = new ArrayList<>();
        String[] transferSubjectSpli = transferSubjects.split(",");
        for (String transferSubjectId : transferSubjectSpli) {
            TransferSubjectEntity transferSubjectEntity = transferSubjectService.getById(transferSubjectId);
            if (transferSubjectEntity != null) {
                transferSubjectEntityList.add(transferSubjectEntity);
            }
        }
        return ApiRes.ok(transferSubjectEntityList);
    }

    @PostMapping("/state")
    public ApiRes exam() {
        JSONObject reqParamJSON = getReqParamJSON();
        Integer state = reqParamJSON.getInteger("state");
        String id = reqParamJSON.getString("id");
        String remark = reqParamJSON.getString("remark");

        TransferSubjectEntity transferSubjectEntity = transferSubjectService.getById(id);
        Assert.notNull(transferSubjectEntity, "付款账户信息不存在");

        if (state == TransferSubject.STATE_DISABLE) {
            transferSubjectEntity.setState(TransferSubject.STATE_DISABLE);
            transferSubjectEntity.setRemark(remark);
            transferSubjectService.updateById(transferSubjectEntity);
        } else if (state == TransferSubject.STATE_ENABLE) {
            transferSubjectEntity.setState(TransferSubject.STATE_ENABLE);
            transferSubjectService.updateById(transferSubjectEntity);
        } else if (state == TransferSubject.STATE_ENABLE_REVIEW) {
            transferSubjectEntity.setState(TransferSubject.STATE_ENABLE_REVIEW);
            transferSubjectService.updateById(transferSubjectEntity);
        }

        return ApiRes.ok();
    }
    /**
     * 统计收款账户总成交金额和总成交笔数
     */
    @GetMapping("/getSubStatistics")
    public Map<String, Object> getSubStatistics(){
        TransferSubjectEntity subject = getObject(TransferSubjectEntity.class);
        return  transferSubjectService.getSubStatistics(subject);
    }
}
