package cn.pluss.platform.controller.merchantOrder;

import cn.hutool.core.io.FileUtil;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.controller.BaseNoModelController;
import cn.pluss.platform.dto.SummaryOfWaterDTO;
import cn.pluss.platform.entitiy.ShiroUser;
import cn.pluss.platform.entity.MerchantChannel;
import cn.pluss.platform.entity.MerchantOrder;
import cn.pluss.platform.entity.MerchantStore;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.merchantChannel.MerchantChannelService;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.merchantProfit.MerchantProfitService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.refundOrder.MerchantRefundOrderService;
import cn.pluss.platform.ryx.RyxService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.util.ExcelUtil;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.vo.*;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("merchantOrder")
public class MerchantOrderController extends BaseNoModelController {


    private Integer PAGE_SIZE = 12;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private MerchantOrderService merchantOrderService;

    @Autowired
    private MerchantStoreService merchantStoreService;

    @Autowired
    private UserAppService userAppService;

    @Autowired
    private MerchantProfitService merchantProfitService;

    @Autowired
    private RyxService ryxService;

    @Resource
    private MerchantChannelService merchantChannelService;

    @Resource
    private MerchantRefundOrderService merchantRefundOrderService;

    /**
     * 引导页
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String initIndex() {
        List<MerchantChannel> channelList = merchantChannelService.getValidChannelList();
        request.setAttribute("channelList", channelList);
        return "merchantOrder/merchantOrderList";
    }

    @ResponseBody
    @RequestMapping(value = "/queryMerchantOrderByPage", method = RequestMethod.GET)
    public Map<String, Object> querPage(@RequestParam(name = "currPage") Integer currPage, MerchantOrder merchantOrder, @RequestParam(name = "size") Integer size, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageSize", size);
        map.put("offset", (currPage - 1) * size);
        Boolean bol = verifyUserRole();
        ShiroUser shiroUser = queryCurrentShiroUser();
        if (!bol) {
            map.put("merchantCode", shiroUser.getMerchantCode());
        }
        map.put("userId", merchantOrder.getUserId());
        map.put("merchantCode", merchantOrder.getMerchantCode());
        map.put("orderNumber", merchantOrder.getOrderNumber());// 订单号
        map.put("storeName", merchantOrder.getStoreName());// 门店名称
        if (StringUtil.isNotEmpty(merchantOrder.getPayTypeCode())) {
            String[] payTypeCodeArr = merchantOrder.getPayTypeCode().split("\\|");
            map.put("payTypeCode", payTypeCodeArr);//支付方式
        }
        map.put("alias", merchantOrder.getAlias());// 商家名称
        map.put("status", merchantOrder.getStatus());// 交易状态
        map.put("aisleSwitch", merchantOrder.getAisleSwitch());
        if (StringUtil.isNotEmpty(merchantOrder.getSettlementType())) {
            map.put("settlementType", merchantOrder.getSettlementType());// 结算类型
        }
        if (StringUtil.isNotEmpty(merchantOrder.getPayTypeName())) {
            switch (merchantOrder.getPayTypeName()) {// 支付方式
                case "1":
                    map.put("payTypeName", "微信");
                    break;
                case "2":
                    map.put("payTypeName", "支付宝");
                    break;
                case "3":
                    map.put("payTypeName", "随行支付宝支付");
                    break;
                case "4":
                    map.put("payTypeName", "随行微信支付");
                    break;
                case "5":
                    map.put("payTypeName", "随行刷卡支付");
                    break;
                case "6":
                    map.put("payTypeName", "随行云闪付支付");
            }
        }
        map.put("orderType", merchantOrder.getOrderType());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StringUtil.isNotEmpty(merchantOrder.getStartTime())) {
            String startTime = simpleDateFormat.format(merchantOrder.getStartTime());
            System.out.println("获取的开始时间startTime为:" + startTime);
            map.put("startTime", startTime);// 开始时间
        }
        if (StringUtil.isNotEmpty(merchantOrder.getEndTime())) {
            String endTime = simpleDateFormat.format(merchantOrder.getEndTime());
            System.out.println("获取的结束时间endTime为:" + endTime);
            map.put("endTime", endTime);// 结束时间
        }
        List<MerchantMangeOrderVO> merchantOrderList = null;
        Integer count = 0;
        // if (bol) {
            merchantOrderList = merchantOrderService.queryMerchantOrderPageShuju(map);
            count = merchantOrderService.queryMerchantOrderPageCountShuju(map);
        // } else {
        //     merchantOrderList = merchantOrderService.queryMerchantOrderNoPageShuju(map);
        //     count = merchantOrderService.queryMerchantOrderNoPageCountShuju(map);
        // }
        Boolean flag = false;
        for(String key:map.keySet()){//keySet获取map集合key的集合  然后在遍历key即可
            if("pageSize".equals(key) || "offset".equals(key)){
                continue;
            }
            if(map.get(key) != null && StringUtil.isNotEmpty(map.get(key).toString())){
                flag = true;
            }
        }
        if(!flag){
            map.put("createDate",DateUtils.toString(DateUtils.currentDate(),"yyyy-MM-dd"));
        }
        Map<String, Object> resultData = merchantOrderService.getOrderCountData(map);
        Map<String, Object> result = new HashMap<>(9);
        if (count == 0) {
            result.put("resultData", null);
        } else {
            result.put("resultData", resultData);
        }
        result.put("merchantOrderList", merchantOrderList);
        result.put("count", count);
        result.put("code", 200);
        result.put("pageCount", StringUtil.getPageCount(count, PAGE_SIZE));
        result.put("currPage", currPage);
//		if(resultData != null){
//			result.putAll(resultData);
//		}
        return result;
    }

    /**
     * 订单推广分润明细
     *
     * @return
     */
    @GetMapping("/profit/page2")
    @ResponseBody
    public Result<Map<String, Object>> orderProfitPage2(Page<MerchantOrderProfitVO> page, MerchantOrderVO condition, OrderItem orderItem) {
        Map<String, Object> map = new HashMap<>(16);
        Map<String, Object> result = new HashMap<>();
        map.put("pageSize", page.getSize());
        map.put("offset", (page.getSize() - 1) * PAGE_SIZE);
        map.put("profitCount", "all");
        if (StringUtil.isNotEmpty(condition.getUserId())) {
            map.put("userId", condition.getUserId());
        }
        if (StringUtil.isNotEmpty(condition.getAlias())) {
            map.put("merchantName", condition.getAlias());
        }
        if (StringUtil.isNotEmpty(condition.getOrderNumber())) {
            map.put("orderNumber", condition.getOrderNumber());
        }
        if (StringUtil.isNotEmpty(condition.getUserId())) {
            Map<String, Object> profitMap = merchantProfitService.getProfitCount(map);
            if (profitMap != null && profitMap.size() > 0) {
                result.put("transAmountCount", profitMap.get("transAmountCount"));
                result.put("shareAmountCount", profitMap.get("shareAmountCount"));
            } else {
                result.put("transAmountCount", "0.00");
                result.put("shareAmountCount", "0.00");
            }
            map.put("profitCount", "part");
        }
        List<MerchantOrderProfitVO> pageData = merchantOrderService.pageData(map);
        Integer count = merchantOrderService.pageDataCount(map);
        result.put("count", count);
        result.put("pageCount", StringUtil.getPageCount(count, PAGE_SIZE));
        result.put("currPage", page.getCurrent());

        page.setRecords(pageData);
        page.setTotal(count);

        result.put("pageData", page);

        return ResultGenerator.genSuccessResult(result);
    }

    /**
     * 订单推广分润明细
     *
     * @return
     */
    @RequestMapping(value = "/profit/page", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> orderProfitPage(@RequestParam(defaultValue = "1") Integer currPage, MerchantOrder order) {
        Map<String, Object> result = new HashMap<>(16);
        Map<String, Object> map = new HashMap<>(16);
        map.put("pageSize", PAGE_SIZE);
        map.put("offset", (currPage - 1) * PAGE_SIZE);
        map.put("profitCount", "all");
        if (StringUtil.isNotEmpty(order.getUserId())) {
            map.put("userId", order.getUserId());
        }
        if (StringUtil.isNotEmpty(order.getAlias())) {
            map.put("merchantName", order.getAlias());
        }
        if (StringUtil.isNotEmpty(order.getOrderNumber())) {
            map.put("orderNumber", order.getOrderNumber());
        }
        if (StringUtil.isNotEmpty(order.getUserId())) {
            Map<String, Object> profitMap = merchantProfitService.getProfitCount(map);
            if (profitMap != null && profitMap.size() > 0) {
                result.put("transAmountCount", profitMap.get("transAmountCount"));
                result.put("shareAmountCount", profitMap.get("shareAmountCount"));
            } else {
                result.put("transAmountCount", "0.00");
                result.put("shareAmountCount", "0.00");
            }
            map.put("profitCount", "part");
        }
        List<MerchantOrderProfitVO> pageData = merchantOrderService.pageData(map);
        Integer count = merchantOrderService.pageDataCount(map);
        result.put("orderProfitList", pageData);
        result.put("count", count);
        result.put("pageCount", StringUtil.getPageCount(count, PAGE_SIZE));
        result.put("currPage", currPage);
        return result;
    }

    @RequestMapping(value = "/profit", method = RequestMethod.GET)
    public String index() {
        return "merchantOrder/orderProfitList";
    }


    /**
     * 分页查询
     */
//	@RequestMapping(value = "/queryMerchantOrderByPage", method = RequestMethod.POST)
//	@ResponseBody
//	public Map<String, Object> queryMerchantOrderByPage(@RequestParam(defaultValue = "1") Integer currPage,
//			MerchantOrder merchantOrder) {
//		return result;
//	}

    /**
     * 查询详情
     */
    @RequestMapping(value = "/queryMerchantOrderDetails", method = RequestMethod.GET)
    public String queryMerchantOrderDetails(HttpServletRequest request, Integer id, Integer pageIndex) {

        if (id != null && id != 0) {
            MerchantOrder merchantOrder = new MerchantOrder();
            merchantOrder.setId(id.longValue());
            merchantOrder = merchantOrderService.queryMerchantOrder(merchantOrder);
            request.setAttribute("merchantOrder", merchantOrder);
            request.setAttribute("pageIndex", pageIndex);
        }
        return "merchantOrder/merchantOrderDetails";
    }

    /**
     * 查询详情
     */
    @RequestMapping(value = "/queryMerchantOrderBaseInfo", method = RequestMethod.GET)
    public String queryMerchantOrderBaseInfo(HttpServletRequest request, Integer id, Integer pageIndex) {

        if (id != null && id != 0) {
            MerchantOrder merchantOrder = new MerchantOrder();
            merchantOrder.setId(id.longValue());
            merchantOrder = merchantOrderService.queryMerchantOrder(merchantOrder);
            request.setAttribute("merchantOrder", merchantOrder);
            request.setAttribute("pageIndex", pageIndex);
        }
        return "merchantOrder/merchantOrderBaseInfo";
    }

    /**
     * 查询详情
     */
    @RequestMapping(value = "/queryMerchantOrderExtendsInfo", method = RequestMethod.GET)
    public String queryMerchantOrderExtendsInfo() {

        return "merchantOrder/merchantOrderExtendsInfo";
    }

    /**
     * 查询详情
     */
    @RequestMapping(value = "/queryMerchantOrderFunctionsInfo", method = RequestMethod.GET)
    public String queryMerchantOrderFunctionsInfo() {

        return "merchantOrder/merchantOrderFunctionsInfo";
    }

    /**
     * 保存对象
     *
     * @throws IOException
     */
    @RequestMapping(value = "/saveMerchantOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveMerchantOrder(MerchantOrder merchantOrder) {

        if (merchantOrder.getId() != null && merchantOrder.getId() != 0) {
            merchantOrderService.updateById(merchantOrder);
        } else {
            merchantOrderService.save(merchantOrder);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }

    /**
     * 修改对象
     *
     * @throws IOException
     */
    @RequestMapping(value = "/updateMerchantOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateMerchantOrder(Integer id) {

        MerchantOrder merchantOrder = new MerchantOrder();
        merchantOrder.setId(id.longValue());
        merchantOrderService.updateById(merchantOrder);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }

    /**
     * 删除对象
     *
     * @throws IOException
     */
    @RequestMapping(value = "/deleteMerchantOrder", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deleteMerchantOrder(Integer id) {
        MerchantOrder merchantOrder = new MerchantOrder();
        merchantOrder.setId(id.longValue());
        merchantOrderService.removeById(merchantOrder.getId());
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }

    /**
     * 跳转汇总流水
     *
     * @return
     */
    @RequestMapping(value = "/summaryOfWater", method = RequestMethod.GET)
    public String summaryOfWater() {
        ShiroUser user = queryCurrentShiroUser();
        // user.setMerchantCode("M800201909246546966");
        if (StringUtil.isNotEmpty(user)) {
            request.setAttribute("merchantCode", user.getMerchantCode());
            if (StringUtil.isNotEmpty(user.getMerchantCode())) {
                MerchantStore merchantStore = new MerchantStore();
                merchantStore.setMerchantCode(user.getMerchantCode());
                List<MerchantStore> merchantStoreList = merchantStoreService.queryMerchantStoreList(merchantStore);
                // 得到门店集合
                request.setAttribute("merchantStoreList", merchantStoreList);
                UserApp userApp = new UserApp();
                userApp.setUserType("staff");
                userApp.setMerchantCode(user.getMerchantCode());
                List<UserApp> userAppList = userAppService.queryUserAppList(userApp);
                // 得到员工集合
                request.setAttribute("userAppList", userAppList);
            }
        }
        return "merchantOrder/summaryOfWater";
    }

    /**
     * AJAX请求查询汇总流水数据
     */
    @RequestMapping(value = "/querySummaryOfWater", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> querySummaryOfWater(SummaryOfWaterDTO summaryOfWaterDTO) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        Map<String, Object> map = new HashMap<String, Object>(16);
        if (StringUtil.isNotEmpty(summaryOfWaterDTO.getPayTypeCodeList())) {
            map.put("payTypeCodeList", Arrays.asList(summaryOfWaterDTO.getPayTypeCodeList().split(",")));
        }
        if (StringUtil.isNotEmpty(summaryOfWaterDTO.getStaffCodeList())) {
            map.put("staffCodeList", Arrays.asList(summaryOfWaterDTO.getStaffCodeList().split(",")));
        }
        if (StringUtil.isNotEmpty(summaryOfWaterDTO.getStoreIdList())) {
            map.put("storeIdList", Arrays.asList(summaryOfWaterDTO.getStoreIdList().split(",")));
        }
        if (StringUtil.isNotEmpty(summaryOfWaterDTO.getTimeStatus())) {
            map.put("timeStatus", summaryOfWaterDTO.getTimeStatus());
        }
        if (StringUtil.isNotEmpty(summaryOfWaterDTO.getMerchantCode())) {
            map.put("merchantCode", summaryOfWaterDTO.getMerchantCode());
        } else {
            return result;
        }
        SummaryOfWaterVO summaryOfWaterVO = merchantOrderService.querySummaryOfWater(map);
        result.put("summaryOfWaterVO", summaryOfWaterVO);
        return result;
    }

    /**
     * 订单退款跳转页
     *
     * @return
     */
    @GetMapping(value = "/orderRefund")
    public String orderRefund() {
        return "merchantOrder/orderRefund";
    }

    @RequestMapping(value = "/queryOrderRefund", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryOrderRefund(@RequestParam(defaultValue = "1") Integer currPage,
                                                SummaryOfWaterDTO summaryOfWaterDTO) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        Map<String, Object> map = new HashMap<String, Object>(16);
        ShiroUser shiroUser = queryCurrentShiroUser();
        if (StringUtil.isNotEmpty(shiroUser.getMerchantCode())) {
            map.put("merchantCode", shiroUser.getMerchantCode());
        }
        if (StringUtil.isNotEmpty(summaryOfWaterDTO.getOrderType())) {
            map.put("orderType", summaryOfWaterDTO.getOrderType());
        }
        if (StringUtil.isNotEmpty(summaryOfWaterDTO.getPayTypeCodeList())) {
            map.put("payTypeCodeList", Arrays.asList(summaryOfWaterDTO.getPayTypeCodeList().split(",")));
        }
        if (StringUtil.isNotEmpty(summaryOfWaterDTO.getStaffCodeList())) {
            map.put("staffCodeList", Arrays.asList(summaryOfWaterDTO.getStaffCodeList().split(",")));
        }
        if (StringUtil.isNotEmpty(summaryOfWaterDTO.getStoreIdList())) {
            map.put("storeIdList", Arrays.asList(summaryOfWaterDTO.getStoreIdList().split(",")));
        }
        if (StringUtil.isNotEmpty(summaryOfWaterDTO.getTimeStatus())) {
            map.put("timeStatus", summaryOfWaterDTO.getTimeStatus());
        }
        map.put("pageSize", PAGE_SIZE);
        map.put("offset", (currPage - 1) * PAGE_SIZE);
        map.put("status", "2");
        List<MerchantOrder> merchantOrderList = merchantOrderService.queryMerchantOrderRefundPage(map);
        Integer count = merchantOrderService.queryMerchantOrderRefundPageCount(map);
        result.put("merchantOrderList", merchantOrderList);
        result.put("count", count);
        result.put("pageCount", StringUtil.getPageCount(count, PAGE_SIZE));
        result.put("currPage", currPage);
        return result;
    }

    /**
     * 店长审核通过
     *
     * @return
     */
    @RequestMapping(value = "/buinourPass", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> buinourPass(Integer id) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            MerchantOrder merchantOrder = new MerchantOrder();
            merchantOrder.setStatus("2");
            merchantOrder.setId(id.longValue());
            merchantOrderService.updateById(merchantOrder);
            result.put("data", "1");
        } catch (Exception e) {
            result.put("data", "0");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 店长审核拒绝
     *
     * @return
     */
    @RequestMapping(value = "/buinourRefuse", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> buinourRefuse(Integer id) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            MerchantOrder merchantOrder = new MerchantOrder();
            merchantOrder.setId(id.longValue());
            merchantOrder.setStatus("3");
            merchantOrderService.updateById(merchantOrder);
            result.put("data", "1");
        } catch (Exception e) {
            result.put("data", "0");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 店长退款
     *
     * @return
     */
    @RequestMapping(value = "/buinourRefund", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> buinourRefund(Integer id) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            MerchantOrder merchantOrder = new MerchantOrder();
            merchantOrder.setStatus("2");
            merchantOrder.setId(id.longValue());
            merchantOrderService.updateById(merchantOrder);
            result.put("data", "1");
        } catch (Exception e) {
            result.put("data", "0");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 店员发起退款
     *
     * @return
     */
    @RequestMapping(value = "/clerkSponsorRefund", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> clerkSponsorRefund(Integer id) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            MerchantOrder merchantOrder = new MerchantOrder();
            merchantOrder.setStatus("4");
            merchantOrder.setId(id.longValue());
            merchantOrderService.updateById(merchantOrder);
            result.put("data", "1");
        } catch (Exception e) {
            result.put("data", "0");
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping(value = "/dowloadExcel", method = RequestMethod.GET)
    @ResponseBody
    public void dow(HttpServletResponse response) throws IOException {
        ShiroUser shiroUser = queryCurrentShiroUser();
        Boolean isAdmin = verifyUserRole();
        if (isAdmin) {
            String[] title = new String[]{"订单号", "商家名称", "门店名称", "支付方式名称", "消费金额", "交易时间", "交易状态"};
            List<MerchantOrder> merchantOrder = merchantOrderService.list();
            List<MerchantOrderDVO> mVos = new ArrayList<MerchantOrderDVO>();
            for (MerchantOrder merchantOrder2 : merchantOrder) {
                mVos.add(new MerchantOrderDVO(merchantOrder2));
            }
            HSSFWorkbook workbook = ExcelUtil.getHSSFWorkbook("管理员", title, mVos);
            String fileName = "交易查询.xls";
            download(response, fileName, workbook);
        } else {
            if (StringUtil.isNotEmpty(shiroUser.getMerchantCode())) {
                String[] title = new String[]{"订单号", "商家名称", "门店名称", "支付方式名称", "消费金额", "交易时间", "交易状态"};
                MerchantOrder m = new MerchantOrder();
                m.setMerchantCode(shiroUser.getMerchantCode());
                List<MerchantOrder> merchantOrder = merchantOrderService.list(new QueryWrapper<>(m));
                List<MerchantOrderDVO> mVos = new ArrayList<MerchantOrderDVO>();
                for (MerchantOrder merchantOrder2 : merchantOrder) {
                    mVos.add(new MerchantOrderDVO(merchantOrder2));
                }
                HSSFWorkbook workbook = ExcelUtil.getHSSFWorkbook("管理员", title, mVos);
                String fileName = "交易查询.xls";
                download(response, fileName, workbook);
            }
        }
    }

    private void download(HttpServletResponse response, String fileName, HSSFWorkbook workbook) throws IOException {
        // 文件下载
        String downName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + downName);
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
    }

    @RequestMapping(value = "/dowOrderRefundExcel", method = RequestMethod.GET)
    @ResponseBody
    public void dowOrderRefund(HttpServletResponse response) throws IOException {
        ShiroUser shiroUser = queryCurrentShiroUser();
        Boolean isAdmin = verifyUserRole();
        if (isAdmin) {
            String[] title = new String[]{"订单号", "商家名称", "门店名称", "支付方式名称", "消费金额", "交易流水号", "交易时间", "交易状态"};
            List<MerchantOrder> merchantOrders = merchantOrderService.list();
            List<MerchantOrderDVO> mVos = new ArrayList<MerchantOrderDVO>();
            for (MerchantOrder merchantOrder2 : merchantOrders) {
                mVos.add(new MerchantOrderDVO(merchantOrder2));
            }
            HSSFWorkbook workbook = ExcelUtil.getHSSFWorkbook("管理员", title, mVos);
            String fileName = "退款订单.xls";
            download(response, fileName, workbook);
        } else {
            if (StringUtil.isNotEmpty(shiroUser.getMerchantCode())) {
                String[] title = new String[]{"订单号", "商家名称", "门店名称", "支付方式名称", "消费金额", "交易流水号", "交易时间", "交易状态"};
                MerchantOrder merchantOrder = new MerchantOrder();
                merchantOrder.setMerchantCode(shiroUser.getMerchantCode());
                List<MerchantOrder> merchantOrders = merchantOrderService.list(new QueryWrapper<>(merchantOrder));
                List<MerchantOrderDVO> mVos = new ArrayList<MerchantOrderDVO>();
                for (MerchantOrder merchantOrder2 : merchantOrders) {
                    mVos.add(new MerchantOrderDVO(merchantOrder2));
                }
                HSSFWorkbook workbook = ExcelUtil.getHSSFWorkbook("管理员", title, mVos);
                String fileName = "退款订单.xls";
                download(response, fileName, workbook);
            }
        }
    }

    /**
     *
     * querySumEarnings:(查询平台/商家总的收益). <br/>
     *
     * @author Administrator
     * @return
     * @since JDK 1.8
     */
//	@PostMapping(value="/querySumEarnings")
//	@ResponseBody
//	public Map<String, Object> querySumEarnings(@RequestParam Map<String,Object> params) {
//		Map<String, Object> resultMap=new HashMap<String, Object>(16);
//
//		Map<String,Object> result = merchantOrderService.querySumCount(params);
//
//		//Map<String, Object> map=new HashMap<String, Object>(16);
//		/*Double shareoneySum1=merchantProfitService.queryMerchantProfitSumPrice(null);
//		System.out.println("总收益"+shareoneySum1);
//		//粉丝奖励总额
//				List<Fans> fansList= fansService.queryFansList(null);
//		        Double fansShareMoneySum1=0.0;
//				for(Fans li:fansList) {
//					String money=li.getShareMoney();
//					if(money!=null) {
//						Double d=Double.parseDouble(money);
//						fansShareMoneySum1+=d;
//					}
//				}
//
//
//				//交易总额
//				Map<String, Object> orderMap = new HashMap<String, Object>();
//				orderMap.put("status",1);
//				orderMap.put("limit",1000000000);
//				orderMap.put("offset",0);
//				Double orderFeeSum1=0.0;
//
//				List<MerchantOrder> merchantOrderList = merchantOrderService.queryMerchantOrderPage(orderMap);
//				for(MerchantOrder li:merchantOrderList) {
//					Double money=li.getConsumeFee();
//					if(money!=null) {
//						orderFeeSum1+=money;
//					}
//				}
//
//
//		*//*
//		 * map.put("startTime", startTime); map.put("endTime", endTime); Boolean isAdmin
//		 * = verifyUserRole(); ShiroUser shiroUser = queryCurrentShiroUser();
//		 * MerchantMangeOrderVO merchantMangeOrderVO =new MerchantMangeOrderVO();
//		 * if(isAdmin) { merchantMangeOrderVO =
//		 * merchantOrderService.querySumEarnings(map); resultMap.put("isAdmin", "1");
//		 * }else { String merchantCode = shiroUser.getMerchantCode();
//		 * if(StringUtil.isEmpty(merchantCode)) { map.put("merchantCode",
//		 * StringUtil.genRandomNum(33)); }else { map.put("merchantCode", merchantCode);
//		 * } merchantMangeOrderVO=merchantOrderService.querySumEarnings(map);
//		 * resultMap.put("isAdmin", "0"); }
//		 *//*
//
//		//resultMap.put("merchantMangeOrderVO", merchantMangeOrderVO);
//
//		Double shareoneySum=StringUtil.bigDecimal(shareoneySum1);
//		Double fansShareMoneySum=StringUtil.bigDecimal(fansShareMoneySum1);//粉丝奖励金额
//		Double orderFeeSum=StringUtil.bigDecimal(orderFeeSum1);
//		Double sum1=fansShareMoneySum+shareoneySum1;//总收益
//		Double sum=StringUtil.bigDecimal(sum1);
//		resultMap.put("shareoneySum", shareoneySum);//推广分润
//		resultMap.put("fansShareMoneySum", fansShareMoneySum);//粉丝奖励总额
//		resultMap.put("orderFeeSum", orderFeeSum);//实际收益
//		resultMap.put("sum", sum);//总收益*/
//		if(result == null){
//			result = new HashMap<>();
//		}
//		return result;
//	}

    /**
     * 订单补单参数
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/suppleOrder/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Result suppleOrder(@PathVariable("id") Integer id) {
        try {
            return merchantOrderService.suppleOrder(id);
        } catch (Exception e) {
            e.printStackTrace();
            MsgException.throwException(e.getMessage());
        }
        return ResultGenerator.genFailResult("补单失败");
    }

    /**
     * 数据同步
     */
    @RequestMapping(value = "/syncPluginOrder", method = RequestMethod.POST)
    @ResponseBody
    public Result syncPluginOrder(Date startDate, Date endDate) {
        int i = DateUtils.differentDaysByMillisecond(startDate, endDate);
        if (i > 0) {
            return ResultGenerator.genFailResult("日期相差超过一天");
        }
        String date = DateUtils.formatDateDefault(startDate, "yyyyMMdd");
        String nowDate = DateUtils.formatDateDefault(new Date(), "yyyyMMdd");
        if (Integer.parseInt(nowDate) - Integer.parseInt(date) < 1) {
            return ResultGenerator.genFailResult("同步数据的日期不能选择当天的日期！");
        }
        try {
            JSONObject result = ryxService.downloadFtpFile(date);
            if (result == null) {
                return ResultGenerator.genFailResult("文件下载失败");
            }
            String uploadPath = result.getString("uploadPath");
            String filePath = result.getString("filePath");
            //读取文件
            merchantOrderService.readCSV(filePath);
            //删除文件
            FileUtil.del(uploadPath);
            return ResultGenerator.genSuccessResult("数据同步成功！");
        } catch (Exception e) {
            e.printStackTrace();
            MsgException.throwException(e.getMessage());
        }
        return ResultGenerator.genSuccessResult("数据同步失败！");
    }

    /**
     * 获取通道对账文件下载地址
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/getChannelFileUrl", method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> getChannelFileUrl(String accountDate,Integer channel,Integer type) {
        return merchantOrderService.getChannelFileUrl(accountDate,channel,type);
    }
}
