package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.cweb.config.SysConfig;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.channel.lakala.config.LaKaLaConfig;
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.DateUtil;
import com.hfkj.common.utils.IDGenerator;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.*;
import com.hfkj.model.*;
import com.hfkj.obs.HuaWeiYunObs;
import com.hfkj.service.*;
import com.hfkj.sysenum.*;
import com.obs.services.model.PutObjectResult;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

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

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

    @Resource
    private BsDeviceService deviceService;

    @Resource
    private BsDevicePriceService devicePriceService;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value="/bindStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "绑定门店")
    public ResponseData bindStore(@RequestBody JSONObject body) {
        try {
            if (body.getLong("storeId") == null || StringUtils.isBlank(body.getString("deviceNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询设备
            BsDevice device = deviceService.getDetailByNo(body.getString("deviceNo"));
            if (device == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的设备");
            }

            deviceService.bindStore(device.getId(), body.getLong("storeId") );

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/unbindStore",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "解绑门店")
    public ResponseData unbindStore(@RequestBody JSONObject body) {
        try {
            if (StringUtils.isBlank(body.getString("deviceNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询设备
            BsDevice device = deviceService.getDetailByNo(body.getString("deviceNo"));
            if (device == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的设备");
            }

            deviceService.unbindStore(device.getId());

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getDevicePrice",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询设备金额")
    public ResponseData getDevicePrice(@RequestParam(name = "priceType", required = true) Integer priceType,
                                       @RequestParam(name = "deviceType", required = true) Integer deviceType) {
        try {

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

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

            return ResponseMsgUtil.success(devicePriceService.getPriceByType(devicePriceTypeEnum, typeEnum));

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

    @RequestMapping(value="/getSalesmanDeviceList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询业务员设备列表")
    public ResponseData getSalesmanDeviceList(@RequestParam(name = "salesmanId", required = true) Long salesmanId,
                                              @RequestParam(name = "isAssignStore", required = false) Boolean isAssignStore,
                                              @RequestParam(name = "deviceSn", required = false) String deviceSn,
                                              @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                              @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {

            Map<String, Object> param = new HashMap<>();
            param.put("salesmanId", salesmanId);
            param.put("isAssignStore", isAssignStore);
            param.put("deviceSn", deviceSn);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(deviceService.getDeviceList(param)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getStoreDeviceList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询门店设备列表")
    public ResponseData getStoreDeviceList(@RequestParam(name = "storeId", required = true) Long storeId,
                                           @RequestParam(name = "deviceSn", required = false) String deviceSn,
                                           @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                           @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("storeId", storeId);
            param.put("deviceSn", deviceSn);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(deviceService.getDeviceList(param)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getDeviceList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询设备列表")
    public ResponseData getDeviceList(@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 = "storeId", required = false) String storeId,
                                      @RequestParam(name = "storeName", required = false) String storeName,
                                      @RequestParam(name = "deviceType", required = false) Integer deviceType,
                                      @RequestParam(name = "deviceNo", required = false) String deviceNo,
                                      @RequestParam(name = "buildStatus", required = false) Boolean buildStatus,
                                      @RequestParam(name = "status", required = false) Integer 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("deviceNo", deviceNo);
            param.put("status", status);
            param.put("buildStatus", buildStatus);

            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);
                param.put("storeId", storeId);

            } 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);
                param.put("storeId", storeId);

            } 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);
                param.put("storeId", storeId);

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

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

            } 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);
            return ResponseMsgUtil.success(new PageInfo<>(deviceService.getDeviceList(param)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }


}
