package com.bweb.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.bweb.config.SysConst;
import com.bweb.excelListener.ImportRechargeOrderListener;
import com.bweb.model.ExportOutRechargeOrder;
import com.bweb.model.ExportOutRechargeOrderCount;
import com.bweb.model.ExportOutRechargeUserOrderCount;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.pay.util.XmlUtil;
import com.hai.common.pay.util.sdk.WXPayConstants;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.common.utils.WxUtils;
import com.hai.config.HuiLianTongUnionCardConfig;
import com.hai.config.UnionPayConfig;
import com.hai.entity.HighRefundAudit;
import com.hai.entity.OutRechargeChildOrder;
import com.hai.entity.OutRechargeOrder;
import com.hai.entity.OutRechargeOrderRecord;
import com.hai.model.*;
import com.hai.service.HighRefundAuditService;
import com.hai.service.HighUserService;
import com.hai.service.OutRechargeChildOrderService;
import com.hai.service.OutRechargeOrderService;
import com.hai.service.pay.impl.GoodsOrderServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.IntFunction;

@Controller
@RequestMapping(value = "/outRechargeOrder")
@Api(value = "充值订单接口")
public class OutRechargeOrderController {
    private static Logger log = LoggerFactory.getLogger(HighMerchantStoreController.class);

    @Autowired
    private UserCenter userCenter;

    @Resource
    private OutRechargeOrderService outRechargeOrderService;

    @Resource
    private OutRechargeChildOrderService outRechargeChildOrderService;


    @RequestMapping(value = "/getOrderById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id查询订单详情")
    public ResponseData getOrderById(@RequestParam(name = "orderId", required = true) Long orderId) {
        try {

            return ResponseMsgUtil.success(outRechargeOrderService.findByOrderId(orderId));

        } catch (Exception e) {
            log.error("HighOrderController --> getOrderById() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getChildOrder", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id查询子订单详情")
    public ResponseData getChildOrder(@RequestParam(name = "orderId", required = true) Long orderId) {
        try {

            // 查询充值子订单
            Map<String, Object> childOrderMap = new HashMap<>();

            childOrderMap.put("parent_order_id", orderId);

            List<OutRechargeChildOrder> childOrderList = outRechargeChildOrderService.getListRechargeChildOrder(childOrderMap);

            return ResponseMsgUtil.success(childOrderList);

        } catch (Exception e) {
            log.error("HighOrderController --> getOrderById() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/importRechargeOrder",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "导入话费充值订单")
    public ResponseData importRechargeOrder( @RequestParam(value = "file" , required = true) MultipartFile files,
                                    HttpServletRequest request) {
        try {

            ImportRechargeOrderListener importRechargeOrderListener = new ImportRechargeOrderListener();
            importRechargeOrderListener.initData(outRechargeOrderService);
            EasyExcel.read(files.getInputStream(), ExportOutRechargeOrder.class, importRechargeOrderListener).sheet().doRead();

            Map<String, Object> map = new HashMap<>();
            map.put("errorData", importRechargeOrderListener.getErrorData());
            map.put("errorTotal", importRechargeOrderListener.getErrorData().size());

            return ResponseMsgUtil.success(map);

        } catch (Exception e) {
            log.error("HighCouponController -> importStock() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getOrderList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取订单")
    public ResponseData getUserOrderList(
            @RequestParam(name = "payStatus", required = false) Integer payStatus,
            @RequestParam(name = "rechargeStatus", required = false) String rechargeStatus,
            @RequestParam(name = "orderNo", required = false) String orderNo,
            @RequestParam(name = "companyId", required = false) Long companyId,
            @RequestParam(name = "operatorType", required = false) String operatorType,
            @RequestParam(name = "laborUnionCard", required = false) String laborUnionCard,
            @RequestParam(name = "rechargeContent", required = false) String rechargeContent,
            @RequestParam(name = "userPhone", required = false) String userPhone,
            @RequestParam(name = "rechargeType", required = false) String rechargeType,
            @RequestParam(name = "payType", required = false) Integer payType,
            @RequestParam(name = "payTimeS", required = false) Long payTimeS,
            @RequestParam(name = "payTimeE", required = false) Long payTimeE,
            @RequestParam(name = "createTimeS", required = false) Long createTimeS,
            @RequestParam(name = "createTimeE", required = false) Long createTimeE,
            @RequestParam(name = "pageNum", required = true) Integer pageNum,
            @RequestParam(name = "pageSize", required = true) Integer pageSize,
            HttpServletRequest request) {
        try {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            Map<String, Object> map = new HashMap<>();

            if (companyId != null) {
                map.put("companyId", companyId);
            } else if (userInfoModel.getSecRole().getRoleType() != 1){
                if (userInfoModel.getSecRole().getRoleType() == 7) {
                    map.put("companyId", 23);
                } else {
                    map.put("companyId", userInfoModel.getBsCompany().getId());
                }
            }

            map.put("rechargeStatus", rechargeStatus);
            map.put("payStatus", payStatus);
            map.put("orderNo", orderNo);
            map.put("operatorType", operatorType);
            map.put("laborUnionCard", laborUnionCard);
            map.put("rechargeContent", rechargeContent);
            map.put("userPhone", userPhone);
            map.put("rechargeType", rechargeType);
            map.put("payType", payType);
            if (payTimeS != null && payTimeE != null ) {
                map.put("payTimeS", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(payTimeS));
                map.put("payTimeE", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(payTimeE));
            }
            if (createTimeS != null && createTimeE != null) {
                map.put("createTimeS", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTimeS));
                map.put("createTimeE", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTimeE));
            }

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(outRechargeOrderService.getListRechargeOrder(map)));

        } catch (Exception e) {
            log.error("HighOrderController --> getUserOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/exportOrderList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出订单")
    public ResponseData exportOrderList(
            @RequestParam(name = "payStatus", required = false) Integer payStatus,
            @RequestParam(name = "rechargeStatus", required = false) String rechargeStatus,
            @RequestParam(name = "companyId", required = false) Long companyId,
            @RequestParam(name = "orderNo", required = false) String orderNo,
            @RequestParam(name = "operatorType", required = false) String operatorType,
            @RequestParam(name = "laborUnionCard", required = false) String laborUnionCard,
            @RequestParam(name = "rechargeContent", required = false) String rechargeContent,
            @RequestParam(name = "userPhone", required = false) String userPhone,
            @RequestParam(name = "rechargeType", required = false) String rechargeType,
            @RequestParam(name = "payType", required = false) Integer payType,
            @RequestParam(name = "payTimeS", required = false) Long payTimeS,
            @RequestParam(name = "payTimeE", required = false) Long payTimeE,
            @RequestParam(name = "createTimeS", required = false) Long createTimeS,
            @RequestParam(name = "createTimeE", required = false) Long createTimeE,
            HttpServletRequest request
    ) {
        try {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            Map<String, Object> map = new HashMap<>();


            if (companyId != null) {
                map.put("companyId", companyId);
            } else if (userInfoModel.getSecRole().getRoleType() != 1){
                if (userInfoModel.getSecRole().getRoleType() == 7) {
                    map.put("companyId", 23);
                } else {
                    map.put("companyId", userInfoModel.getBsCompany().getId());
                }
            }
            map.put("rechargeStatus", rechargeStatus);
            map.put("payStatus", payStatus);
            map.put("orderNo", orderNo);
            map.put("operatorType", operatorType);
            map.put("laborUnionCard", laborUnionCard);
            map.put("rechargeContent", rechargeContent);
            map.put("userPhone", userPhone);
            map.put("rechargeType", rechargeType);
            map.put("payType", payType);
            if (payTimeS != null && payTimeE != null ) {
                map.put("payTimeS", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(payTimeS));
                map.put("payTimeE", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(payTimeE));
            }
            if (createTimeS != null && createTimeE != null) {
                map.put("createTimeS", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTimeS));
                map.put("createTimeE", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTimeE));
            }
            List<OutRechargeOrderModel> list = outRechargeOrderService.getOrderCount(map);

            String name = "/outRechargeOrder/充值订单" + System.currentTimeMillis() + ".xlsx";
            String fileName = SysConst.getSysConfig().getFileUrl() + name;
            EasyExcel.write(fileName, ExportOutRechargeOrder.class).sheet("充值订单").doWrite(list);
            return ResponseMsgUtil.success(name);
        } catch (Exception e) {
            log.error("HighOrderController --> exportOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getOrderCountList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询时间订单统计")
    public ResponseData getOrderCountList(
            @RequestParam(name = "finishTimeS", required = false) Long finishTimeS,
            @RequestParam(name = "finishTimeE", required = false) Long finishTimeE,
            @RequestParam(name = "status", required = false) Integer status,
            @RequestParam(name = "pageNum", required = true) Integer pageNum,
            @RequestParam(name = "pageSize", required = true) Integer pageSize,
            HttpServletRequest request) {
        try {

            Map<String, String> map = new HashMap<>();

            if (finishTimeS != null) {
                map.put("finishTimeS", finishTimeS.toString());
            }

            if (finishTimeE != null) {
                map.put("finishTimeE", finishTimeE.toString());
            }
            if (status != null) {
                map.put("status", status.toString());
            }

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(outRechargeOrderService.getListOrderCount(map)));

        } catch (Exception e) {
            log.error("HighOrderController --> getUserOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/exportOrderListCount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出订单")
    public ResponseData exportOrderListCount(@RequestParam(name = "finishTimeS", required = false) Long finishTimeS,
                                             @RequestParam(name = "status", required = false) Integer status,
                                             @RequestParam(name = "finishTimeE", required = false) Long finishTimeE) {
        try {

            Map<String, String> map = new HashMap<>();

            if (finishTimeS != null) {
                map.put("finishTimeS", finishTimeS.toString());
            }

            if (finishTimeE != null) {
                map.put("finishTimeE", finishTimeE.toString());
            }
            if (status != null) {
                map.put("status", status.toString());
            }

            List<OutOrderModel> list = outRechargeOrderService.getListOrderCount(map);

            String name = "/outRechargeOrder/订单统计" + System.currentTimeMillis() + ".xlsx";
            String fileName = SysConst.getSysConfig().getFileUrl() + name;
            EasyExcel.write(fileName, ExportOutRechargeOrderCount.class).sheet("订单统计").doWrite(list);
            return ResponseMsgUtil.success(name);
        } catch (Exception e) {
            log.error("HighOrderController --> exportOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getUserCountList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询员工订单统计")
    public ResponseData getUserCountList(
            @RequestParam(name = "finishTimeS", required = false) Long finishTimeS,
            @RequestParam(name = "finishTimeE", required = false) Long finishTimeE,
            @RequestParam(name = "pageNum", required = true) Integer pageNum,
            @RequestParam(name = "pageSize", required = true) Integer pageSize,
            HttpServletRequest request) {
        try {

            Map<String, String> map = new HashMap<>();

            if (finishTimeS != null) {
                map.put("finishTimeS", finishTimeS.toString());
            }

            if (finishTimeE != null) {
                map.put("finishTimeE", finishTimeE.toString());
            }

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(outRechargeOrderService.getUserCountList(map)));

        } catch (Exception e) {
            log.error("HighOrderController --> getUserOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/exportUserOrderListCount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出员工订单")
    public ResponseData exportUserOrderListCount(@RequestParam(name = "finishTimeS", required = false) Long finishTimeS,
                                                 @RequestParam(name = "finishTimeE", required = false) Long finishTimeE) {
        try {

            Map<String, String> map = new HashMap<>();

            if (finishTimeS != null) {
                map.put("finishTimeS", finishTimeS.toString());
            }

            if (finishTimeE != null) {
                map.put("finishTimeE", finishTimeE.toString());
            }

            List<OutUserOrderModel> list = outRechargeOrderService.getUserCountList(map);

            String name = "/outRechargeOrder/员工订单统计" + System.currentTimeMillis() + ".xlsx";
            String fileName = SysConst.getSysConfig().getFileUrl() + name;
            EasyExcel.write(fileName, ExportOutRechargeUserOrderCount.class).sheet("订单统计").doWrite(list);
            return ResponseMsgUtil.success(name);
        } catch (Exception e) {
            log.error("HighOrderController --> exportOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/rechargeOrderByIndex", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "充值订单首页统计")
    public ResponseData rechargeOrderByIndex(
            @RequestParam(name = "code", required = true) Integer code) {
        try {

            return ResponseMsgUtil.success(outRechargeOrderService.rechargeOrderByIndex(code));

        } catch (Exception e) {
            log.error("HighOrderController --> getUserOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
