package com.bweb.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.*;
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 org.apache.commons.collections4.MapUtils;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/tyAgentPrice")
@Api(value = "订单接口")
public class HighTyAgentPriceController {

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

    @Resource
    private HighTyAgentPriceService tyAgentPriceService;

    @Resource
    private HighTyAgentOilStationService tyAgentOilStationService;

    @Resource
    private HighMerchantStoreService merchantStoreService;

    @Resource
    private HighGasOilPriceService gasOilPriceService;

    @Resource
    private HighGasDiscountOilPriceService gasDiscountOilPriceService;

    @Resource
    private CommonService commonService;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value = "/editPrice", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑价格")
    public ResponseData editPrice(@RequestBody JSONArray bodyArray) {
        try {

            if (bodyArray == null || bodyArray.size() == 0) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            for (Object obj : bodyArray) {
                JSONObject body = (JSONObject)JSONObject.toJSON(obj);
                if (body.getInteger("belongType") == null
                        || body.getLong("oilStationId") == null
                        || StringUtils.isBlank(body.getString("oilStationName"))
                        || StringUtils.isBlank(body.getString("oilNoName"))
                        || StringUtils.isBlank(body.getString("oilNo"))
                        || body.getBigDecimal("priceRate") == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
                }

                // 查询油站
                HighTyAgentPrice agentOilStation = tyAgentPriceService.getDetail(body.getInteger("belongType"),body.getLong("oilStationId"), body.getString("oilNo"));
                if (agentOilStation == null) {
                    agentOilStation = new HighTyAgentPrice();
                    agentOilStation.setBelongType(body.getInteger("belongType"));
                    agentOilStation.setOilStationId(body.getLong("oilStationId"));
                    agentOilStation.setOilStationName(body.getString("oilStationName"));
                    agentOilStation.setTyAgentOilStationId(body.getLong("tyAgentOilStationId"));
                    agentOilStation.setOilNoName(body.getString("oilNoName"));
                    agentOilStation.setOilNo(body.getString("oilNo"));
                    agentOilStation.setPriceRate(body.getBigDecimal("priceRate"));
                } else {
                    agentOilStation.setPriceRate(body.getBigDecimal("priceRate"));
                }
                tyAgentPriceService.editTyAgentPrice(agentOilStation);
            }

            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value = "/batchConfigPrice", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "批量配置价格")
    public ResponseData batchConfigPrice(@RequestBody JSONObject body) {
        try {
            if (body.getInteger("belongType") == null
                    || body.getInteger("oilNo") == null
                    || body.getBigDecimal("priceRate") == null
                    || body.getJSONArray("oilStationList") == null
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            String oilNoName = commonService.getDictionaryCodeName("GAS_OIL_TYPE", body.getInteger("oilNo").toString());
            if (StringUtils.isBlank(oilNoName)) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的油品");
            }

            for (Object obj : body.getJSONArray("oilStationList")) {
                JSONObject oilStation = (JSONObject)JSONObject.toJSON(obj);
                if (oilStation.getLong("oilStationId") == null || StringUtils.isBlank(oilStation.getString("oilStationName"))) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
                }
                // 查询油站
                HighTyAgentPrice agentOilStation = tyAgentPriceService.getDetail(body.getInteger("belongType"), oilStation.getLong("oilStationId"), body.getString("oilNo"));
                if (agentOilStation == null) {
                    agentOilStation = new HighTyAgentPrice();
                    agentOilStation.setBelongType(body.getInteger("belongType"));
                    agentOilStation.setOilStationId(oilStation.getLong("oilStationId"));
                    agentOilStation.setOilStationName(oilStation.getString("oilStationName"));
                    agentOilStation.setTyAgentOilStationId(oilStation.getLong("tyAgentOilStationId"));
                    agentOilStation.setOilNoName(oilNoName);
                    agentOilStation.setOilNo(body.getString("oilNo"));
                    agentOilStation.setPriceRate(body.getBigDecimal("priceRate"));
                } else {
                    agentOilStation.setPriceRate(body.getBigDecimal("priceRate"));
                }
                tyAgentPriceService.editTyAgentPrice(agentOilStation);
            }

            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value = "/batchConfigOilNo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "批量油品管理")
    public ResponseData batchConfigOilNo(@RequestBody JSONObject body) {
        try {
            if (body.getInteger("oilNo") == null
                  || body.getInteger("status") == null
                  || body.getJSONArray("oilStationList") == null
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            String oilNoName = commonService.getDictionaryCodeName("GAS_OIL_TYPE", body.getInteger("oilNo").toString());
            if (StringUtils.isBlank(oilNoName)) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的油品");
            }
            for (Object obj : body.getJSONArray("oilStationList")) {
                JSONObject oilStation = (JSONObject)JSONObject.toJSON(obj);
                if (oilStation.getLong("oilStationId") == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
                }
                HighGasOilPrice oilNo = gasOilPriceService.getGasOilPriceByStoreAndOilNo(oilStation.getLong("oilStationId"), body.getInteger("oilNo"));
                if (oilNo != null) {
                    oilNo.setStatus(body.getInteger("status"));
                    gasOilPriceService.editGasOilPrice(oilNo);
                }
            }

            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value = "/getOilStationPrice", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "油站价格")
    public ResponseData getOilStationPrice(@RequestParam(name = "belongType", required = true) Integer belongType,
                                           @RequestParam(name = "oilStationId", required = true) Long oilStationId) {
        try {

            List<HighGasOilPrice> oilPriceList = gasOilPriceService.getGasOilPriceByStore(oilStationId);
            if (oilPriceList == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "此加油站，暂无法配置");
            }
            List<Map<String, Object>> oilPriceMapList = new ArrayList<>();
            Map<String, Object> oilPriceMap;

            for (HighGasOilPrice price : oilPriceList) {
                oilPriceMap = new HashMap<>();
                oilPriceMap.put("oilNo", price.getOilNo());
                oilPriceMap.put("oilNoName", price.getOilNoName());
                oilPriceMap.put("status", price.getStatus());
                oilPriceMap.put("lowPrice", commonService.getDictionaryCodeName("TY_AGENT_OIL_STATION_LOW_PRICE", price.getOilNo().toString()));

                // 价格
                HighTyAgentPrice priceRate = tyAgentPriceService.getDetail(belongType, oilStationId, price.getOilNo().toString());
                if (priceRate == null) {
                    // 油站
                    HighMerchantStore store = merchantStoreService.getDetailById(price.getMerchantStoreId());
                    if (store != null) {
                        oilPriceMap.put("oilStationId", store.getId());
                        oilPriceMap.put("oilStationName", store.getStoreName());
                    }
                    oilPriceMap.put("priceRate", gasDiscountOilPriceService.getDetailByOilNo(price.getOilNo().toString()).getPriceRate());
                } else {
                    oilPriceMap.put("oilStationId", priceRate.getOilStationId());
                    oilPriceMap.put("oilStationName", priceRate.getOilStationName());
                    oilPriceMap.put("priceRate", priceRate.getPriceRate());
                }
                oilPriceMapList.add(oilPriceMap);
            }

            return ResponseMsgUtil.success(oilPriceMapList);

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

}
