package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
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.PageUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.RechargeConfig;
import com.hai.entity.BsOperationLog;
import com.hai.entity.BsRechargeCode;
import com.hai.entity.OutRechargePrice;
import com.hai.entity.SecDictionary;
import com.hai.model.OutRechargePriceModel;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
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.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping(value = "/outRechargePrice")
@Api(value = "查询充值金额接口")
public class OutRechargePriceController {

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

    @Autowired
    private UserCenter userCenter;

    @Resource
    private OutRechargePriceService outRechargePriceService;

    @Resource
    private CommonService commonService;

    @Resource
    private BsConfigService bsConfigService;

    @Resource
    private BsOperationLogService bsOperationLogService;

    @Resource
    private BsRechargeCodeService bsRechargeCodeService;

    @RequestMapping(value = "/getListOutRechargePrice", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询充值金额列表")
    public ResponseData getListOutRechargePrice(
            @RequestParam(value = "operatorType", required = false) Integer operatorType,
            @RequestParam(value = "rechargePlatform", required = false) Integer rechargePlatform,
            @RequestParam(value = "rechargeType", required = false) Integer rechargeType,
            @RequestParam(value = "rechargeWay", required = false) Integer rechargeWay,
            @RequestParam(value = "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();

            Map<String, Object> map = new HashMap<>();

            map.put("operatorType", operatorType);
            map.put("rechargePlatform", "-" + rechargePlatform + "-");
            map.put("rechargeType", rechargeType);
            map.put("rechargeWay", rechargeWay);
            map.put("status", status);

            map.put("companyId", String.valueOf(userInfoModel.getBsCompany().getId()));

            List<OutRechargePrice> outRechargePrices = outRechargePriceService.getListRechargePrice(map);

            Map<String, Object> listMap;

            List<OutRechargePriceModel> outRechargePriceModelList = new ArrayList<>();

            for (OutRechargePrice list : outRechargePrices) {
                OutRechargePriceModel outRechargePriceModel = new OutRechargePriceModel();
                listMap = new HashMap<>();
                listMap.put("returnType", 2);
                listMap.put("productType", "3");
                listMap.put("sourceId", list.getId());
                BeanUtils.copyProperties(list, outRechargePriceModel);
                outRechargePriceModel.setIntegralDiscount(bsConfigService.getProductDiscountByMap(listMap).getDiscount());
                outRechargePriceModel.setProductPayTypeString(bsConfigService.getProductPayTypeByMap(listMap));
                outRechargePriceModel.setProductPlatformString(bsConfigService.getProductPlatformByMap(listMap));
                outRechargePriceModelList.add(outRechargePriceModel);

            }

            return ResponseMsgUtil.success(PageUtil.initPageInfoObj(pageNum,outRechargePriceModelList.size(),pageSize,new PageInfo<>(outRechargePriceModelList)));
        } catch (Exception e) {
            log.error("OutRechargePriceController --> getListUser() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/insertPrice", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增金额")
    public ResponseData insertPrice(@RequestBody JSONObject object, HttpServletRequest request) {
        try {

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

            if (object == null ||
                    object.getJSONArray("rechargePrices") == null ||
                    object.getBigDecimal("discount") == null ||
                    object.getString("operatorType") == null ||
                    object.getJSONArray("rechargePlatform") == null ||
                    object.getJSONArray("productPlatform") == null ||
//                    object.getInteger("rechargeType") == null ||
                    object.getJSONArray("payType") == null ||
                    object.getInteger("rechargeWay") == null
            ) {
                log.error("OutRechargePriceController -> insertPrice() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            if (object.getBigDecimal("integralDiscount") == null) {
                object.put("integralDiscount" , new BigDecimal(0));
            }

            object.put("operatorId", userInfoModel.getSecUser().getId());
            object.put("operatorName", userInfoModel.getSecUser().getLoginName());
            object.put("companyId", userInfoModel.getBsCompany().getId());

            outRechargePriceService.insertRechargePrice(object);

            BsOperationLog bsOperationLog = new BsOperationLog();

            bsOperationLog.setOperationType(1);
            bsOperationLog.setBeforeContent(String.valueOf(object));
            bsOperationLog.setAfterContent("新增数据");
            bsOperationLog.setOperatorId(userInfoModel.getSecUser().getId());
            bsOperationLog.setOperatorName(userInfoModel.getSecUser().getUserName());
            bsOperationLog.setEntityName("OutRechargePrice");

            bsOperationLogService.insertOperationLog(bsOperationLog);

            return ResponseMsgUtil.success("新增成功");

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

    @RequestMapping(value = "/updatePrice", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改金额")
    public ResponseData updatePrice(@RequestBody JSONObject object, HttpServletRequest request) {
        try {

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

            if (object == null ||
                    object.getLong("id") == null ||
                    object.getJSONArray("rechargePrices") == null ||
                    object.getBigDecimal("discount") == null ||
                    object.getString("operatorType") == null ||
                    object.getJSONArray("rechargePlatform") == null ||
                    object.getJSONArray("productPlatform") == null ||
//                    object.getInteger("rechargeType") == null ||
                    object.getJSONArray("payType") == null ||
                    object.getInteger("rechargeWay") == null
            ) {
                log.error("OutRechargePriceController -> insertPrice() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            if (object.getBigDecimal("integralDiscount") == null) {
                object.put("integralDiscount" , new BigDecimal(0));
            }

            OutRechargePriceModel outRechargePrice = outRechargePriceService.findById(object.getLong("id") , null);

            if (outRechargePrice == null) {
                log.error("OutRechargePriceController -> updatePrice() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.UPDATE_DATA_ERROR, "");
            }

            object.put("operatorId", userInfoModel.getSecUser().getId());
            object.put("operatorName", userInfoModel.getSecUser().getLoginName());
            object.put("companyId", userInfoModel.getBsCompany().getId());
            outRechargePriceService.updateRechargePrice(object);

            BsOperationLog bsOperationLog = new BsOperationLog();

            bsOperationLog.setOperationType(2);
            bsOperationLog.setBeforeContent(String.valueOf(outRechargePrice));
            bsOperationLog.setAfterContent(String.valueOf(object));
            bsOperationLog.setOperatorId(userInfoModel.getSecUser().getId());
            bsOperationLog.setOperatorName(userInfoModel.getSecUser().getUserName());
            bsOperationLog.setEntityName("OutRechargePrice");

            bsOperationLogService.insertOperationLog(bsOperationLog);

            return ResponseMsgUtil.success("修改成功");

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

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

            OutRechargePriceModel outRechargePriceModel = outRechargePriceService.findById(id , null);
            return ResponseMsgUtil.success(outRechargePriceModel);

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

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

            outRechargePriceService.deletePrice(id);
            return ResponseMsgUtil.success("删除成功");

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

    @RequestMapping(value = "/editPriceStatus", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改价格状态")
    public ResponseData editPriceStatus(@RequestBody JSONObject object, HttpServletRequest request) {
        try {

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

            OutRechargePrice outRechargePrice = outRechargePriceService.findById(object.getLong("id") , null);
            if (object.getInteger("status") == 1) {

                Map<String, Object> map = new HashMap<>();
                map.put("type" , 1);
                map.put("sourceId" , outRechargePrice.getId());
                List<BsRechargeCode> rechargeCodes = bsRechargeCodeService.getListRechargeCode(map);

                if ((outRechargePrice.getRechargePlatform().contains("-2-") || outRechargePrice.getRechargePlatform().contains("-3-") ) && rechargeCodes.size() == 0) {
                    log.error("OutRechargePriceController -> editPriceStatus() error!");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "龙阅,城宇平台需要输入商品编码！");
                }

                for (BsRechargeCode rechargeCode : rechargeCodes) {

                    if ((rechargeCode.getRechargePlatform() == 2 || rechargeCode.getRechargePlatform() == 3) ){
                        if (rechargeCode.getGoodsId() == null) {
                            log.error("OutRechargePriceController -> editPriceStatus() error!");
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "龙阅,城宇平台需要输入商品编码！");
                        }
                        if (rechargeCode.getGoodsId().length() == 0) {
                            log.error("OutRechargePriceController -> editPriceStatus() error!");
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "龙阅,城宇平台需要输入商品编码！");
                        }

                    }
                }


            }

            outRechargePrice.setStatus(object.getInteger("status"));
            outRechargePriceService.editPriceStatus(outRechargePrice);

            BsOperationLog bsOperationLog = new BsOperationLog();

            bsOperationLog.setOperationType(2);
            bsOperationLog.setBeforeContent(String.valueOf(outRechargePrice));
            bsOperationLog.setAfterContent(String.valueOf(object));
            bsOperationLog.setOperatorId(userInfoModel.getSecUser().getId());
            bsOperationLog.setOperatorName(userInfoModel.getSecUser().getUserName());
            bsOperationLog.setEntityName("OutRechargePrice");

            bsOperationLogService.insertOperationLog(bsOperationLog);

            return ResponseMsgUtil.success("修改成功");

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

    @RequestMapping(value = "/getProductsList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取产品")
    public ResponseData getProductsList() {
        try {

            return ResponseMsgUtil.success(RechargeConfig.getProductsListByLy());

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

    @RequestMapping(value = "/getRechargeCodeList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取充值产品编码列表")
    public ResponseData getRechargeCodeList(@RequestParam(value = "id", required = true) Long id,
                                            @RequestParam(value = "codeType", required = true) String codeType) {
        try {

            List<SecDictionary> list = commonService.mappingSysNameOl(codeType);

            List<JSONObject> objectList = new ArrayList<>();

            for (SecDictionary dictionary : list) {
                JSONObject object = new JSONObject();

                Map<String, Object> map = new HashMap<>();
                map.put("type" , 1);
                map.put("sourceId" , id);
                map.put("rechargePlatform" , dictionary.getCodeValue());
                BsRechargeCode rechargeCode = bsRechargeCodeService.findByMap(map);
                object.put("rechargePlatformName" , dictionary.getCodeName());
                object.put("rechargePlatform" , dictionary.getCodeValue());
                if (rechargeCode != null) {
                    object.put("id" , rechargeCode.getId());
                    object.put("goodsId" , rechargeCode.getGoodsId());
                }
                objectList.add(object);

            }

            return ResponseMsgUtil.success(objectList);

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

    @RequestMapping(value = "/editRechargeCode", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑充值编码")
    public ResponseData editRechargeCode(@RequestBody List<BsRechargeCode> objectList, HttpServletRequest request) {
        try {

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

            for (BsRechargeCode rechargeCode : objectList) {
                rechargeCode.setOperatorId(userInfoModel.getSecUser().getId());
                rechargeCode.setOperatorName(userInfoModel.getSecUser().getUserName());
                rechargeCode.setStatus(100);

                if (rechargeCode.getId() == null) {
                    rechargeCode.setCreateTime(new Date());
                    rechargeCode.setUpdateTime(new Date());
                    bsRechargeCodeService.insertRechargeCode(rechargeCode);
                } else {
                    rechargeCode.setUpdateTime(new Date());
                    bsRechargeCodeService.updateRechargeCode(rechargeCode);
                }
            }

            return ResponseMsgUtil.success("新增成功");

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


}
