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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jeequan.jeepay.agent.ctrl.CommonCtrl;
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.AgentInfo;
import com.jeequan.jeepay.db.entity.PackageOrder;
import com.jeequan.jeepay.db.entity.ProductInfo;
import com.jeequan.jeepay.db.entity.TransferSubjectEntity;
import com.jeequan.jeepay.service.impl.AgentInfoService;
import com.jeequan.jeepay.service.impl.PackageOrderService;
import com.jeequan.jeepay.service.impl.ProductInfoService;
import com.jeequan.jeepay.service.impl.TransferSubjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

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

    @Autowired
    private TransferSubjectService transferSubjectService;

    @Autowired
    private AgentInfoService agentInfoService;

    @Autowired
    private PackageOrderService packageOrderService;

    @Autowired
    private ProductInfoService productInfoService;

    /**
     * 新增付款方账户信息
     *
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ApiRes addTransferSubject() {
        String currentAgentNo = getCurrentAgentNo();
        AgentInfo agentInfo = agentInfoService.getById(currentAgentNo);

        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());
        // 当前登录用户信息
        transferSubject.setId("SUB" + DateUtil.format(new Date(), "yyMMdd") + RandomUtil.randomNumbers(6));
        SysUser sysUser = getCurrentUser().getSysUser();
        transferSubject.setSubjectType(TransferSubject.SUBJECT_TYPE_SPONSOR);
        transferSubject.setInfoType(CS.SYS_ROLE_TYPE.AGENT);
        transferSubject.setTransApplyId(UUID.randomUUID().toString().replace("-", "").substring(0, 32));
        //当前服务商
        transferSubject.setAgentNo(getCurrentAgentNo());
        if (ObjUtil.isEmpty(agentInfo.getPid())) {
            transferSubject.setAgentNo(currentAgentNo);
        } else {
            String[] split = agentInfo.getPidArr().split(",");
            transferSubject.setTopAgentNo(split[split.length - 1]);
        }

        //获取渠道信息
        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);
        // 时间搜索
        Date[] searchDateRange = transferSubject.buildQueryDateRange();
        transferSubject.setFirstDate(searchDateRange[0]);
        transferSubject.setLastDate(searchDateRange[1]);
        // 可查看自己和全部下级代理数据
        String currentAgentNo = getCurrentAgentNo();
        List<String> subAgentNoList = agentInfoService.queryAllSubAgentNo(currentAgentNo);
        // 自己和下级服务商
        if (CollUtil.isNotEmpty(subAgentNoList)){
            transferSubject.setSubAgentNoList(subAgentNoList);
        }
        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);

        transferSubject.setId(id);
        //当前服务商
        transferSubject.setAgentNo(getCurrentAgentNo());
        //获取渠道信息
        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() {
        String currentAgentNo = getCurrentAgentNo();
        AgentInfo agentInfo = agentInfoService.getById(currentAgentNo);
        TransferSubjectEntity transferSubject = getObject(TransferSubjectEntity.class);
        // 当前登录用户信息
        transferSubject.setId("SUB" + DateUtil.format(new Date(), "yyMMdd") + RandomUtil.randomNumbers(6));
        SysUser sysUser = getCurrentUser().getSysUser();
        transferSubject.setSubjectType(TransferSubject.SUBJECT_TYPE_RECEIVER);
        transferSubject.setCreatedUid(sysUser.getSysUserId());
        //当前服务商
        transferSubject.setAgentNo(currentAgentNo);
        if (ObjUtil.isEmpty(agentInfo.getPid())) {
            transferSubject.setAgentNo(currentAgentNo);
        } else {
            String[] split = agentInfo.getPidArr().split(",");
            transferSubject.setTopAgentNo(split[split.length - 1]);
        }

        transferSubject.setTransIfCode(CS.IF_CODE.ALIAQF);
        //获取渠道信息
        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);
        // 可查看自己和全部下级代理数据
        String currentAgentNo = getCurrentAgentNo();
        List<String> subAgentNoList = agentInfoService.queryAllSubAgentNo(currentAgentNo);
        // 自己和下级服务商
        if (CollUtil.isNotEmpty(subAgentNoList)){
            subject.setSubAgentNoList(subAgentNoList);
        }
        return  transferSubjectService.getSubStatistics(subject);
    }
}
