package com.bweb.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bweb.config.SysConst;
import com.bweb.excelListener.ImportCouponListener;
import com.bweb.model.ImportCouponModel;
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.GenerateCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.MemberValidateUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.HuiLianTongConfig;
import com.hai.config.HuiLianTongUnionCardConfig;
import com.hai.entity.*;
import com.hai.enum_type.ApproveType;
import com.hai.model.HighCouponHandselModel;
import com.hai.model.HighCouponModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/11 22:16
 */
@Controller
@RequestMapping(value = "/coupon")
@Api(value = "卡卷接口")
public class HighCouponController {

    private static Logger log = LoggerFactory.getLogger(HighCouponController.class);

    @Autowired
    private UserCenter userCenter;

    @Resource
    private HighMerchantService highMerchantService;

    @Resource
    private HighCouponService highCouponService;

    @Resource
    private HighCouponHandselService highCouponHandselService;

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @Resource
    private HighApproveService highApproveService;

    @Resource
    private HuiLianTongConfig huiLianTongConfig;

    @RequestMapping(value="/insertCoupon",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "增加卡卷")
    public ResponseData insertCoupon(@RequestBody HighCoupon highCoupon, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighCouponController -> insertCoupon() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }

            if (highCoupon.getMerchantId() == null
                    || StringUtils.isBlank(highCoupon.getCouponName())
                    || StringUtils.isBlank(highCoupon.getCouponImg())
                    || StringUtils.isBlank(highCoupon.getCouponCarouselImg())
                    || StringUtils.isBlank(highCoupon.getCouponDesc())
                    || highCoupon.getCouponType() == null
                    || highCoupon.getPayType() == null
//                    || highCoupon.getDisplayArea() == null
                    || highCoupon.getSalesEndTime() == null
                    || highCoupon.getRecycleDay() == null
                    || highCoupon.getLimitNumber()== null
                    || highCoupon.getSalesPrice()== null
                    || highCoupon.getDiscountPrice() == null
                    || highCoupon.getIsPresent() == null) {
                log.error("HighCouponController -> insertCoupon() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 校验名称是否重复
            if (highCouponService.getCouponByCouponName(userInfoModel.getBsCompany().getId(),highCoupon.getCouponName()) > 0) {
                log.error("HighCouponController -> insertCoupon() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_CODE_NAME, "");
            }

            // 折扣价格 大于 销售价格
            if (highCoupon.getDiscountPrice().compareTo(highCoupon.getSalesPrice()) == 1) {
                log.error("HighCouponController -> insertCoupon() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.DISCOUNT_PRICE_BIG_SALES_PRICE_ERROR, "");
            }

            // 是否赠送卡卷
            if (highCoupon.getIsPresent()) {
                if (highCoupon.getHandselCouponId() == null || highCoupon.getHandselCouponId().size() == 0) {
                    log.error("HighCouponController -> insertCoupon() error!","请选择赠送卡卷名单");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.SELECT_HANDSEL_COUPON_ERROR, "");
                }
                highCoupon.setHandselCouponList(new ArrayList<>());
                HighCouponHandselModel highCouponHandsel;
                for (Long couponId : highCoupon.getHandselCouponId()) {
                    highCouponHandsel = new HighCouponHandselModel();
                    highCouponHandsel.setHandselCouponId(couponId);
                    highCouponHandsel.setCreateTime(new Date());
                    highCouponHandsel.setStatus(1); // 状态  0：删除  1：正常
                    highCouponHandsel.setOperatorId(userInfoModel.getSecUser().getId());
                    highCouponHandsel.setOperatorName(userInfoModel.getSecUser().getUserName());
                    highCoupon.getHandselCouponList().add(highCouponHandsel);
                }
            }

            // 查询商户
            HighMerchant merchant = highMerchantService.getMerchantById(highCoupon.getMerchantId());
            if (merchant == null) {
                log.error("HighCouponController -> insertCoupon() error!","未找到商户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOF_FOUND, "");
            }

            // 计算销售截止时间
            Calendar salesEndTime = Calendar.getInstance();
            salesEndTime.setTime(highCoupon.getSalesEndTime());
            salesEndTime.set(Calendar.HOUR_OF_DAY, 23);
            salesEndTime.set(Calendar.MINUTE, 59);
            salesEndTime.set(Calendar.SECOND, 59);
            highCoupon.setSalesEndTime(salesEndTime.getTime());

            String setCouponKey = DateUtil.date2String(new Date(), "yyyyMMddHHmmss");	//订单号生成  年月日小时分秒 + 5位随机数
            highCoupon.setCouponKey(setCouponKey);
            highCoupon.setCompanyId(merchant.getCompanyId());
            highCoupon.setOperatorId(userInfoModel.getSecUser().getId());
            highCoupon.setOperatorName(userInfoModel.getSecUser().getUserName());
            highCoupon.setCreateTime(new Date());
            highCoupon.setUpdateTime(new Date());
            highCoupon.setStatus(1);  // 状态：0.删除 1.编辑中  2.已上架  3.已下架   101.上架审批中 102.上架审批驳回
            highCouponService.insertCoupon(highCoupon);

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

    @RequestMapping(value="/updateCoupon",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改卡卷")
    public ResponseData updateCoupon(@RequestBody HighCoupon highCoupon, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (highCoupon.getId() == null
                    || highCoupon.getMerchantId() == null
                    || StringUtils.isBlank(highCoupon.getCouponName())
                    || StringUtils.isBlank(highCoupon.getCouponImg())
                    || StringUtils.isBlank(highCoupon.getCouponCarouselImg())
                    || StringUtils.isBlank(highCoupon.getCouponDesc())
                    || highCoupon.getCouponType() == null
                    || highCoupon.getPayType() == null
//                    || highCoupon.getDisplayArea() == null
                    || highCoupon.getSalesEndTime() == null
                    || highCoupon.getRecycleDay() == null
                    || highCoupon.getLimitNumber()== null
                    || highCoupon.getSalesPrice()== null
                    || highCoupon.getDiscountPrice() == null
                    || highCoupon.getIsPresent() == null) {
                log.error("HighCouponController -> insertCoupon() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 折扣价格 大于 销售价格
            if (highCoupon.getDiscountPrice().compareTo(highCoupon.getSalesPrice()) == 1) {
                log.error("HighCouponController -> insertCoupon() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.DISCOUNT_PRICE_BIG_SALES_PRICE_ERROR, "");
            }

            // 查询卡券
            HighCoupon coupon = highCouponService.getCouponById(highCoupon.getId());
            if (coupon == null) {
                log.error("HighCouponController -> updateCoupon() error!","未找到卡卷信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
            }

            // 校验名称是否重复
            if (!highCoupon.getCouponName().equals(coupon.getCouponName()) && highCouponService.getCouponByCouponName(userInfoModel.getBsCompany().getId(),highCoupon.getCouponName()) > 0) {
                log.error("HighCouponController -> insertCoupon() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_CODE_NAME, "");
            }

            // 是否赠送卡卷
            if (highCoupon.getIsPresent()) {
                if (highCoupon.getHandselCouponId() == null || highCoupon.getHandselCouponId().size() == 0) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.SELECT_HANDSEL_COUPON_ERROR, "");
                }
                HighCouponHandselModel highCouponHandsel;
                // 上传数据与数据库对比，需要新增的数据
                for (Long couponId : highCoupon.getHandselCouponId()) {
                    List<HighCouponHandselModel> collect = coupon.getHandselCouponList().stream().filter(o -> o.getHandselCouponId().equals(couponId)).collect(Collectors.toList());
                    if (collect.size() == 0) {
                        highCouponHandsel = new HighCouponHandselModel();
                        highCouponHandsel.setHandselCouponId(couponId);
                        highCouponHandsel.setCreateTime(new Date());
                        highCouponHandsel.setStatus(1);
                        highCouponHandsel.setOperatorId(userInfoModel.getSecUser().getId());
                        highCouponHandsel.setOperatorName(userInfoModel.getSecUser().getUserName());
                        coupon.getHandselCouponList().add(highCouponHandsel);
                    }
                }

                // 上传数据与数据库对比，需要删除的数据
                for (HighCouponHandsel handsel : coupon.getHandselCouponList()) {
                    List<Long> collect = highCoupon.getHandselCouponId().stream().filter(o -> o.equals(handsel.getHandselCouponId())).collect(Collectors.toList());
                    if (collect.size() == 0) {
                        handsel.setStatus(0);
                    }
                }
            }

            // 如果不赠送了
            if (!highCoupon.getIsPresent()) {
                List<HighCouponHandselModel> handselListByCoupon = highCouponHandselService.getHandselListByCoupon(highCoupon.getId());
                for (HighCouponHandsel handsel : handselListByCoupon) {
                    handsel.setStatus(0);
                }
                coupon.setHandselCouponList(handselListByCoupon);
            }

            // 查询商户
            HighMerchant merchant = highMerchantService.getMerchantById(highCoupon.getMerchantId());
            if (merchant == null) {
                log.error("HighCouponController -> updateCoupon() error!","未找到商户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOF_FOUND, "");
            }
            coupon.setCouponSource(highCoupon.getCouponSource());
            coupon.setMerchantId(highCoupon.getMerchantId());
            coupon.setCouponName(highCoupon.getCouponName());
            coupon.setCouponImg(highCoupon.getCouponImg());
            coupon.setCouponCarouselImg(highCoupon.getCouponCarouselImg());
            coupon.setCouponDesc(highCoupon.getCouponDesc());
            coupon.setPayType(highCoupon.getPayType());
            coupon.setSalesEndTime(highCoupon.getSalesEndTime());
            coupon.setRecycleDay(highCoupon.getRecycleDay());
            coupon.setLimitNumber(highCoupon.getLimitNumber());
            coupon.setSalesPrice(highCoupon.getSalesPrice());
            coupon.setDiscountPrice(highCoupon.getDiscountPrice());
            coupon.setIsPresent(highCoupon.getIsPresent());
            coupon.setBuyPoints(highCoupon.getBuyPoints());
            coupon.setOperatorId(userInfoModel.getSecUser().getId());
            coupon.setGoodsTypeId(highCoupon.getGoodsTypeId());
            coupon.setBrandId(highCoupon.getBrandId());
            coupon.setOperatorName(userInfoModel.getSecUser().getUserName());
            coupon.setUpdateTime(new Date());
            coupon.setStatus(3);  // 状态：0.删除 1.编辑中  2.已上架  3.已下架 101.上架审批中 102.上架审批驳回
            highCouponService.updateCoupon(coupon);

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

    @RequestMapping(value="/upShelfApprove",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "卡卷上架审批")
    public ResponseData upShelfApprove(@RequestParam(name = "id", required = true) Long id, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            // 查询卡券
            HighCoupon coupon = highCouponService.getCouponById(id);
            if (coupon == null) {
                log.error("HighCouponController -> upShelfApprove() error!","未找到卡卷信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
            }
            // 如果卡卷状态不处于  编辑中、已下架、审上架批驳回
            if (coupon.getStatus() != 1 && coupon.getStatus() != 3 && coupon.getStatus() != 102) {
                log.error("HighCouponController -> upShelfApprove() error!","卡卷状态错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_UNABLE_UP_SHELF, "");
            }

            // 中石化
            if (coupon.getCouponSource() != null && coupon.getCouponSource() != 4) {
                // 根据卡卷查询 销售码库存
                if (highCouponCodeService.getStockCountByCoupon(coupon.getId()) == 0) {
                    log.error("HighCouponController -> upShelfApprove() error!","卡卷库存数量错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_STOCK_ERROR, "");
                }
            }

            HighApprove approve = new HighApprove();
            approve.setObjectType(ApproveType.UP_SHELF_APPROVE.getType());
            approve.setObjectId(id);
            approve.setObjectName(coupon.getCouponName());
            approve.setApproveSerialNo(DateUtil.date2String(new Date(), "yyyyMMddHHmmss"));
            approve.setStatus(1);
            approve.setCreateTime(new Date());
            approve.setUpdateTime(new Date());
            approve.setSubmitOperatorId(userInfoModel.getSecUser().getId());
            approve.setSubmitOperatorName(userInfoModel.getSecUser().getUserName());

            // 增加审批
            highApproveService.insertApprove(approve);

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("HighCouponController -> upShelfApprove() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/ofShelfApprove",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "卡卷下架")
    public ResponseData ofShelfApprove(@RequestParam(name = "id", required = true) Long id) {
        try {

            highCouponService.ofShelfCoupon(id);

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("HighCouponController -> ofShelfApprove() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/deleteCoupon",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除卡卷")
    public ResponseData deleteCoupon(@RequestParam(name = "id", required = true) Long id) {
        try {

            highCouponService.deleteCoupon(id);

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("HighCouponController -> deleteCoupon() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getCouponById",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id 查询卡卷")
    public ResponseData getCouponById(@RequestParam(name = "id", required = true) Long id) {
        try {

            return ResponseMsgUtil.success(highCouponService.getCouponById(id));

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

    @RequestMapping(value="/getCouponList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "卡卷列表")
    public ResponseData getCouponList(
            @RequestParam(name = "merchantId", required = false) Long merchantId,
            @RequestParam(name = "couponName", required = false) String couponName,
            @RequestParam(name = "couponType", required = false) Integer couponType,
            @RequestParam(name = "displayArea", required = false) Integer displayArea,
            @RequestParam(name = "couponSource", required = false) Integer couponSource,
            @RequestParam(name = "brandId", required = false) Integer brandId,
            @RequestParam(name = "goodsTypeId", required = false) Integer goodsTypeId,
            @RequestParam(name = "status", required = false) Integer status,
            @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();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighCouponController -> getCouponList() error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("companyId", userInfoModel.getBsCompany().getId());
            map.put("merchantId", merchantId);
            map.put("couponName", couponName);
            map.put("couponType", couponType);
            map.put("brandId", brandId);
            map.put("goodsTypeId", goodsTypeId);
            map.put("displayArea", displayArea);
            map.put("couponSource", couponSource);
            map.put("status", status);


            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(highCouponService.getCouponList(map)));
        } catch (Exception e) {
            log.error("HighCouponController -> getCouponList() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/importStock",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "导入卡卷库存（外部卷）")
    public ResponseData importStock(@RequestParam(name = "couponId", required = true) Long couponId,
                                    @RequestParam(value = "file" , required = true) MultipartFile files,
                                    HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            // 查找卡卷
            HighCoupon coupon = highCouponService.getCouponById(couponId);
            if (coupon == null) {
                log.error("HighCouponController -> writeStock() error!","未找到卡卷信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
            }
            if (coupon.getCouponType() != 2) {
                log.error("HighCouponController -> writeStock() error!","卡卷类型错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_TYPE_ERROR, "");
            }

            ImportCouponListener importCouponListener = new ImportCouponListener();
            importCouponListener.initData(coupon,userInfoModel, highCouponCodeService);
            EasyExcel.read(files.getInputStream(), ImportCouponModel.class, importCouponListener).sheet().doRead();

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

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

    @RequestMapping(value="/exportStock",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "导出卡卷库存")
    public ResponseData exportStock(@RequestBody JSONObject body, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            if (body == null || body.getLong("couponId") == null) {
                log.error("HighCouponController -> exportStock() error!","请求参数校验失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查找卡卷
            HighCoupon coupon = highCouponService.getCouponById(body.getLong("couponId"));
            if (coupon == null) {
                log.error("HighCouponController -> writeStock() error!","未找到卡卷信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
            }

            Map<String, Object> param = new HashMap<>();
            param.put("couponId", body.getLong("couponId"));
            param.put("status", body.getInteger("status"));
            param.put("createTimeS", body.getLong("createTimeS"));
            param.put("createTimeE", body.getLong("createTimeE"));
            // 销售码
            List<HighCouponCode> codeList = highCouponCodeService.getCouponCodeList(param);

            List<String> headList = new ArrayList<>();;
            headList.add("序号");
            headList.add("消费码key");
            headList.add("消费码");
            headList.add("状态");
            headList.add("使用门店");
            headList.add("领取时间");
            headList.add("消费时间");
            headList.add("销售截止时间");
            headList.add("使用截止时间");
            headList.add("创建时间");

            List<List<Object>> dataList = new ArrayList<>();
            List<Object> data;
            Integer i = 1;

            for (HighCouponCode couponCode : codeList) {
                data = new ArrayList<>();
                data.add(i++);
                data.add(couponCode.getCodeKey());
                data.add(couponCode.getSalesCode());
                if (couponCode.getStatus() == 1) {
                    data.add("待销售");
                } else if (couponCode.getStatus() == 2) {
                    data.add("待使用");
                } else if (couponCode.getStatus() == 3) {
                   data.add("已使用");
                } else if (couponCode.getStatus() == 4) {
                   data.add("已过期");
                } else if (couponCode.getStatus() == 99) {
                    data.add("预支付");
                } else {
                    data.add("未知");
                }
                data.add(couponCode.getStoreName());
                data.add(couponCode.getReceiveTime());
                data.add(couponCode.getConsumeTime());
                data.add(couponCode.getSalesEndTime());
                data.add(couponCode.getUseEndTime());
                data.add(couponCode.getCreateTime());
                dataList.add(data);
            }

            String fileUrl = SysConst.getSysConfig().getFileUrl() + "/temporary/";
            String pathName = "导出销售码"+System.currentTimeMillis()+".xlsx";
            File file = new File(fileUrl);
            if (!file.exists()) {
                file.mkdirs();
            }
            EasyExcel.write(fileUrl+pathName).head(generationHead(headList)).sheet("消费码").doWrite(dataList);
            return ResponseMsgUtil.success(pathName);
        } catch (Exception e) {
            log.error("HighCouponController -> importStock() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

/*    private List<List<String>> generationHead(List<String> headList) {
        List<List<String>> list = new ArrayList<>();
        List<String> head0 = new ArrayList<>();
        head0.add("字符串" + System.currentTimeMillis());
        List<String> head1 = new ArrayList<>();
        head1.add("数字" + System.currentTimeMillis());
        List<String> head2 = new ArrayList<>();
        head2.add("日期" + System.currentTimeMillis());
        list.add(head0);
        list.add(head1);
        list.add(head2);
        return list;
    }*/

    /**
     * 生成头部
     * @param headList
     * @return
     */
    private List<List<String>> generationHead(List<String> headList) {
        List<List<String>> list = new ArrayList<>();
        List<String> head;
        for (String headStr : headList) {
            head = new ArrayList<>();
            head.add(headStr);
            list.add(head);
        }
        return list;
    }

    @RequestMapping(value="/writeStock",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "填写卡卷库存（内部劵）")
    public ResponseData writeStock(@RequestBody String reqBody, HttpServletRequest request){
        try {

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

            JSONObject jsonObject = JSONObject.parseObject(reqBody);
            Long couponId = jsonObject.getLong("couponId");
            Long salesEndTime = jsonObject.getLong("salesEndTime");
            Long useEndTime = jsonObject.getLong("useEndTime");
            Integer generateNum = jsonObject.getInteger("generateNum");
            if(couponId == null || salesEndTime == null || useEndTime == null || generateNum == null) {
                log.error("HighCouponController -> writeStock() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查找商户
            HighCoupon coupon = highCouponService.getCouponById(couponId);
            if (coupon == null) {
                log.error("HighCouponController -> writeStock() error!","未找到商户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOF_FOUND, "");
            }
            if (coupon.getCouponType() != 1) {
                log.error("HighCouponController -> writeStock() error!","卡卷类型错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COUPON_TYPE_ERROR, "");
            }

            // 销售截止时间
            Calendar salesEndTimeC = Calendar.getInstance();
            salesEndTimeC.setTime(new Date(salesEndTime));
            salesEndTimeC.set(Calendar.HOUR_OF_DAY, 23);
            salesEndTimeC.set(Calendar.MINUTE, 59);
            salesEndTimeC.set(Calendar.SECOND, 59);

            // 使用截止时间
            Calendar useEndTimeC = Calendar.getInstance();
            useEndTimeC.setTime(new Date(useEndTime));
            useEndTimeC.set(Calendar.HOUR_OF_DAY, 23);
            useEndTimeC.set(Calendar.MINUTE, 59);
            useEndTimeC.set(Calendar.SECOND, 59);

            HighCouponCode highCouponCode;
            List<HighCouponCode> list = new ArrayList<>();
            for (int i = 0; i < generateNum;i++) {
                highCouponCode = new HighCouponCode();
                highCouponCode.setCouponId(couponId);
                highCouponCode.setMerchantId(coupon.getMerchantId());
                highCouponCode.setSalesCode(GenerateCode.couponSalesCode(coupon.getMerchantId(), couponId));
                highCouponCode.setSalesEndTime(salesEndTimeC.getTime());
                highCouponCode.setUseEndTime(useEndTimeC.getTime());
                highCouponCode.setStatus(1); // 状态：1.待销售 2.未使用 3.已使用  99.预支付
                highCouponCode.setIsAssignAgent(false);
                highCouponCode.setCreateTime(new Date());
                highCouponCode.setOperatorId(userInfoModel.getSecUser().getId());
                highCouponCode.setOperatorName(userInfoModel.getSecUser().getUserName());
                list.add(highCouponCode);
            }

            highCouponCodeService.insertList(list);

            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/getMerchantCouponTree",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询商户下的卡卷【树结构】")
    public ResponseData getMerchantCouponTree(HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighCouponController -> getCouponList() error!","权限不足");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            // 查询商户
            Map<String,Object> map = new HashMap<>();
            map.put("companyId", userInfoModel.getBsCompany().getId());
            List<HighMerchant> merchantList = highMerchantService.getMerchantList(map);


            List<Map<String, Object>> parentMap = new ArrayList<>();
            Map<String, Object> merchantMap;

            List<Map<String, Object>> couponMapList;
            Map<String, Object> couponMap;


            for (HighMerchant highMerchant : merchantList) {
                merchantMap = new HashMap<>();
                merchantMap.put("key", highMerchant.getId());
                merchantMap.put("title", highMerchant.getMerchantName());
                couponMapList = new ArrayList<>();
                // 查询门店下的卡卷
                List<HighCoupon> list = highCouponService.getCouponListByMerchant(highMerchant.getId());
                if (list.size() > 0) {
                    for (HighCoupon highCoupon : list) {
                        couponMap = new HashMap<>();
                        couponMap.put("key", highCoupon.getId());
                        couponMap.put("title", highCoupon.getCouponName());
                        couponMap.put("isLeaf", true);
                        couponMapList.add(couponMap);
                    }
                }
                merchantMap.put("children", couponMapList);
                parentMap.add(merchantMap);
            }
            return ResponseMsgUtil.success(parentMap);

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

    @RequestMapping(value="/getGuizhouSinopec",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取贵州中石化电子卡券")
    public ResponseData getGuizhouSinopec(HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighCouponController -> insertCoupon() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }
            // 查询商户
            HighMerchant merchant = highMerchantService.getMerchantById(40L);
            if (merchant == null) {
                log.error("HighCouponController -> insertCoupon() error!","未找到商户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MERCHANT_NOF_FOUND, "");
            }

            // 查询电子卡券类型
            JSONObject corpCouTypes = HuiLianTongConfig.getHltFuelCoupList();
            if (!corpCouTypes.getString("respCode").equals("0000")) {
                log.error("HighCouponController -> insertCoupon() error!","获取电子卡券列表失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "获取电子卡券列表失败");
            }
            // 参数解密
            JSONObject resolveResponseData = HuiLianTongUnionCardConfig.resolveResponse(corpCouTypes.getString("data"));

            HighCoupon coupon;
            JSONArray dataArray = resolveResponseData.getJSONArray("data");
            if (dataArray != null && dataArray.size() > 0) {
                for (Object object : dataArray) {
                    JSONObject dataObject = (JSONObject)object;
                    HighCoupon highCoupon = highCouponService.getCouponDetail(dataObject.getString("couTypeCode"));
                    if (highCoupon != null) {
                        continue;
                    }
                    coupon = new HighCoupon();
                    coupon.setCompanyId(userInfoModel.getBsCompany().getId());
                    coupon.setMerchantId(merchant.getId());
                    coupon.setCouponKey(dataObject.getString("couTypeCode"));
                    coupon.setCouponName(dataObject.getString("couTypeTitle"));
                    coupon.setCouponPrice(dataObject.getBigDecimal("couFaceValue"));
                    coupon.setCouponImg(dataObject.getString("couPic"));
                    coupon.setCouponCarouselImg(dataObject.getString("couPic"));
                    coupon.setCouponDesc(dataObject.getString("couDesc"));
                    coupon.setCouponType(2);
                    coupon.setSalesEndTime(dataObject.getDate("validEndDate"));
                    coupon.setRecycleDay(99);
                    coupon.setLimitNumber(99);
                    coupon.setSalesPrice(dataObject.getBigDecimal("couFaceValue"));
                    coupon.setDiscountPrice(dataObject.getBigDecimal("couFaceValue"));
                    coupon.setSalesCount(0);
                    coupon.setIsPresent(false);
                    coupon.setCreateTime(new Date());
                    coupon.setUpdateTime(new Date());
                    coupon.setOperatorId(0L);
                    coupon.setOperatorName("系统自动生成");
                    coupon.setPayType(2);
                    coupon.setStatus(1);
                    coupon.setDisplayArea(2);
                    coupon.setCouponSource(4);
                    highCouponService.insertCoupon(coupon);
                }
            }
            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("HighCouponController -> getGuizhouSinopec() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
