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.AESEncodeUtil;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.HighCompanyTwoPwd;
import com.hai.entity.HighOilCard;
import com.hai.enum_type.OilCardStatusEnum;
import com.hai.enum_type.UserObjectTypeEnum;
import com.hai.model.OilCardOrderModel;
import com.hai.model.ResponseData;
import com.hai.model.TyOrderModel;
import com.hai.model.UserInfoModel;
import com.hai.service.HighCompanyTwoPwdService;
import com.hai.service.HighOilCardService;
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 java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/oilCard")
@Api(value = "油卡")
public class HighOilCardController {

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

    @Resource
    private UserCenter userCenter;

    @Resource
    private HighOilCardService oilCardService;

    @Resource
    private HighCompanyTwoPwdService companyTwoPwdService;

    @RequestMapping(value = "/recharge", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "油卡充值")
    public ResponseData recharge(@RequestBody JSONObject body) {
        try {
            if (StringUtils.isBlank(body.getString("cardNo")) ||
                body.getBigDecimal("price") == null ||
                StringUtils.isBlank(body.getString("twoPwd"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userModel.getBsOrganization() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "权限不足");
            }

            // 查询二级密码
            HighCompanyTwoPwd pwdByOrg = companyTwoPwdService.getTwoPwdByOrg(userModel.getBsOrganization().getId());
            if (pwdByOrg == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_TOW_PWD, "");
            }
            if (!AESEncodeUtil.aesEncrypt(body.getString("twoPwd")).equals(pwdByOrg.getPassword())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "支付密码错误");
            }
            // 充值
            oilCardService.recharge(body.getString("cardNo"), body.getBigDecimal("price"), userModel.getBsOrganization().getId());

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

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

    @RequestMapping(value = "/recycleAmount", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "回收余额")
    public ResponseData recycleAmount(@RequestBody JSONObject body) {
        try {
            if (StringUtils.isBlank(body.getString("cardNo")) ||
                    StringUtils.isBlank(body.getString("twoPwd"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userModel.getBsOrganization() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "权限不足");
            }

            // 查询二级密码
            HighCompanyTwoPwd pwdByOrg = companyTwoPwdService.getTwoPwdByOrg(userModel.getBsOrganization().getId());
            if (pwdByOrg == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_TOW_PWD, "");
            }
            if (!AESEncodeUtil.aesEncrypt(body.getString("twoPwd")).equals(pwdByOrg.getPassword())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "支付密码错误");
            }
            // 充值
            oilCardService.recycleAmount(body.getString("cardNo"));

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

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

    @RequestMapping(value = "/generateCard", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "生成油卡")
    public ResponseData generateCard(@RequestBody JSONObject body) {
        try {
            if (body.getInteger("generateNum") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userModel.getBsOrganization() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "权限不足");
            }

            oilCardService.generateCard(userModel.getBsOrganization().getId(), body.getInteger("generateNum"));

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

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

    @RequestMapping(value = "/setContact", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "设置联系人")
    public ResponseData setContact(@RequestBody JSONObject body) {
        try {
            if (StringUtils.isBlank(body.getString("cardNo"))
                || StringUtils.isBlank(body.getString("contactName"))
                || StringUtils.isBlank(body.getString("contactPhone"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userModel.getBsOrganization() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "权限不足");
            }
            oilCardService.setContact(body.getString("cardNo"),body.getString("contactName"),body.getString("contactPhone"));

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

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

    @RequestMapping(value = "/disabled", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "禁用")
    public ResponseData disabled(@RequestBody JSONObject body) {
        try {
            if (StringUtils.isBlank(body.getString("cardNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            oilCardService.disabled(body.getString("cardNo"));

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

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

    @RequestMapping(value = "/enable", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "启用")
    public ResponseData enable(@RequestBody JSONObject body) {
        try {
            if (StringUtils.isBlank(body.getString("cardNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            oilCardService.enable(body.getString("cardNo"));

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

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

    @RequestMapping(value = "/getCardList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油卡列表")
    public ResponseData getCardList(@RequestParam(name = "orgId", required = false) Long orgId,
                                    @RequestParam(name = "cardNo", required = false) String cardNo,
                                    @RequestParam(name = "contactName", required = false) String contactName,
                                    @RequestParam(name = "contactPhone", required = false) String contactPhone,
                                    @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                    @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                    @RequestParam(name = "bindTimeS", required = false) Long bindTimeS,
                                    @RequestParam(name = "bindTimeE", required = false) Long bindTimeE,
                                    @RequestParam(name = "isConfigContact", required = false) Boolean isConfigContact,
                                    @RequestParam(name = "status", required = false) Integer status,
                                    @RequestParam(name = "bindStatus", required = false) Integer bindStatus,
                                    @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                    @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {

            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);

            Map<String, Object> param = new HashMap<>();
            param.put("companyId", userModel.getBsCompany().getId());

            if (userModel.getSecUser().getAdminFlag() != 1) {
                param.put("orgId", userModel.getBsOrganization().getId());
            } else {
                param.put("orgId", orgId);
            }
            param.put("cardNo", cardNo);
            param.put("contactName", contactName);
            param.put("contactPhone", contactPhone);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);
            param.put("bindTimeS", bindTimeS);
            param.put("bindTimeE", bindTimeE);
            param.put("isConfigContact", isConfigContact);
            param.put("status", status);
            param.put("bindStatus", bindStatus);

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

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

    @RequestMapping(value = "/exportCard", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出油卡")
    public ResponseData exportCard(@RequestParam(name = "orgId", required = false) Long orgId,
                                    @RequestParam(name = "cardNo", required = false) String cardNo,
                                    @RequestParam(name = "contactName", required = false) String contactName,
                                    @RequestParam(name = "contactPhone", required = false) String contactPhone,
                                    @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                    @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                    @RequestParam(name = "bindTimeS", required = false) Long bindTimeS,
                                    @RequestParam(name = "bindTimeE", required = false) Long bindTimeE,
                                    @RequestParam(name = "isConfigContact", required = false) Boolean isConfigContact,
                                    @RequestParam(name = "status", required = false) Integer status,
                                    @RequestParam(name = "bindStatus", required = false) Integer bindStatus) {
        try {

            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);

            Map<String, Object> param = new HashMap<>();
            param.put("companyId", userModel.getBsCompany().getId());

            if (userModel.getSecUser().getAdminFlag() != 1) {
                param.put("orgId", userModel.getBsOrganization().getId());
            } else {
                param.put("orgId", orgId);
            }
            param.put("cardNo", cardNo);
            param.put("contactName", contactName);
            param.put("contactPhone", contactPhone);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);
            param.put("bindTimeS", bindTimeS);
            param.put("bindTimeE", bindTimeE);
            param.put("isConfigContact", isConfigContact);
            param.put("status", status);
            param.put("bindStatus", bindStatus);
            List<HighOilCard> cardList = oilCardService.getOilCardList(param);


            List<String> headList = new ArrayList<>();
            headList.add("卡号");
            headList.add("余额");
            headList.add("消费金额");
            headList.add("联系人");
            headList.add("联系电话");
            headList.add("状态");

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

            for (HighOilCard card: cardList) {
                data = new ArrayList<>();
                data.add(card.getCardNo());
                data.add(card.getAmount());
                data.add(card.getAmountConsume());

                if (StringUtils.isNotBlank(card.getContactName())) {
                    data.add(card.getContactName());
                } else {
                    data.add("未设置");
                }

                if (StringUtils.isNotBlank(card.getContactPhone())) {
                    data.add(card.getContactName());
                } else {
                    data.add("未设置");
                }

                if (card.getStatus().equals(OilCardStatusEnum.status1.getStatus())) {
                    data.add("正常");
                } else if (card.getStatus().equals(OilCardStatusEnum.status2.getStatus())) {
                    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("油卡").doWrite(dataList);

            return ResponseMsgUtil.success(pathName);

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

    @RequestMapping(value = "/getCardOrderList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油卡订单列表")
    public ResponseData getCardOrderList(@RequestParam(name = "orgId", required = false) Long orgId,
                                         @RequestParam(name = "cardNo", required = false) String cardNo,
                                         @RequestParam(name = "goodsName", required = false) String goodsName,
                                         @RequestParam(name = "status", required = false) Integer status,
                                         @RequestParam(name = "payTimeS", required = false) String payTimeS,
                                         @RequestParam(name = "payTimeE", required = false) String payTimeE,
                                         @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                         @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {

            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);

            Map<String, Object> param = new HashMap<>();
            param.put("companyId", userModel.getBsCompany().getId());

            if (userModel.getSecUser().getAdminFlag() != 1) {
                param.put("orgId", userModel.getBsOrganization().getId());
            } else {
                param.put("orgId", orgId);
            }
            param.put("status", status);
            param.put("cardNo", cardNo);
            param.put("goodsName", goodsName);
            param.put("payTimeS", payTimeS);
            param.put("payTimeE", payTimeE);

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

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

    @RequestMapping(value = "/exportCardOrder", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出油卡订单")
    public ResponseData exportCardOrder(@RequestParam(name = "orgId", required = false) Long orgId,
                                         @RequestParam(name = "cardNo", required = false) String cardNo,
                                         @RequestParam(name = "goodsName", required = false) String goodsName,
                                         @RequestParam(name = "status", required = false) Integer status,
                                         @RequestParam(name = "payTimeS", required = false) String payTimeS,
                                         @RequestParam(name = "payTimeE", required = false) String payTimeE,
                                         @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                         @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {

            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);

            Map<String, Object> param = new HashMap<>();
            param.put("companyId", userModel.getBsCompany().getId());

            if (userModel.getSecUser().getAdminFlag() != 1) {
                param.put("orgId", userModel.getBsOrganization().getId());
            } else {
                param.put("orgId", orgId);
            }
            param.put("status", status);
            param.put("cardNo", cardNo);
            param.put("goodsName", goodsName);
            param.put("payTimeS", payTimeS);
            param.put("payTimeE", payTimeE);

            List<OilCardOrderModel> cardOrderList = oilCardService.getOilCardOrderList(param);
            List<String> headList = new ArrayList<>();

            if (userModel.getSecUser().getAdminFlag() == 1) {
                headList.add("所属部门");
                headList.add("用户手机号");
            }
            headList.add("油卡卡号");
            headList.add("平台订单号");
            headList.add("团油订单号");
            headList.add("加油金额");
            headList.add("优惠金额");
            headList.add("实付金额");
            headList.add("加油站");
            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;

            for (OilCardOrderModel cardOrder: cardOrderList) {
                data = new ArrayList<>();
                if (userModel.getSecUser().getAdminFlag() == 1) {
                    data.add(cardOrder.getOrgName());
                    data.add(cardOrder.getMerPhone());
                }
                data.add(cardOrder.getMemCardNo());
                data.add(cardOrder.getOrderNo());
                data.add(cardOrder.getGasOrderNo());
                data.add(cardOrder.getTotalPrice());
                data.add(cardOrder.getDeductionPrice());
                data.add(cardOrder.getPayRealPrice());
                data.add(cardOrder.getGoodsName());
                data.add(cardOrder.getGasOilNo());
                data.add(cardOrder.getGasGunNo());
                data.add(cardOrder.getGasPriceGun());
                data.add(cardOrder.getPlatformPriceGun());
                data.add(cardOrder.getStatusName());
                data.add(DateUtil.format(cardOrder.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                data.add(DateUtil.format(cardOrder.getPayTime(), "yyyy-MM-dd HH:mm:ss"));
                if (cardOrder.getRefundTime() != null) {
                    data.add(DateUtil.format(cardOrder.getRefundTime(), "yyyy-MM-dd HH:mm:ss"));
                } else {
                    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("油卡订单").doWrite(dataList);

            return ResponseMsgUtil.success(pathName);

        } catch (Exception e) {
            log.error("HighOilCardController --> getCardOrderList() 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;
    }
}
