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.BsGasOilPriceTask;
import com.hfkj.entity.BsMerchant;
import com.hfkj.entity.SecDictionary;
import com.hfkj.entity.SecRegion;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.service.gas.BsGasOilPriceTaskService;
import com.hfkj.service.merchant.BsMerchantService;
import com.hfkj.service.CommonService;
import com.hfkj.sysenum.gas.GasOilPriceTaskExecutionTypeEnum;
import com.hfkj.sysenum.gas.GasTaskPriceTypeEnum;
import com.hfkj.sysenum.SecUserObjectTypeEnum;
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.util.HashMap;
import java.util.List;
import java.util.Map;

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

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

    @Resource
    private BsGasOilPriceTaskService gasOilPriceTaskService;
    @Resource
    private BsMerchantService merchantService;
    @Resource
    private UserCenter userCenter;
    @Resource
    private CommonService commonService;

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

            for (BsGasOilPriceTask task : taskList) {
                if (task.getPriceType() == null
                     || task.getPrice() == null
                     || task.getOilNo() == null
                     || task.getExecutionType() == null) {
                    log.error("BsGasOilPriceTaskController -> batchAddTask() error!","");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                // 执行方式   1. 立刻执行   2. 定时执行
                if (task.getExecutionType().equals(GasOilPriceTaskExecutionTypeEnum.type2.getNumber()) && task.getStartTime() == null) {
                    log.error("BsGasOilPriceTaskController -> batchAddTask() 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 (StringUtils.isBlank(task.getMerNo())) {
                        log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未配置加油站");
                    }
                    // 加油站
                    BsMerchant merchant = merchantService.getMerchant(task.getMerNo());
                    if (merchant == null) {
                        log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到加油站");
                    }
                    task.setRegionId(merchant.getProvinceCode());
                    task.setRegionName(merchant.getProvinceName());
                    task.setMerId(merchant.getId());
                    task.setMerNo(merchant.getMerNo());
                    task.setMerName(merchant.getMerName());
                    task.setMerAddress(merchant.getAddress());
                }
                // 查询油品
                SecDictionary oil = commonService.mappingSysCode("OIL_NO", task.getOilNo().toString());
                if (oil == null) {
                    log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                // 查询油品
                SecDictionary oilNoType = commonService.mappingSysCode("OIL_NO_TYPE", ""+oil.getExt1());
                if (oilNoType == null) {
                    log.error("HighGasDiscountOilPriceController -> updateOilPriceOfficial() error!","");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                task.setOilType(Integer.valueOf(oilNoType.getCodeValue()));
                task.setOilTypeName(oilNoType.getCodeName());
                task.setOilNoName(oil.getCodeName());
                task.setOpUserId(userInfoModel.getAccount().getId());
                task.setOpUserName(userInfoModel.getAccount().getUserName());

                if (task.getOilPriceZoneId() != null) {
                    // 查询价区
                    SecDictionary oilPriceZone = commonService.mappingSysCode("OIL_PRICE_ZONE", "" + task.getOilPriceZoneId());
                    if (oilPriceZone != null) {
                        task.setOilPriceZoneId(Integer.valueOf(oilPriceZone.getCodeValue()));
                        task.setOilPriceZoneName(oilPriceZone.getCodeName());
                    }
                }
            }

            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) Long regionId,
                                    @RequestParam(name = "regionName", required = false) String regionName,
                                    @RequestParam(name = "merId", required = false) Long merId,
                                    @RequestParam(name = "merNo", required = false) String merNo,
                                    @RequestParam(name = "merName", required = false) String merName,
                                    @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 {
            SecUserSessionObject userInfoModel = userCenter.getSessionModel(SecUserSessionObject.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }

            Map<String, Object> param = new HashMap<>();
            param.put("regionId", regionId);
            param.put("regionName", regionName);
            param.put("merId", merId);
            param.put("merNo", merNo);
            param.put("merName", merName);

            if (userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type1.getCode())) {

            } else if (userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type2.getCode())
                || userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type3.getCode())) {
                param.put("merId", userInfoModel.getMerchant().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);
        }
    }

}
