package com.bweb.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.bweb.config.SysConfig;
import com.bweb.config.SysConst;
import com.bweb.excel.listener.ImportDeviceListener;
import com.bweb.excel.model.ImportDeviceModel;
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.BsDevice;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserInfoModel;
import com.hfkj.service.BsDeviceService;
import com.hfkj.sysenum.DeviceOpTypeEnum;
import com.hfkj.sysenum.DeviceStatusEnum;
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 org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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

    @Resource
    private BsDeviceService deviceService;

    @Resource
    private UserCenter userCenter;


    @RequestMapping(value="/editDevice",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑设备")
    public ResponseData editDevice(@RequestBody BsDevice body) {
        try {
            UserInfoModel sessionModel = userCenter.getSessionModel(UserInfoModel.class);
            if (body == null || body.getDeviceType() == null || StringUtils.isBlank(body.getDeviceNo())) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            BsDevice device;
            if (body.getId() != null) {
                // 查询设备信息
                device = deviceService.getDetail(body.getId());
                if (device == null) {
                    log.error("BsDeviceController error!","未找到设备");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到设备");
                }

                BsDevice detailNo = deviceService.getDetailByNo(body.getDeviceNo());
                if (detailNo != null && detailNo.getDeviceNo().equals(device.getDeviceNo())) {
                    log.error("BsDeviceController error!","设备编号已存在");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "设备编号已存在");
                }
            } else {
                device = new BsDevice();
                if (deviceService.getDetailByNo(body.getDeviceNo()) != null) {
                    log.error("BsDeviceController error!","设备编号已存在");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "设备编号已存在");
                }
            }
            device.setDeviceType(body.getDeviceType());
            device.setDeviceNo(body.getDeviceNo());
            device.setDeviceImsi(body.getDeviceImsi());
            device.setDeviceIccid(body.getDeviceIccid());
            device.setBindStatus(false);
            device.setOpUserId(sessionModel.getSecUser().getId());
            device.setOpUserName(sessionModel.getSecUser().getUserName());
            deviceService.editDevice(device);

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

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

    @RequestMapping(value="/importDevice",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "导入设备")
    public ResponseData importDevice(@RequestBody JSONObject body) {
        try {

            if (body == null
                    || body.getInteger("deviceType") == null
                    || StringUtils.isBlank(body.getString("file"))
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            UserInfoModel userModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            FileInputStream fileUrl = new FileInputStream(SysConst.getSysConfig().getFileUrl()+File.separator+body.getString("file"));
            if (fileUrl == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请上传文件");
            }

            ImportDeviceListener importDeviceListener = new ImportDeviceListener();
            importDeviceListener.initData(userModel, body.getInteger("deviceType"), deviceService);
            EasyExcel.read(fileUrl, ImportDeviceModel.class, importDeviceListener).sheet().doRead();

            return ResponseMsgUtil.success(importDeviceListener.getErrorData());

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

    @RequestMapping(value="/assignCompany",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分配公司")
    public ResponseData assignCompany(@RequestBody JSONObject body) {
        try {

            if (body.getLong("companyId") == null
                    || body.getJSONArray("deviceArray") == null
                    || body.getJSONArray("deviceArray").size() == 0
            ) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            List<Long> deviceIdList = new ArrayList<>();
            for (Object obj : body.getJSONArray("deviceArray")) {
                JSONObject data = (JSONObject) obj;
                if (data.getLong("id") == null) {
                    log.error("BsDeviceController error!","参数错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                deviceIdList.add(data.getLong("id"));
            }

            deviceService.batchBindCompany(deviceIdList, body.getLong("companyId"));

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

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

    @RequestMapping(value="/assignAgent",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分配代理商")
    public ResponseData assignAgent(@RequestBody JSONObject body) {
        try {

            if (body.getLong("agentId") == null
                    || body.getJSONArray("deviceArray") == null
                    || body.getJSONArray("deviceArray").size() == 0
            ) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            List<Long> deviceIdList = new ArrayList<>();
            for (Object obj : body.getJSONArray("deviceArray")) {
                JSONObject data = (JSONObject) obj;
                if (data.getLong("id") == null) {
                    log.error("BsDeviceController error!","参数错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                deviceIdList.add(data.getLong("id"));
            }

            deviceService.batchBindAgent(deviceIdList, body.getLong("agentId"));

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

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

    @RequestMapping(value="/assignSalesman",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分配业务员")
    public ResponseData assignSalesman(@RequestBody JSONObject body) {
        try {

            if (body.getLong("salesmanId") == null
                    || body.getJSONArray("deviceArray") == null
                    || body.getJSONArray("deviceArray").size() == 0
            ) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            List<Long> deviceIdList = new ArrayList<>();
            for (Object obj : body.getJSONArray("deviceArray")) {
                JSONObject data = (JSONObject) obj;
                if (data.getLong("id") == null) {
                    log.error("BsDeviceController error!","参数错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                deviceIdList.add(data.getLong("id"));
            }

            deviceService.batchBindSalesman(deviceIdList, body.getLong("salesmanId"));

            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 (body.getLong("deviceId") == null) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            deviceService.unbindStore(body.getLong("deviceId"));

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

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

    @RequestMapping(value="/delDevice",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除设备")
    public ResponseData delDevice(@RequestBody JSONObject body) {
        try {

            if (body.getLong("deviceId") == null) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 设备详情
            BsDevice device = deviceService.getDetail(body.getLong("deviceId"));
            if (device == null) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到设备详情");
            }
            if (!device.getStatus().equals(DeviceStatusEnum.status1.getNumber())) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "设备状态异常");
            }

            device.setStatus(DeviceStatusEnum.status0.getNumber());
            deviceService.editDevice(device);
            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/enableDevice",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "启用设备")
    public ResponseData enableDevice(@RequestBody JSONObject body) {
        try {

            if (body.getLong("deviceId") == null) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 设备详情
            BsDevice device = deviceService.getDetail(body.getLong("deviceId"));
            if (device == null) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到设备详情");
            }
            if (!device.getStatus().equals(DeviceStatusEnum.status2.getNumber())) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "设备状态异常");
            }

            device.setStatus(DeviceStatusEnum.status1.getNumber());
            deviceService.editDevice(device);
            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/disableDevice",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "禁用设备")
    public ResponseData disableDevice(@RequestBody JSONObject body) {
        try {

            if (body.getLong("deviceId") == null) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 设备详情
            BsDevice device = deviceService.getDetail(body.getLong("deviceId"));
            if (device == null) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到设备详情");
            }
            if (!device.getStatus().equals(DeviceStatusEnum.status1.getNumber())) {
                log.error("BsDeviceController error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "设备状态异常");
            }

            device.setStatus(DeviceStatusEnum.status2.getNumber());
            deviceService.editDevice(device);
            return ResponseMsgUtil.success("操作成功");

        } 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) Long storeId,
                                      @RequestParam(name = "storeName", required = false) String storeName,
                                      @RequestParam(name = "deviceType", required = false) Integer deviceType,
                                      @RequestParam(name = "deviceNo", required = false) String deviceNo,
                                      @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);

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

            } else if (userModel.getSecUser().getObjectType().equals(SecUserTypeEnum.type4.getNumber())) {
                param.put("merId", userModel.getMer().getId());
                param.put("storeId", storeId);
                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);
            return ResponseMsgUtil.success(new PageInfo<>(deviceService.getDeviceList(param)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }


}
