package cn.com.ctop.finance.payment.controller;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.finance.payment.entity.FinancePaymentPool;
import cn.com.ctop.finance.payment.service.IFinancePaymentPoolService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import cn.com.ctop.toutiao.modules.tool.service.IByteDanceGetAccountFundService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 款项池表
 */
@Slf4j
@Api(tags = "款项池表")
@RestController
@RequestMapping("/financePayment/pool")
public class FinancePaymentPoolController {
    @Autowired
    private IFinancePaymentPoolService financePaymentPoolService;
    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 分页列表查询
     */
    @ApiOperation(value = "款项池表-分页列表查询", notes = "款项池表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<FinancePaymentPool>> queryPageList(FinancePaymentPool pool,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        Result<IPage<FinancePaymentPool>> result = new Result<>();
        QueryWrapper<FinancePaymentPool> queryWrapper = QueryGenerator.initQueryWrapper(new FinancePaymentPool(), req.getParameterMap());
        if (!Check.isNull(pool.getAdvertiserName())) {
            queryWrapper.like("advertiser_name", pool.getAdvertiserName());
        }
        if (!Check.isNull(pool.getProductName())) {
            queryWrapper.like("product_name", pool.getProductName());
        }
        if (!Check.isNull(pool.getPaymentMedia())) {
            queryWrapper.eq("payment_media", pool.getPaymentMedia());
        }
        if (!Check.isNull(pool.getPaymentType())) {
            queryWrapper.eq("payment_type", pool.getPaymentType());
        }
        if (!Check.isNull(pool.getRebateType())) {
            queryWrapper.eq("rebate_type", pool.getRebateType());
        }
        if (!Check.isNull(pool.getStartDate()) && !Check.isNull(pool.getEndDate())) {
            queryWrapper.ge("create_time", pool.getStartDate() + " 00:00:00");
            queryWrapper.le("create_time", pool.getEndDate() + " 23:59:59");
        }
        queryWrapper.orderByDesc("create_time");
        Page<FinancePaymentPool> page = new Page<FinancePaymentPool>(pageNo, pageSize);
        IPage<FinancePaymentPool> pageList = financePaymentPoolService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param financePaymentPool
     * @return
     */
    @ApiOperation(value = "款项池表-添加", notes = "款项池表-添加")
    @PostMapping(value = "/add")
    public Result<FinancePaymentPool> add(@RequestBody FinancePaymentPool financePaymentPool) {
        Result<FinancePaymentPool> result = new Result<>();
        try {
            financePaymentPoolService.save(financePaymentPool);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param financePaymentPool
     * @return
     */
    @ApiOperation(value = "款项池表-编辑", notes = "款项池表-编辑")
    @PutMapping(value = "/edit")
    public Result<FinancePaymentPool> edit(@RequestBody FinancePaymentPool financePaymentPool) {
        Result<FinancePaymentPool> result = new Result<FinancePaymentPool>();
        FinancePaymentPool financePaymentPoolEntity = financePaymentPoolService.getById(financePaymentPool.getId());
        if (financePaymentPoolEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = financePaymentPoolService.updateById(financePaymentPool);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "款项池表-通过id删除", notes = "款项池表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            financePaymentPoolService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "款项池表-批量删除", notes = "款项池表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<FinancePaymentPool> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<FinancePaymentPool> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.financePaymentPoolService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "款项池表-通过id查询", notes = "款项池表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<FinancePaymentPool> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<FinancePaymentPool> result = new Result<>();
        FinancePaymentPool financePaymentPool = financePaymentPoolService.getById(id);
        if (financePaymentPool == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(financePaymentPool);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 查询信息
     */
    @GetMapping(value = "/queryPool")
    public Result<Object> queryPoolAmountById(String advertiserId, Long productId, String type, String paymentPort) {
        return financePaymentPoolService.queryPoolAmountById(advertiserId, productId, type, paymentPort);
    }

    /**
     * 获取项目
     */
    @GetMapping(value = "/queryPoolProjectList")
    public Result<Object> queryPoolProjectList(String advertiserId, Long productId, String type) {
        productId = null;
        return financePaymentPoolService.queryPoolProjectList(advertiserId, productId, type);
    }

    /**
     * 获取账户
     */
    @GetMapping(value = "/queryPoolAccountList")
    public Result<Object> queryPoolAccountList(String advertiserId, Long projectId, String type) {
        return financePaymentPoolService.queryPoolAccountList(advertiserId, projectId, type);
    }


    /**
     * 为充值提供客户，产品等信息
     */
    @PostMapping(value = "/querySheetIdAndNameList")
    public Result<Object> querySheetIdAndNameList(@RequestBody JSONObject data) {
        try {
            String tableparameters = data.getString("table");
            if (tableparameters.indexOf(",") != -1) {
                return financePaymentPoolService.querySheetIdAndNameList(data);
            } else {
                return Result.error("入参格式不正确");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询异常");
    }

    @GetMapping(value = "/queryPaymentPort")
    public Result<Object> queryPaymentPort(String advertiserId, Long productId, String paymentMedia) {
        try {
            return financePaymentPoolService.queryPaymentPort(advertiserId, productId, paymentMedia);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询异常");
    }

    @Autowired
    private IKuaishouInterfaceService iKuaishouInterfaceService;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Autowired
    IByteDanceGetAccountFundService byteDanceGetAccountFundService;

    /**
     * 查询账户余额
     * media 媒体类型 1-头条、2-快手、7-磁力金牛、9-广点通
     */
    @GetMapping(value = "/queryAccountBalance")
    public Result<Object> queryAccountBalance(Long accountId, String media) {
        try {
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                return Result.ok(0);
            }
            if ("1".equals(media)) {
                JSONObject fundData = byteDanceGetAccountFundService.getAccountFundBy(oauthToken, accountId);
                if (Check.isNull(fundData)) {
                    return Result.ok(0);
                }
                return Result.ok(fundData.getBigDecimal("valid_balance"));
            } else if ("2".equals(media)) {
                JSONObject fundJson = iKuaishouInterfaceService.fundGet(oauthToken);
                return Result.ok(fundJson.getBigDecimal("balance"));
            } else {
                return Result.error("暂不支持查询磁力金牛和广点通余额");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询异常");
    }


}
