package com.order.controller.business;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.BsOrderCoupon;
import com.hfkj.entity.FileRecords;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.model.order.OrderCouponModel;
import com.hfkj.service.coupon.BsOrderCouponNoService;
import com.hfkj.service.coupon.BsOrderCouponService;
import com.hfkj.service.file.FileRecordsService;
import com.hfkj.sysenum.SecUserObjectTypeEnum;
import com.hfkj.sysenum.fileRecords.FileRecordsEnum;
import com.hfkj.sysenum.order.OrderChildStatusEnum;
import com.hfkj.sysenum.order.OrderCouponNoStatusEnum;
import com.hfkj.sysenum.order.OrderPayChannelEnum;
import com.hfkj.sysenum.order.OrderPayTypeEnum;
import com.order.utils.excel.OrderCouponExcelMergeHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.DateUtils;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

/**
 * @className: OrderCouponController
 * @author: HuRui
 * @date: 2024/5/11
 **/
@Controller
@RequestMapping(value="/coupon")
@Api(value="卡券订单业务")
public class OrderCouponController {
    Logger log = LoggerFactory.getLogger(OrderCouponController.class);

    @Resource
    private BsOrderCouponService orderCouponService;
    @Resource
    private BsOrderCouponNoService orderCouponNoService;
    @Resource
    private UserCenter userCenter;
    @Resource
    private FileRecordsService fileRecordsService;

    @RequestMapping(value="/queryCouNo",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询卡密")
    public ResponseData queryCouNo(@RequestParam(value = "orderChildNo" , required = true) String orderChildNo) {
        try {
            // 卡券订单
            BsOrderCoupon orderCoupon = orderCouponService.getDetailByChildOrderNo(orderChildNo);
            if (orderCoupon == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的卡券订单");
            }

            return ResponseMsgUtil.success(orderCouponNoService.getListByCouponOrderId(orderCoupon.getId()));

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

    @RequestMapping(value="/queryDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询交易订单详情")
    public ResponseData queryDetail(@RequestParam(value = "orderChildNo" , required = true) String orderChildNo) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("order", orderCouponService.getDetailByChildOrderNo(orderChildNo));

            Map<String,Object> goodsParam = new HashMap<>();
            goodsParam.put("orderChildNo", orderChildNo);
            param.put("goods", orderCouponService.getOrderList(goodsParam));

            return ResponseMsgUtil.success(param);

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

    @RequestMapping(value="/queryList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询交易订单列表")
    public ResponseData queryList(@RequestParam(value = "orderNo" , required = false) String orderNo,
                                  @RequestParam(value = "userPhone" , required = false) String userPhone,
                                  @RequestParam(value = "tradeStatus" , required = false) Integer tradeStatus,
                                  @RequestParam(value = "goodsName" , required = false) String goodsName,
                                  @RequestParam(value = "payType" , required = false) Integer payType,
                                  @RequestParam(value = "channelOrderNo" , required = false) String channelOrderNo,
                                  @RequestParam(value = "couNo" , required = false) String couNo,
                                  @RequestParam(value = "couStatus" , required = false) Integer couStatus,
                                  @RequestParam(value = "createTimeS" , required = false) Long createTimeS,
                                  @RequestParam(value = "createTimeE" , required = false) Long createTimeE,
                                  @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                  @RequestParam(value = "pageSize" , required = true) Integer pageSize) {
        try {
            Map<String,Object> param = new HashMap<>();
            SecUserSessionObject userSessionObject = userCenter.getSessionModel(SecUserSessionObject.class);
            if (SecUserObjectTypeEnum.type1.getCode() == userSessionObject.getAccount().getObjectType()) {

            } else if (SecUserObjectTypeEnum.type2.getCode() == userSessionObject.getAccount().getObjectType()) {
                param.put("merId", userSessionObject.getAccount().getObjectId());
            }

            if (userSessionObject.getAccount().getPlatformCode() != null) {
                param.put("platformCode", userSessionObject.getAccount().getPlatformCode());
            }

            param.put("orderNo", orderNo);
            param.put("userPhone", userPhone);
            param.put("tradeStatus", tradeStatus);
            param.put("goodsName", goodsName);
            param.put("payType", payType);
            param.put("channelOrderNo", channelOrderNo);
            param.put("couNo", couNo);
            param.put("couStatus", couStatus);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(orderCouponService.getOrderList(param)));

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

    @RequestMapping(value="/export",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出订单")
    public ResponseData export(@RequestParam(value = "orderNo" , required = false) String orderNo,
                                  @RequestParam(value = "userPhone" , required = false) String userPhone,
                                  @RequestParam(value = "tradeStatus" , required = false) Integer tradeStatus,
                                  @RequestParam(value = "goodsName" , required = false) String goodsName,
                                  @RequestParam(value = "payType" , required = false) Integer payType,
                                  @RequestParam(value = "channelOrderNo" , required = false) String channelOrderNo,
                                  @RequestParam(value = "couNo" , required = false) String couNo,
                                  @RequestParam(value = "couStatus" , required = false) Integer couStatus,
                                  @RequestParam(value = "createTimeS" , required = false) Long createTimeS,
                                  @RequestParam(value = "createTimeE" , required = false) Long createTimeE) {
        FileRecords fileRecords = new FileRecords();

        try {
            Map<String,Object> param = new HashMap<>();
            SecUserSessionObject userSessionObject = userCenter.getSessionModel(SecUserSessionObject.class);
            if (SecUserObjectTypeEnum.type1.getCode() == userSessionObject.getAccount().getObjectType()) {

            } else if (SecUserObjectTypeEnum.type2.getCode() == userSessionObject.getAccount().getObjectType()) {
                param.put("merId", userSessionObject.getAccount().getObjectId());
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NOT_PERMISSIONS, "");
            }
            param.put("orderNo", orderNo);
            param.put("userPhone", userPhone);
            param.put("tradeStatus", tradeStatus);
            param.put("goodsName", goodsName);
            param.put("payType", payType);
            param.put("channelOrderNo", channelOrderNo);
            param.put("couNo", couNo);
            param.put("couStatus", couStatus);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);

            // 下载记录
            fileRecords.setCreateTime(new Date());
            fileRecords.setBusinessType(FileRecordsEnum.status2.getCode());
            fileRecords.setDownloadConditions(param.toString());
            fileRecords.setOpId(userSessionObject.getAccount().getId());
            fileRecords.setOpName(userSessionObject.getAccount().getUserName());
            fileRecords.setStatus(2);
            fileRecords.setDownloadStatus(2);
            fileRecords.setTitle(FileRecordsEnum.status2.getName() + DateUtil.date2String(new Date(System.currentTimeMillis()),DateUtil.YMDHMS) + ".xlsx");
            fileRecords.setFileUrl(CommonSysConst.getSysConfig().getDomainName() + "/filesystem/temporary/" + fileRecords.getTitle());
            fileRecords.setType("2");
            fileRecordsService.create(fileRecords);

            // 查询数据
            List<OrderCouponModel> orderList = orderCouponService.getOrderList(param);
            for (OrderCouponModel coupon : orderList) {
                if (coupon.getPayChannel() != null) {
                    coupon.setPayChannel(OrderPayChannelEnum.getData(Integer.valueOf(coupon.getPayChannel())).getName());
                }
                if (coupon.getPayType() != null) {
                    coupon.setPayType(OrderPayTypeEnum.getData(Integer.valueOf(coupon.getPayType())).getName());
                }
                coupon.setTradeStatus(OrderChildStatusEnum.getData(Integer.valueOf(coupon.getTradeStatus())).getName());
                coupon.setCouStatus(OrderCouponNoStatusEnum.getData(Integer.valueOf(coupon.getCouStatus())).getName());
                coupon.setExceptionStatus(Boolean.getBoolean(coupon.getExceptionStatus())?"是":"否");
            }

            // 文件存放地址
            String fileUrl = CommonSysConst.getSysConfig().getFileUrl() + "/temporary/";
            File file = new File(fileUrl);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 需要合并的列
            int[] mergeColumnIndex = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
            // 需要从第几行开始合并
            int mergeRowIndex = 1;

            // 生成excel文件
            EasyExcel.write(fileUrl+fileRecords.getTitle())
                    .head(OrderCouponModel.class)
                    .sheet("虚拟商品订单")
                    .registerWriteHandler(new OrderCouponExcelMergeHandler(mergeRowIndex, mergeColumnIndex))
                    .doWrite(orderList);

            fileRecords.setStatus(1);
            fileRecords.setUpdateTime(new Date());
            fileRecordsService.update(fileRecords);
            return ResponseMsgUtil.success(fileRecords);

        } catch (Exception e) {
            fileRecords.setStatus(3);
            fileRecords.setUpdateTime(new Date());
            fileRecords.setExt1(e.toString());
            fileRecordsService.update(fileRecords);

            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }





}
