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.utils.ResponseMsgUtil;
import com.hai.entity.*;
import com.hai.enum_type.MerchantStoreSourceType;
import com.hai.model.HighMerchantStoreModel;
import com.hai.model.ResponseData;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
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.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/gasOilPrice")
@Api(value = "油品价格配置")
public class HighGasOilPriceController {

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

    @Resource
    private HighGasOilPriceService gasOilPriceService;

    @Resource
    private HighTyAgentPriceService tyAgentPriceService;

    @Resource
    private HighGasOilPriceOfficialService gasOilPriceOfficialService;

    @Resource
    private HighGasOilGunNoService gasOilGunNoService;

    @Resource
    private HighGasDiscountOilPriceService gasDiscountOilPriceService;

    @Resource
    private HighMerchantStoreService merchantStoreService;

    @Resource
    private CommonService commonService;

    @RequestMapping(value="/editGasOilPrice",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑油品价格")
    public ResponseData editGasOilPrice(@RequestBody JSONObject body) {
        try {
            if (body.getLong("storeId") == null || body.getInteger("oilNo") == null) {
                log.error("HighGasDiscountOilPriceController -> editGasOilPrice() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询门店详情
            HighMerchantStoreModel store = merchantStoreService.getMerchantStoreById(body.getLong("storeId"));
            if (store == null) {
                log.error("HighGasDiscountOilPriceController -> editGasOilPrice() error!","未找到门店");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到门店");
            }
            if (!store.getType().equals(1)) {
                log.error("HighGasDiscountOilPriceController -> editGasOilPrice() error!","门店不是加油站");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "门店不是加油站");
            }
            SecDictionary oilNo = commonService.mappingSysCode("GAS_OIL_TYPE", body.getString("oilNo"));
            if (oilNo == null) {
                log.error("HighGasDiscountOilPriceController -> editGasOilPrice() error!","未找到油品");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到油品");
            }
            // 查询价格
            HighGasOilPrice price = gasOilPriceService.getGasOilPriceByStoreAndOilNo(body.getLong("storeId"), Integer.valueOf(body.getString("oilNo")));
            if (price == null) {
                price = new HighGasOilPrice();
                // 查询国标价格
                HighGasOilPriceOfficial priceOfficial = gasOilPriceOfficialService.getPrice(store.getRegionId(),  body.getInteger("oilNo"));
                if (priceOfficial == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂时无法添加，系统未配置"+body.getInteger("oilNo")+"油号的国标价");
                }
                price.setMerchantStoreId(body.getLong("storeId"));
                price.setOilType(Integer.parseInt(oilNo.getExt1()));
                price.setOilTypeName(oilNo.getExt2());
                price.setOilNo(Integer.parseInt(oilNo.getCodeValue()));
                price.setOilNoName(oilNo.getCodeName());

                price.setPriceOfficial(priceOfficial.getPriceOfficial());
                price.setPriceGun(priceOfficial.getPriceOfficial());
                price.setPriceVip(priceOfficial.getPriceOfficial());

                price.setGasStationDrop(new BigDecimal("0"));
                price.setPreferentialMargin(new BigDecimal("0"));

                gasOilPriceService.editGasOilPrice(price);
                return ResponseMsgUtil.success("操作成功");
            }
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "已添加" + body.getInteger("oilNo") + "油号");

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

    @RequestMapping(value="/delOilPrice",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除油品价格")
    public ResponseData delOilPrice(@RequestBody JSONObject body) {
        try {
            if (body.getLong("storeId") == null || StringUtils.isBlank(body.getString("oilNo")) ) {
                log.error("HighGasDiscountOilPriceController -> editGasOilPrice() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询价格
            HighGasOilPrice price = gasOilPriceService.getGasOilPriceByStoreAndOilNo(body.getLong("storeId"), Integer.valueOf(body.getString("oilNo")));
            if (price == null) {
                log.error("HighGasDiscountOilPriceController -> editGasOilPrice() error!","未找到油品价格");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到油品价格");
            }
            price.setStatus(0);
            gasOilPriceService.editGasOilPrice(price);

            List<HighGasOilGunNo> oilGunNoList = gasOilGunNoService.getGunNoListByOilPrice(price.getId());
            for (HighGasOilGunNo gunNo : oilGunNoList) {
                gunNo.setStatus(0);
                gasOilGunNoService.editGunNo(gunNo);
            }
            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/getOilPriceDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油品价格详情")
    public ResponseData getOilPriceDetail(@RequestParam(name = "storeId", required = true) Long storeId,
                                          @RequestParam(name = "oilNo", required = true) Integer oilNo) {
        try {
            // 查询门店详情
            HighMerchantStoreModel store = merchantStoreService.getMerchantStoreById(storeId);
            if (store == null) {
                log.error("HighGasDiscountOilPriceController -> editGasOilPrice() error!","未找到门店");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到门店");
            }

            // 查询价格
            HighGasOilPrice gasOilPrice = gasOilPriceService.getGasOilPriceByStoreAndOilNo(storeId, oilNo);
            if (gasOilPrice == null) {
                gasOilPrice = new HighGasOilPrice();
                // 查询国标价格
                HighGasOilPriceOfficial priceOfficial = gasOilPriceOfficialService.getPrice(store.getRegionId(), oilNo);
                if (priceOfficial != null) {
                    gasOilPrice.setPriceOfficial(priceOfficial.getPriceOfficial());
                }
            }

            return ResponseMsgUtil.success(gasOilPrice);

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

    @RequestMapping(value="/getOilPriceListByStore",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油品价格列表")
    public ResponseData getOilPriceListByStore(@RequestParam(name = "storeId", required = true) Long storeId) {
        try {

            List<HighGasOilPrice> gasOilPriceList = gasOilPriceService.getGasOilPriceByStore(storeId);
            for (HighGasOilPrice gasOilPrice : gasOilPriceList) {
                BigDecimal discount = new BigDecimal("100");

                // 查询是否配置了【油站的】优惠比例
                HighTyAgentPrice tyAgentPrice = tyAgentPriceService.getDetail(1, gasOilPrice.getMerchantStoreId(), gasOilPrice.getOilNo().toString());
                if (tyAgentPrice != null) {
                    discount = tyAgentPrice.getPriceRate();
                } else {
                    // 查询是否配置了【油品】优惠比例
                    HighGasDiscountOilPrice gasDiscountOilPrice = gasDiscountOilPriceService.getDetailByOilNo(gasOilPrice.getOilNo().toString());
                    if (gasDiscountOilPrice != null) {
                        discount = gasDiscountOilPrice.getPriceRate();
                    }
                }
                // 油枪价 - 优惠幅度
                BigDecimal price = gasOilPrice.getPriceGun().subtract(gasOilPrice.getPreferentialMargin());
                gasOilPrice.setPriceVip(price.multiply(discount.divide(new BigDecimal("100"))).setScale(2, BigDecimal.ROUND_HALF_UP));
                gasOilPrice.setExt1(discount.toString());
            }
            return ResponseMsgUtil.success(gasOilPriceList);

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

}
