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

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jeequan.jeepay.agent.ctrl.CommonCtrl;
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.core.model.export.MchTransferOrderExportExcel;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.core.utils.ExcelUtil;
import com.jeequan.jeepay.db.entity.TransferOrderEntity;
import com.jeequan.jeepay.service.impl.TransferOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;


/**
* 转账订单api
*
* @author terrfly
*
* @date 2021/8/13 10:52
*/
@RestController
@RequestMapping("/api/transferOrders")
public class TransferOrderController extends CommonCtrl {

    @Autowired private TransferOrderService transferOrderService;

    /** list **/
    @PreAuthorize("hasAuthority('ENT_TRANSFER_ORDER_LIST')")
    @RequestMapping(value="", method = RequestMethod.GET)
    public ApiRes list() {

        TransferOrderEntity transferOrder = getObject(TransferOrderEntity.class);
        // 可查看自己和全部下级代理数据
        String currentAgentNo = getCurrentAgentNo();
        List<String> subAgentNoList = agentInfoService.queryAllSubAgentNo(currentAgentNo);
        // 自己和下级服务商
        if (CollUtil.isNotEmpty(subAgentNoList)){
            transferOrder.setSubAgentNoList(subAgentNoList);
        }
        IPage<TransferOrderEntity> pages = transferOrderService.pageList(getIPage(), transferOrder);

        return ApiRes.page(pages);
    }

    /** detail **/
    /*@PreAuthorize("hasAuthority('ENT_TRANSFER_ORDER_VIEW')")
    @RequestMapping(value="/{recordId}", method = RequestMethod.GET)
    public ApiRes detail(@PathVariable("recordId") String transferId) {
        TransferOrderEntity refundOrder = transferOrderService.queryMchOrder(getCurrentMchNo(), null, transferId);
        if (refundOrder == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        return ApiRes.ok(refundOrder);
    }*/

    /**
     * @author: xiaoyu
     * @date: 2022/1/14 9:45
     * @describe: 转账数据导出
     */
    @RequestMapping(value="/exportExcel", method = RequestMethod.GET)
    public void exportExcel() {
        try {
            TransferOrderEntity transferOrder = getObject(TransferOrderEntity.class);
            transferOrder.setAgentNo(getCurrentAgentNo());
            IPage<TransferOrderEntity> pages = transferOrderService.pageList(getIPage(true), transferOrder);

            List<JSONObject> newList = new LinkedList<>();
            for (TransferOrderEntity order:pages.getRecords()) {
                JSONObject object = (JSONObject) JSONObject.toJSON(order);
                object.put("entryType", order.getEntryType().replaceAll("_",""));
                object.put("amount", AmountUtil.convertCent2Dollar(order.getAmount()));
                newList.add(object);
            }

            List<MchTransferOrderExportExcel> linkedList = JSONArray.parseArray(JSONArray.toJSONString(newList), MchTransferOrderExportExcel.class);
            // excel输出
            ExcelUtil.exportExcel(linkedList, "转账订单", "转账订单", MchTransferOrderExportExcel.class, "转账订单", response);
        }catch (Exception e) {
            logger.error("导出excel失败", e);
            throw new BizException("导出订单失败！");
        }

    }

    /**
     * @author: xiaoyu
     * @date: 2023/4/26 14:55
     * @describe: 数据统计
     */
    @PreAuthorize("hasAuthority('ENT_TRANSFER_ORDER_COUNT')")
    @RequestMapping(value="/count", method = RequestMethod.GET)
    public ApiRes count() {
        TransferOrderEntity transferOrder = getObject(TransferOrderEntity.class);
        LambdaQueryWrapper<TransferOrderEntity> wrapper = TransferOrderEntity.gw();
        // 可查看自己和全部下级代理数据
        List<String> subAgentNoList = agentInfoService.queryAllSubAgentNo(getCurrentAgentNo());
        // 自己和下级服务商
        if (CollUtil.isNotEmpty(subAgentNoList)){
            transferOrder.setSubAgentNoList(subAgentNoList);
        }

        transferOrder.setState(null);
        // 条件参数
        transferOrderService.selectParams(wrapper, transferOrder);
        Map result = transferOrderService.queryCount(wrapper);

        return ApiRes.ok(result);
    }
}
