package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.service.gas.BsGasOilPriceOfficialService;
import com.hfkj.service.gas.BsGasOilPriceService;
import com.hfkj.service.gas.BsGasOilPriceWeekService;
import com.hfkj.service.merchant.BsMerchantService;
import com.hfkj.service.CommonService;
import com.hfkj.service.gas.BsGasService;
import com.hfkj.sysenum.merchant.MerchantSourceTypeEnum;
import com.hfkj.sysenum.gas.GasOilPriceStatusEnum;
import com.hfkj.sysenum.SecUserObjectTypeEnum;
import com.hfkj.sysenum.gas.GasOilPriceWeekEnum;
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.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/gasOilPrice")
@Api(value = "加油站价格")
public class BsGasOilPriceController {
    private static Logger log = LoggerFactory.getLogger(BsGasOilPriceController.class);

    @Resource
    private BsGasOilPriceService gasOilPriceService;
    @Resource
    private BsMerchantService merchantService;
    @Resource
    private UserCenter userCenter;
    @Resource
    private CommonService commonService;
    @Resource
    private BsGasService gasService;
    @Resource
    private BsGasOilPriceWeekService gasOilPriceWeekService;

    @RequestMapping(value = "/createOil", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "创建油品")
    public ResponseData createOil(@RequestBody BsGasOilPrice body) {
        try {
            SecUserSessionObject sessionObject = userCenter.getSessionModel(SecUserSessionObject.class);
            if (sessionObject == null || !sessionObject.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type2.getCode())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NOT_PERMISSIONS, "");
            }

            if (body == null
                    || body.getMerNo() == null
                    || StringUtils.isBlank(body.getOilNo())){
                log.error("BsGasOilPriceController --> createOil() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询商户
            BsMerchant merchant = merchantService.getMerchant(body.getMerNo());
            if (merchant == null) {
                log.error("BsGasOilPriceController --> createOil() error!", "未知的商户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
            }
            if (!merchant.getSourceType().equals(MerchantSourceTypeEnum.type1.getNumber())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "第三方油站不能创建油品");
            }
            // 是否重复添加商户油品
            if (gasOilPriceService.getGasOilPrice(merchant.getId(), body.getOilNo()) != null) {
                log.error("BsGasOilPriceController --> createOil() error!", "重复添加" + body.getOilNo() + "油品");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "重复添加" + body.getOilNo() + "油品");
            }
            // 获取油品信息
            SecDictionary oilNo = commonService.mappingSysCode("OIL_NO", body.getOilNo());
            if (oilNo == null) {
                log.error("BsGasOilPriceController --> createOil() error!", "油品不存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "油品不存在");
            }
            // 获取油品类型
            SecDictionary oilNoType = commonService.mappingSysCode("OIL_NO_TYPE", oilNo.getExt1());
            if (oilNoType == null) {
                log.error("BsGasOilPriceController --> createOil() error!", "未知的的油品类型");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的的油品类型");
            }

            BsGasOilPrice oilPrice = new BsGasOilPrice();
            oilPrice.setMerId(merchant.getId());
            oilPrice.setMerNo(merchant.getMerNo());
            oilPrice.setOilType(Integer.valueOf(oilNoType.getCodeValue()));
            oilPrice.setOilTypeName(oilNoType.getCodeName());
            oilPrice.setOilNo(oilNo.getCodeValue());
            oilPrice.setOilNoName(oilNo.getCodeName());
            oilPrice.setPreferentialMargin(new BigDecimal("0"));
            oilPrice.setPriceOfficial(new BigDecimal("0"));
            oilPrice.setGasStationDrop(new BigDecimal("0"));
            oilPrice.setPriceGun(oilPrice.getPriceOfficial().subtract(oilPrice.getGasStationDrop()));
            oilPrice.setPriceVip(oilPrice.getPriceGun());
            oilPrice.setStatus(GasOilPriceStatusEnum.status1.getNumber());
            gasOilPriceService.editOilPrice(oilPrice);

            // 初始化周期价格
            for (GasOilPriceWeekEnum weekEnum : GasOilPriceWeekEnum.values()) {
                BsGasOilPriceWeek priceWeek = new BsGasOilPriceWeek();
                priceWeek.setMerId(oilPrice.getMerId());
                priceWeek.setMerNo(oilPrice.getMerNo());
                priceWeek.setWeeks(weekEnum.getNumber());
                priceWeek.setOilType(oilPrice.getOilType());
                priceWeek.setOilTypeName(oilPrice.getOilTypeName());
                priceWeek.setOilNo(oilPrice.getOilNo());
                priceWeek.setOilNoName(oilPrice.getOilNoName());
                priceWeek.setPriceOfficial(oilPrice.getPriceOfficial());
                priceWeek.setPriceGun(oilPrice.getPriceGun());
                priceWeek.setPriceVip(oilPrice.getPriceVip());
                gasOilPriceWeekService.editData(priceWeek);
            }

            // 删除缓存
            gasService.clean(oilPrice.getMerNo());
            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value = "/restore", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "恢复")
    public ResponseData restore(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || StringUtils.isBlank(body.getString("merNo"))
                    || StringUtils.isBlank(body.getString("oilNo"))) {
                log.error("BsMerchantController --> restoreMer() error!", "请求参数校验失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询商户
            BsMerchant merchant = merchantService.getMerchant(body.getString("merNo"));
            if (merchant == null) {
                log.error("BsGasOilPriceController --> restoreOil() error!", "未知的商户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
            }
            BsGasOilPrice oilPrice = gasOilPriceService.getGasOilPrice(merchant.getId(), body.getString("oilNo"));
            if (oilPrice == null) {
                log.error("BsGasOilPriceController --> restoreOil() error!", "未知的油品");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的油品");
            }
            oilPrice.setStatus(GasOilPriceStatusEnum.status1.getNumber());
            gasOilPriceService.editOilPrice(oilPrice);

            // 删除缓存
            gasService.clean(oilPrice.getMerNo());
            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value = "/disable", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "禁用油品")
    public ResponseData disable(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || StringUtils.isBlank(body.getString("merNo"))
                    || StringUtils.isBlank(body.getString("oilNo"))) {
                log.error("BsMerchantController --> disableOil() error!", "请求参数校验失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询商户
            BsMerchant merchant = merchantService.getMerchant(body.getString("merNo"));
            if (merchant == null) {
                log.error("BsGasOilPriceController --> disableOil() error!", "未知的商户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
            }
            BsGasOilPrice oilPrice = gasOilPriceService.getGasOilPrice(merchant.getId(), body.getString("oilNo"));
            if (oilPrice == null) {
                log.error("BsGasOilPriceController --> disableOil() error!", "未知的油品");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的油品");
            }
            oilPrice.setStatus(GasOilPriceStatusEnum.status2.getNumber());
            gasOilPriceService.editOilPrice(oilPrice);

            // 删除缓存
            gasService.clean(oilPrice.getMerNo());
            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("BsMerchantController --> disableOil() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除油品")
    public ResponseData delete(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || StringUtils.isBlank(body.getString("merNo"))
                    || StringUtils.isBlank(body.getString("oilNo"))) {
                log.error("BsMerchantController --> disableOil() error!", "请求参数校验失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询商户
            BsMerchant merchant = merchantService.getMerchant(body.getString("merNo"));
            if (merchant == null) {
                log.error("BsGasOilPriceController --> disableOil() error!", "未知的商户");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
            }
            BsGasOilPrice oilPrice = gasOilPriceService.getGasOilPrice(merchant.getId(), body.getString("oilNo"));
            if (oilPrice == null) {
                log.error("BsGasOilPriceController --> disableOil() error!", "未知的油品");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的油品");
            }
            gasOilPriceService.delete(oilPrice);

            // 删除缓存
            gasService.clean(oilPrice.getMerNo());
            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("BsMerchantController --> disableOil() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/queryOilDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油品详情")
    public ResponseData queryOilDetail(@RequestParam(value = "oilId", required = true) Long oilId) {
        try {

          return ResponseMsgUtil.success(gasOilPriceService.getGasOilPrice(oilId));

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

    @RequestMapping(value = "/queryOilList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询油品列表")
    public ResponseData queryOilList(@RequestParam(value = "merNo", required = true) String merNo,
                                     @RequestParam(value = "oilNo", required = false) String oilNo,
                                     @RequestParam(value = "pageNum", required = true) Integer pageNum,
                                     @RequestParam(value = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("merNo", merNo);
            map.put("oilNo", oilNo);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(gasOilPriceService.getGasOilPriceList(map)));

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


}
