package com.bweb.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.bweb.config.SysConst;
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.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.model.GzSinopecModel;
import com.hai.model.OilCardOrderModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.HighCouponCodeService;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: 胡锐
 * @Description: 卡卷销售码
 * @Date: 2021/3/22 19:39
 */
@Controller
@RequestMapping(value = "/couponCode")
@Api(value = "卡卷销售码接口")
public class HighCouponCodeController {

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

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value="/getCouponCodeList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "销售码列表")
    public ResponseData getCouponCodeList(@RequestParam(name = "couponId", required = true) Long couponId,
                                          @RequestParam(name = "status", required = false) Integer status,
                                          @RequestParam(name = "salesCode", required = false) String salesCode,
                                          @RequestParam(name = "agentId", required = false) Long agentId,
                                          @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                          @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("agentId", agentId);
            map.put("couponId", couponId);
            map.put("status", status);
            map.put("salesCode", salesCode);

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


    @RequestMapping(value="/useCouponCode",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "使用卡卷码")
    public ResponseData useCouponCode(@RequestBody String reqBody, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getMerchantStore() == null) {
                log.error("HighMerchantController -> useCouponCode() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }
            JSONObject jsonObject = JSONObject.parseObject(reqBody);
            String code = jsonObject.getString("code");
            if (StringUtils.isBlank(code)) {
                log.error("HighMerchantStoreController -> useCouponCode() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            highCouponCodeService.useCouponCode(code, userInfoModel);

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

    @RequestMapping(value="/getGzSinopecAssignList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询贵州中石化分配列表")
    public ResponseData getGzSinopecAssignList(@RequestParam(name = "couponName", required = false) String couponName,
                                               @RequestParam(name = "status", required = false) Integer status,
                                               @RequestParam(name = "assignTimeS", required = false) Long assignTimeS,
                                               @RequestParam(name = "assignTimeE", required = false) Long assignTimeE,
                                               @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                               @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("couponName", couponName);
            map.put("status", status);
            map.put("assignTimeS", assignTimeS);
            map.put("assignTimeE", assignTimeE);

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

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

    @RequestMapping(value="/importGzSinopecAssign",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出贵州中石化分配列表")
    public ResponseData importGzSinopecAssign(@RequestParam(name = "couponName", required = false) String couponName,
                                              @RequestParam(name = "assignTimeS", required = false) Long assignTimeS,
                                              @RequestParam(name = "assignTimeE", required = false) Long assignTimeE,
                                              @RequestParam(name = "status", required = false) Integer status) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("couponName", couponName);
            map.put("status", status);
            map.put("assignTimeS", assignTimeS);
            map.put("assignTimeE", assignTimeE);

            List<GzSinopecModel> list = highCouponCodeService.getGzSinopecAssignList(map);

            List<String> headList = new ArrayList<>();
            headList.add("卡券名称");
            headList.add("卡券金额");
            headList.add("分发时间");
            headList.add("分发手机号");
            headList.add("状态");

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

            for (GzSinopecModel gzSinopecModel: list) {
                data = new ArrayList<>();
                data.add(gzSinopecModel.getCouponName());
                data.add(gzSinopecModel.getSalesPrice());
                data.add(DateUtil.format(gzSinopecModel.getSalesTime(), "yyyy-MM-dd HH:mm:ss"));
                data.add(gzSinopecModel.getConvertUserPhone());
                if (gzSinopecModel.getStatus().equals(2)) {
                    data.add("待使用");
                } else if (gzSinopecModel.getStatus().equals(3)) {
                    data.add("已使用");
                }
                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("sheet1").doWrite(dataList);

            return ResponseMsgUtil.success(pathName);

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


    /**
     * 生成头部
     * @param headList
     * @return
     */
    private static 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;
    }
}
