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.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.HighGasOilPriceTask;
import com.hai.entity.HighMerchantStore;
import com.hai.entity.SecDictionary;
import com.hai.entity.SecRegion;
import com.hai.enum_type.GasTaskPriceTypeEnum;
import com.hai.enum_type.UserObjectTypeEnum;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.CommonService;
import com.hai.service.HighGasOilPriceTaskService;
import com.hai.service.HighMerchantStoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.HashMap;
import java.util.List;
import java.util.Map;

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

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

    @Resource
    private HighGasOilPriceTaskService gasOilPriceTaskService;

    @Resource
    private HighMerchantStoreService merchantStoreService;

    @Resource
    private CommonService commonService;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value="/batchAddTask",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "批量增加任务")
    public ResponseData batchAddTask(@RequestBody List<HighGasOilPriceTask> taskList) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            if (taskList == null || taskList.size() == 0) {
                log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            for (HighGasOilPriceTask task : taskList) {
                if (task.getPriceType() == null
                     || task.getPrice() == null
                     || task.getOilNo() == null
                     || task.getExecutionType() == null
                ) {
                    log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                // 执行方式   1. 立刻执行   2. 定时执行
                if (task.getExecutionType().equals(2) && task.getStartTime() == null) {
                    log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未配置执行时间");
                }

                // 价格类型  1. 国标价   2. 油站价  3. 平台优惠  4. 油站直降
                if (task.getPriceType().equals(GasTaskPriceTypeEnum.type1.getStatus())) {
                    if (task.getRegionId() == null) {
                        log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未配置区域");
                    }
                    // 加油站
                    SecRegion region = commonService.getRegionsById(task.getRegionId());
                    if (region == null) {
                        log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到区域");
                    }
                    task.setRegionId(region.getRegionId());
                    task.setRegionName(region.getRegionName());
                }

                // 价格类型  1. 国标价   2. 油站价  3. 平台优惠  4. 油站直降
                if (task.getPriceType().equals(GasTaskPriceTypeEnum.type2.getStatus())
                        || task.getPriceType().equals(GasTaskPriceTypeEnum.type3.getStatus())
                        || task.getPriceType().equals(GasTaskPriceTypeEnum.type4.getStatus())
                ) {

                    if (task.getMerStoreId() == null) {
                        log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未配置加油站");
                    }
                    // 加油站
                    HighMerchantStore store = merchantStoreService.getDetailById(task.getMerStoreId());
                    if (store == null) {
                        log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到加油站");
                    }
                    task.setRegionId(store.getRegionId());
                    task.setRegionName(store.getRegionName());
                    task.setMerStoreId(store.getId());
                    task.setMerStoreKey(store.getStoreKey());
                    task.setMerStoreName(store.getStoreName());
                    task.setMerStoreAddress(store.getAddress());
                }

                // 查询油品
                SecDictionary oil = commonService.mappingSysCode("GAS_OIL_TYPE", task.getOilNo().toString());
                if (oil == null) {
                    log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                task.setOilType(Integer.parseInt(oil.getExt1()));
                task.setOilTypeName(oil.getExt2());
                task.setOilNoName(oil.getCodeName());
                task.setOpUserId(userInfoModel.getSecUser().getId());
                task.setOpUserName(userInfoModel.getSecUser().getUserName());
            }

            gasOilPriceTaskService.batchAddTask(taskList);

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

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

    @RequestMapping(value="/delTask",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除任务")
    public ResponseData delTask(@RequestBody JSONObject body) {
        try {
            if (body.getLong("taskId") == null) {
                log.error("HighGasOilPriceTaskController -> delTask() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            gasOilPriceTaskService.delTask(body.getLong("taskId"));

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

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

    @RequestMapping(value="/getTaskDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询任务详情")
    public ResponseData getTaskDetail(@RequestParam(name = "taskId", required = true) Long taskId) {
        try {

            return ResponseMsgUtil.success(gasOilPriceTaskService.getDetailById(taskId));

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

    @RequestMapping(value="/getTaskList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询任务列表")
    public ResponseData getTaskList(@RequestParam(name = "regionId", required = false) Integer regionId,
                                    @RequestParam(name = "regionName", required = false) String regionName,
                                    @RequestParam(name = "merStoreId", required = false) Integer merStoreId,
                                    @RequestParam(name = "merStoreKey", required = false) String merStoreKey,
                                    @RequestParam(name = "merStoreName", required = false) String merStoreName,
                                    @RequestParam(name = "oilType", required = false) Integer oilType,
                                    @RequestParam(name = "oilNo", required = false) Integer oilNo,
                                    @RequestParam(name = "priceType", required = false) Integer priceType,
                                    @RequestParam(name = "executionType", required = false) Integer executionType,
                                    @RequestParam(name = "status", required = false) Integer status,
                                    @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                    @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                log.error("HighGasController -> disabledOil() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            Map<String, Object> param = new HashMap<>();
            param.put("regionId", regionId);
            param.put("regionName", regionName);
            param.put("merStoreId", merStoreId);
            param.put("merStoreKey", merStoreKey);
            param.put("merStoreName", merStoreName);

            if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type0.getType())) {

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type1.getType())) {
                param.put("regionId", userInfoModel.getBsCompany().getRegionId());

            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type3.getType())) {
                param.put("merStoreId", userInfoModel.getMerchantStore().getId());
            }
            param.put("oilType", oilType);
            param.put("oilNo", oilNo);
            param.put("priceType", priceType);
            param.put("executionType", executionType);
            param.put("status", status);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(gasOilPriceTaskService.getTaskList(param)));

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

}
