package com.cweb.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.BsDeviceOrder;
import com.hfkj.entity.BsDeviceOrderAssign;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserInfoModel;
import com.hfkj.service.BsDeviceOrderAssignService;
import com.hfkj.service.BsDeviceOrderService;
import com.hfkj.service.BsDeviceService;
import com.hfkj.sysenum.DeviceOrderTypeEnum;
import com.hfkj.sysenum.DeviceTypeEnum;
import com.hfkj.sysenum.SecUserTypeEnum;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Api(value = "设备管理")
@RequestMapping(value = "/deviceOrder")
public class BsDeviceOrderController {

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

    @Resource
    private BsDeviceOrderService deviceOrderService;

    @Resource
    private BsDeviceOrderAssignService deviceOrderAssignService;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value="/createDeviceOrder",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "创建设备订单")
    public ResponseData createDeviceOrder(@RequestBody JSONObject body) {
        try {
            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel.getStore() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            if (body.getInteger("orderType") == null || body.getInteger("deviceType") == null || body.getInteger("deviceNum") == null) {
                log.error("BsDeviceController -> addDeviceOrder error!","参数校验失败");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            DeviceOrderTypeEnum orderType = DeviceOrderTypeEnum.getDataByNumber(body.getInteger("orderType"));
            if (orderType == null) {
                log.error("BsDeviceController -> addDeviceOrder error!","未知的订单类型");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "未知的订单类型");
            }

            DeviceTypeEnum deviceType = DeviceTypeEnum.getDataByNumber(body.getInteger("deviceType"));
            if (deviceType == null) {
                log.error("BsDeviceController -> addDeviceOrder error!","未知的设备类型");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "未知的设备类型");
            }

            if (deviceType.getNumber().equals(DeviceTypeEnum.type1.getNumber())) {
                Map<String,Object> param = new HashMap<>();
                param.put("storeId", userInfoModel.getStore().getId());
                param.put("deviceType", deviceType.getNumber());
                param.put("status", "2,3");
                if (deviceOrderService.getOrderList(param).size() != 0) {
                    log.error("BsDeviceController -> addDeviceOrder error!", deviceType.getName() + " 每个门店限制申请1台");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, deviceType.getName()+" 每个门店限制申请1台");
                }
            }

            return ResponseMsgUtil.success(deviceOrderService.createOrder(orderType, deviceType, body.getInteger("deviceNum"),userInfoModel));

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/assignOrder",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分配设备订单")
    public ResponseData assignOrder(@RequestBody JSONObject body) {
        try {

            if (StringUtils.isBlank(body.getString("orderNo"))
                    || body.getJSONArray("deviceNoList") == null
                    || body.getJSONArray("deviceNoList").size() == 0
            ) {
                log.error("configAccount error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            List<String> deviceNoList = new ArrayList<>();
            for (Object deviceNo : body.getJSONArray("deviceNoList")) {
                deviceNoList.add(deviceNo.toString());
            }

            deviceOrderService.assignOrder(body.getString("orderNo"), deviceNoList);

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

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/replace",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "更换设备")
    public ResponseData replace(@RequestBody JSONObject body) {
        try {
            if (body.getLong("deviceOrderAssignId") == null
                    || StringUtils.isBlank(body.getString("deviceNo"))) {
                log.error("configAccount error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            deviceOrderService.replaceDevice(body.getLong("deviceOrderAssignId"), body.getString("deviceNo"));

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

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/orderRefund",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "订单退款")
    public ResponseData orderRefund(@RequestBody JSONObject body) {
        try {
            if (body.getLong("orderNo") == null) {
                log.error("configAccount error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            deviceOrderService.orderRefund(body.getString("orderNo"));

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

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/deviceRefund",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "设备分配订单退款")
    public ResponseData deviceRefund(@RequestBody JSONObject body) {
        try {
            if (body.getLong("deviceOrderAssignId") == null) {
                log.error("configAccount error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            deviceOrderService.deviceRefund(body.getLong("deviceOrderAssignId"));

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

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getOrderDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询订单详情")
    public ResponseData getOrderDetail(@RequestParam(name = "orderNo", required = true) String orderNo) {
        try {
            // 查询订单号
            BsDeviceOrder order = deviceOrderService.getDetailOrder(orderNo);
            if (order == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的订单号");
            }
            order.setOrderAssignList(deviceOrderAssignService.getAssignListByOrderNo(order.getOrderNo()));
            return ResponseMsgUtil.success(order);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getOrderList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询订单列表")
    public ResponseData getOrderList(@RequestParam(name = "companyName", required = false) String companyName,
                                     @RequestParam(name = "agentName", required = false) String agentName,
                                     @RequestParam(name = "salesmanName", required = false) String salesmanName,
                                     @RequestParam(name = "merName", required = false) String merName,
                                     @RequestParam(name = "storeName", required = false) String storeName,
                                     @RequestParam(name = "deviceType", required = false) Integer deviceType,
                                     @RequestParam(name = "orderNo", required = false) String orderNo,
                                     @RequestParam(name = "paySerialNo", required = false) String paySerialNo,
                                     @RequestParam(name = "status", required = false) String status,
                                     @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                     @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {

            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            Map<String, Object> param = new HashMap<>();
            param.put("deviceType", deviceType);
            param.put("orderNo", orderNo);
            param.put("paySerialNo", paySerialNo);
            param.put("status", status);

            if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type0.getNumber())) {
                param.put("companyName", companyName);
                param.put("agentName", agentName);
                param.put("salesmanName", salesmanName);
                param.put("merName", merName);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type1.getNumber())) {
                param.put("companyId", userModel.getBsCompany().getId());
                param.put("agentName", agentName);
                param.put("salesmanName", salesmanName);
                param.put("merName", merName);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type2.getNumber())) {
                param.put("agentId", userModel.getAgent().getId());
                param.put("salesmanName", salesmanName);
                param.put("merName", merName);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type3.getNumber())) {
                param.put("salesmanId", userModel.getSalesman().getId());
                param.put("merName", merName);
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type4.getNumber())) {
                param.put("merId", userModel.getMer().getId());
                param.put("storeName", storeName);

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type5.getNumber())) {
                param.put("storeId", userModel.getStore().getId());

            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            PageHelper.startPage(pageNum,pageSize);
            PageInfo<BsDeviceOrder> pageInfo = new PageInfo<>(deviceOrderService.getOrderList(param));
            for (BsDeviceOrder deviceOrder : pageInfo.getList()) {
                deviceOrder.setOrderAssignList(deviceOrderAssignService.getAssignListByOrderNo(deviceOrder.getOrderNo()));
            }
            return ResponseMsgUtil.success(pageInfo);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }


}
