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.ApiProduct;
import com.hai.entity.ApiStarbucksProducts;
import com.hai.entity.BsProductConfig;
import com.hai.entity.OutRechargePrice;
import com.hai.model.BsProductConfigModel;
import com.hai.model.OutRechargePriceModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.ApiProductService;
import com.hai.service.BsConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/bsProductConfig")
@Api(value = "api产品")
public class BsProductConfigController {

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

    @Resource
    private ApiProductService apiProductService;

    @Resource
    private BsConfigService bsConfigService;

    @Autowired
    private UserCenter userCenter;

    @RequestMapping(value = "/getProductConfig", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询配置产品")
    public ResponseData getProductConfig(@RequestParam(value = "productName", required = false) String productName,
                                         @RequestParam(value = "productType", required = false) Integer productType,
                                         @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("companyId", String.valueOf(userInfoModel.getBsCompany().getId()));
            map.put("productName", productName);
            map.put("productType", productType);


            List<BsProductConfig> productConfigs = apiProductService.getProductConfig(map);

            Map<String, Object> listMap;

            List<BsProductConfigModel> productConfigModels = new ArrayList<>();

            for (BsProductConfig list : productConfigs) {
                BsProductConfigModel bsProductConfigModel = new BsProductConfigModel();
                listMap = new HashMap<>();
                listMap.put("returnType", 2);
                listMap.put("productType", "5");
                listMap.put("sourceId", list.getId());
                BeanUtils.copyProperties(list, bsProductConfigModel);
                bsProductConfigModel.setIntegralDiscount(bsConfigService.getProductDiscountByMap(listMap).getDiscount());
                bsProductConfigModel.setProductPayTypeString(bsConfigService.getProductPayTypeByMap(listMap));
                bsProductConfigModel.setProductPlatformString(bsConfigService.getProductPlatformByMap(listMap));
                productConfigModels.add(bsProductConfigModel);

            }

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

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

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

            if (object == null ||
                    object.getBigDecimal("discount") == null ||
                    object.getInteger("productType") == null ||
                    object.getJSONArray("productPlatform") == null ||
                    object.getJSONArray("payType") == null
            ) {
                log.error("OutRechargePriceController -> productConfig() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

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

            apiProductService.ProductConfig(object);


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

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

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

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

            if (object == null ||
                    object.getLong("id") == null ||
                    object.getBigDecimal("discount") == null ||
                    object.getInteger("productType") == null ||
                    object.getJSONArray("productPlatform") == null ||
                    object.getJSONArray("payType") == null
            ) {
                log.error("OutRechargePriceController -> productConfig() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

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

            apiProductService.updateProductConfig(object);


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

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


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

            BsProductConfig bsProductConfig = apiProductService.findProductConfig(id);

            BsProductConfigModel bsProductConfigModel = new BsProductConfigModel();
            BeanUtils.copyProperties(bsProductConfig, bsProductConfigModel);
            Map<String, Object> listMap = new HashMap<>();
            listMap.put("productType", "5");
            listMap.put("returnType", 1);
            listMap.put("sourceId", bsProductConfig.getId());
            listMap.put("platformId", null);

            bsProductConfigModel.setIntegralDiscount(bsConfigService.getProductDiscountByMap(listMap).getDiscount());
            bsProductConfigModel.setProductPayTypeString(bsConfigService.getProductPayTypeByMap(listMap));
            bsProductConfigModel.setProductPlatformString(bsConfigService.getProductPlatformByMap(listMap));
            return ResponseMsgUtil.success(bsProductConfigModel);

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

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

            BsProductConfig bsProductConfig = apiProductService.findProductConfig(id);

            ApiStarbucksProducts apiStarbucksProducts = apiProductService.findStarbucksProducts(bsProductConfig.getProductId());

            apiStarbucksProducts.setSalesVentiPrice(apiStarbucksProducts.getMarketVentiPrice().multiply(bsProductConfig.getDiscount()).divide(new BigDecimal(100)));
            apiStarbucksProducts.setSalesTallPrice(apiStarbucksProducts.getMarketTallPrice().multiply(bsProductConfig.getDiscount()).divide(new BigDecimal(100)));
            apiStarbucksProducts.setSalesGrandePrice(apiStarbucksProducts.getMarketGrandePrice().multiply(bsProductConfig.getDiscount()).divide(new BigDecimal(100)));

            return ResponseMsgUtil.success(apiStarbucksProducts);


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

}
