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.entity.*;
import com.hai.model.OutRechargePriceModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.ApiProductService;
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.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 = "/apiProduct")
@Api(value = "api产品")
public class ApiProductController {

    Logger log = LoggerFactory.getLogger(ApiProductController.class);

    @Resource
    private ApiProductService apiProductService;

    @Autowired
    private UserCenter userCenter;

    @RequestMapping(value = "/getListApiProduct", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询产品列表")
    public ResponseData getListApiProduct(
            @RequestParam(value = "operatorType", required = false) Integer operatorType,
            @RequestParam(value = "rechargePlatform", required = false) Integer rechargePlatform,
            @RequestParam(value = "phoneRechargeType", required = false) Integer phoneRechargeType,
            @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("phoneRechargeType", phoneRechargeType);
            map.put("status", status);

            PageHelper.startPage(pageNum,pageSize);
            PageHelper.startPage(pageNum, pageSize);

            List<ApiProduct> list = apiProductService.getListApiProduct(map);
            return ResponseMsgUtil.success(new PageInfo<>(list));

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


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

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

            if (object == null ||
                    object.getJSONArray("prices") == null ||
                    object.getInteger("operatorType") == null ||
                    object.getJSONArray("rechargePlatform") == null ||
                    object.getInteger("phoneRechargeType") == null
            ) {
                log.error("ApiProductController -> insertProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }


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

            apiProductService.insertApiProduct(object);

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

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

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

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

            if (object == null ||
                    object.getLong("id") == null ||
                    object.getInteger("operatorType") == null ||
                    object.getJSONArray("rechargePlatform") == null ||
                    object.getInteger("phoneRechargeType") == null
            ) {
                log.error("ApiProductController -> updateProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            ApiProduct apiProduct = apiProductService.findById(object.getLong("id"));
            
            if (apiProduct.getStatus() != 102) {
                log.error("ApiProductController -> updateProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "状态错误");
            }
            
            apiProduct.setOperatorId(userInfoModel.getSecUser().getId());
            apiProduct.setOperatorName(userInfoModel.getSecUser().getLoginName());
            apiProduct.setRechargeType(object.getInteger("rechargeType"));
            apiProduct.setPhoneRechargeType(object.getInteger("phoneRechargeType"));
            apiProduct.setOperatorType(object.getInteger("operatorType"));
            apiProduct.setRechargePlatform("-" + StringUtils.join(object.getJSONArray("rechargePlatform"), "-") + "-");
            apiProduct.setUpdateTime(new Date());
            apiProduct.setSort(object.getInteger("sort"));
            apiProduct.setProductId(object.getLong("productId"));
            apiProduct.setOperatorName(object.getString("operatorName"));
            apiProduct.setOperatorId(object.getLong("operatorId"));

            apiProductService.updateApiProduct(apiProduct);

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

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

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

            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            
            ApiProduct apiProduct = apiProductService.findById(object.getLong("id"));
            
            if (object.getInteger("status") == 101 && apiProduct.getRechargePlatform().contains("-2-") && apiProduct.getProductId() == null) {
                log.error("ApiProductController -> editProductStatus() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "龙阅平台需要输入商品编码！");
            }

            apiProduct.setStatus(object.getInteger("status"));
            apiProduct.setOperatorName(userInfoModel.getSecUser().getUserName());
            apiProduct.setOperatorId(userInfoModel.getSecUser().getId());
            apiProductService.updateApiProduct(apiProduct);


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

        } catch (Exception e) {
            log.error("ApiProductController --> editPriceStatus() 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 {

            return ResponseMsgUtil.success(apiProductService.findById(id));

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

    @RequestMapping(value = "/getAvailableApiProductByList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询可用产品列表")
    public ResponseData getAvailableApiProductByList(
            HttpServletRequest request
    ) {
        try {

            Map<String, Object> map = new HashMap<>();
            map.put("rechargeType", 1);
            map.put("status", 101);

            List<ApiProduct> list = apiProductService.getListApiProduct(map);
            return ResponseMsgUtil.success(list);

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

    @RequestMapping(value = "/configApiProduct", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "配置产品")
    public ResponseData configApiProduct(@RequestBody JSONObject object) {
        try {

            if (object == null ||
                    object.getJSONArray("productIds") == null ||
                    object.getBigDecimal("discount") == null ||
                    object.getLong("merchantsId") == null
            ) {
                log.error("ApiProductController -> configApiProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            apiProductService.configApiProduct(object);

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

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


    @RequestMapping(value = "/editConfigApiProductByStatus", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改商户产品状态")
    public ResponseData editConfigApiProductByStatus(@RequestBody JSONObject object, HttpServletRequest request) {
        try {

            if (object == null ||
                    object.getInteger("status") == null ||
                    object.getInteger("id") == null
            ) {
                log.error("ApiProductController -> configApiProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

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

            ApiProductConfig apiProductConfig = apiProductService.findProductConfigById(object.getLong("id"));

            apiProductConfig.setStatus(object.getInteger("status"));
            apiProductConfig.setOperatorName(userInfoModel.getSecUser().getUserName());
            apiProductConfig.setOperatorId(userInfoModel.getSecUser().getId());
            apiProductService.updateConfigApiProduct(apiProductConfig);

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

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


    @RequestMapping(value = "/updateConfigApiProduct", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改配置产品")
    public ResponseData updateConfigApiProduct(@RequestBody JSONObject object) {
        try {

            if (object == null ||
                    object.getBigDecimal("discount") == null ||
                    object.getLong("id") == null
            ) {
                log.error("ApiProductController -> configApiProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            ApiProductConfig apiProductConfig = apiProductService.findProductConfigById(object.getLong("id"));

            ApiProduct apiProduct = apiProductService.findById(apiProductConfig.getProductId());

            if (apiProductConfig.getStatus() == 101) {
                log.error("ApiProductController -> configApiProduct() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前状态错误");
            }

            apiProductConfig.setDiscount(object.getBigDecimal("discount"));
            apiProductConfig.setDiscountPrice(apiProduct.getRechargePrice().multiply(object.getBigDecimal("discount")).divide(new BigDecimal(100)));

            apiProductService.updateConfigApiProduct(apiProductConfig);

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

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

    @RequestMapping(value = "/findConfigProduct", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询配置产品")
    public ResponseData findConfigProduct(@RequestParam(value = "id", required = true) Long id) {
        try {

            return ResponseMsgUtil.success(apiProductService.findProductConfigById(id));

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

    @RequestMapping(value = "/getStarbucksProducts", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询星巴克产品")
    public ResponseData getStarbucksProducts() {
        try {

            return ResponseMsgUtil.success(apiProductService.getStarbucksProducts(new HashMap<>()));

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


}
