package com.iformall.controller.device;

import com.alibaba.fastjson.JSONObject;
import com.iformall.annotation.SystemControllerLog;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.po.*;
import com.iformall.enums.*;
import com.iformall.exception.MallinkException;
import com.iformall.service.ExcelService;
import com.iformall.service.WxMerchantService;
import com.iformall.service.kw.KwBoxService;
import com.iformall.service.kw.KwMerchantMeterService;
import com.iformall.service.kw.KwMeterDataService;
import com.iformall.service.kw.KwMeterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("kwMeter")
@Api(description="电表设备")
public class KwMeterController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
    private KwMeterService kwMeterService;

	@Autowired
	private KwMeterDataService kwMeterDataService;

	@Autowired
	private KwMerchantMeterService kwMerchantMeterService;

	@Autowired
	private KwBoxService kwBoxService;

	@Autowired
	private ExcelService excelService;

	@Autowired
	private WxMerchantService wxMerchantService;


	@ApiOperation("设备列表")
	@GetMapping("list")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
			@ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)})
    @SystemControllerLog(description = "电表设备-设备列表")
	public Result list(@ModelAttribute KwMeter kwMeter, Integer pageNum, Integer pageSize) {
		if (kwMeter == null) kwMeter = new KwMeter();
		kwMeter.setTenantId(getTenantId());
		kwMeter.setStatus(EnumMeterStatus.VALID.getCode());
		return new ResultData(kwMeterService.listAsPage(kwMeter, pageNum,pageSize));
	}

	@ApiOperation("添加设备")
	@PostMapping("add")
	@SystemControllerLog(description = "电表设备-添加设备")
	public Result add(@RequestBody KwMeter kwMeter) {

		if (kwMeter == null)
			return new ResultData(ErrorCode.SYS_PARAMETER_ERROR);
		if (kwMeter.getAddress() == null)
			return new ResultData(ErrorCode.SYS_PARAMETER_ERROR);

		KwMeter record = new KwMeter();
		record.setTenantId(getTenantId());
		record.setAddress(kwMeter.getAddress());
		record.setStatus(EnumMeterStatus.VALID.getCode());
		List<KwMeter> KwMeters = kwMeterService.findList(record);
		if (KwMeters.size() > 0)
			return new ResultData(ErrorCode.DEVICE_ALREADY_EXIST);
		kwMeter.setTenantId(getTenantId());
		kwMeter.setBoxId(0L);
		kwMeter.setStatus(EnumMeterStatus.VALID.getCode());
		kwMeter.setBindStatus(EnumMeterBindStatus.UNBIND.getCode());
		kwMeterService.saveOrUpdate(kwMeter);
		return new ResultData(kwMeter);
	}


	@ApiOperation("更新设备")
	@PostMapping("update")
    @SystemControllerLog(description = "电表设备-更新设备")
	public Result update(@RequestBody KwMeter kwMeter) {
    	if (kwMeter == null)
    		return new ResultData(ErrorCode.SYS_PARAMETER_ERROR);
		if (kwMeter.getId() == null)
			return new ResultData(ErrorCode.SYS_PARAMETER_ERROR);
		kwMeter.setAddress(null);
		kwMeterService.saveOrUpdate(kwMeter);
		return new ResultData(kwMeter);
	}

	@ApiOperation("设备详情")
	@GetMapping("detail")
    @SystemControllerLog(description = "电表设备-设备详情")
	public Result detail(@RequestParam Long id) {
		if (id == null)
			return new ResultData(ErrorCode.SYS_PARAMETER_ERROR);
		KwMeter kwMeter = kwMeterService.getById(id);
		if (kwMeter == null)
			return new ResultData(ErrorCode.DEVICE_NOT_FOUND);
		return new ResultData(kwMeter);
	}

	@ApiOperation("删除设备")
	@PostMapping("delete")
    @SystemControllerLog(description = "电表设备-删除设备")
	public Result delete(@RequestParam Long id) {
		if (id == null)
			return new ResultData(ErrorCode.SYS_PARAMETER_ERROR);
		KwMeter kwMeter = new KwMeter();
		kwMeter.setId(id);
		kwMeter.setStatus(EnumBoxStatus.INVALID.getCode());
		kwMeterService.unbind(id);
		kwMerchantMeterService.unbind(id);
		kwMeterService.saveOrUpdate(kwMeter);

		return new ResultData(kwMeter);
	}


	private KwBox addOrBind(KwBox kwBox) {

		KwBox record = new KwBox();
		record.setImei(kwBox.getImei());
		record.setStatus(EnumBoxStatus.VALID.getCode());
		List<KwBox> list = kwBoxService.findList(record);
		if (list.size() > 0) return list.get(0);
		kwBox.setTenantId(getTenantId());
		kwBox.setStatus(EnumBoxStatus.VALID.getCode());
		kwBoxService.saveOrUpdate(kwBox);
		return kwBox;
	}

	public void addOrBind(KwMerchantMeter kwMerchantMeter) {

		if (kwMerchantMeter == null)return;
		if (kwMerchantMeter.getMerchantId() == null)return;
		if (kwMerchantMeter.getMeterId() == null)return;

		KwMerchantMeter record = new KwMerchantMeter();
		record.setMeterId(kwMerchantMeter.getMeterId());
		record.setStatus(EnumMerchantMeterStatus.VALID.getCode());
		if (kwMerchantMeterService.selectCount(record) > 0) return;

		kwMerchantMeter.setStatus(EnumMerchantMeterStatus.VALID.getCode());
		kwMerchantMeterService.saveOrUpdate(kwMerchantMeter);
	}

	private void addOrUpdate(KwMeter kwMeter) {
		KwMeter record = new KwMeter();
		record.setTenantId(getTenantId());
		record.setAddress(kwMeter.getAddress());
		record.setStatus(EnumMeterStatus.VALID.getCode());
		List<KwMeter> kwMeters = kwMeterService.findList(record);
		if (kwMeters.size() > 0)
			kwMeter.setId(kwMeters.get(0).getId());
		kwMeterService.saveOrUpdate(kwMeter);
	}

	@ApiOperation("导入设备")
	@PostMapping(value = "import", consumes = "multipart/*")
	@SystemControllerLog(description = "电表管理-导入数据")
	public Result importMeters(@RequestParam("file") MultipartFile mFile) {
		if (mFile == null) {
			return new ResultData(ErrorCode.EXCEL_IMPORT_ERROR);
		}

		try {
			XSSFWorkbook workbook = new XSSFWorkbook(mFile.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
				XSSFRow row = sheet.getRow(i);
				if (row == null)
					continue;
				KwMeter kwMeter = new KwMeter();
				Cell c = row.getCell(0,Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
				if (c != null && c.getCellType() == CellType.STRING ) {
					kwMeter.setAddress(c.getStringCellValue());
				} else {
					continue;
				}
				c = row.getCell(1,Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
				if (c != null && c.getCellType() == CellType.STRING )  {kwMeter.setPlace(c.getStringCellValue());}
				c = row.getCell(2,Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
				if (c != null && c.getCellType() == CellType.STRING )  {kwMeter.setBrand(c.getStringCellValue());}
				c = row.getCell(3,Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
				if (c != null && c.getCellType() == CellType.STRING )  {kwMeter.setModel(c.getStringCellValue());}

				c = row.getCell(4,Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
				if (c != null && c.getCellType() == CellType.STRING )  {kwMeter.setProtocol(Integer.parseInt(c.getStringCellValue()));}
				c = row.getCell(5,Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
				if (c != null && c.getCellType() == CellType.STRING )  {kwMeter.setBandrate(Integer.parseInt(c.getStringCellValue()));}

				if (kwMeter.getProtocol() != null || kwMeter.getBandrate() != null) {
                    JSONObject jsonObject = new JSONObject();
                    if (kwMeter.getProtocol() != null) jsonObject.put("protocol",kwMeter.getProtocol());
                    if (kwMeter.getBandrate() != null) jsonObject.put("bandrate",kwMeter.getBandrate());
                    kwMeter.setConfig(jsonObject.toJSONString());
                }

				c = row.getCell(6,Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
				if (c != null && c.getCellType() == CellType.STRING )  {
					String imei = c.getStringCellValue();
					KwBox kwBox = new KwBox();
					kwBox.setImei(imei);
					kwBox = addOrBind(kwBox);
					kwMeter.setBindStatus(EnumMeterBindStatus.BIND.getCode());
					kwMeter.setBoxId(kwBox.getId());
				} else {
					kwMeter.setBindStatus(EnumMeterBindStatus.UNBIND.getCode());
					kwMeter.setBoxId(0L);
				}
				kwMeter.setStatus(EnumMeterStatus.VALID.getCode());
				kwMeter.setOnlineStatus(EnumMeterOnlineStatus.OFFLINE.getCode());
				addOrUpdate(kwMeter);

				c = row.getCell(7,Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
				if (c != null && c.getCellType() == CellType.STRING ) {
					String merchantName = c.getStringCellValue();
					Optional<WxMerchant> wxMerchant = wxMerchantService.findByName(merchantName);
					if (wxMerchant.isPresent()) {
						KwMerchantMeter kwMerchantMeter = new KwMerchantMeter();
						kwMerchantMeter.setMerchantId(wxMerchant.get().getId());
						kwMerchantMeter.setMeterId(kwMeter.getId());
						addOrBind(kwMerchantMeter);
					}
				}
			}
		}catch(Exception e) {
			return new ResultData(ErrorCode.EXCEL_IMPORT_ERROR);
		}

		return new ResultData();
	}

	@GetMapping("/exportTemplate")
	@SystemControllerLog(description = "电表管理-导出模板")
	public void exportTemplate(HttpServletRequest request, HttpServletResponse response) {
		List <KwMeter> meterList = new ArrayList<>();
		KwMeter meter1 = new KwMeter();
		meter1.setAddress("000020492980");
		meter1.setPlace("1栋-3楼-2号电井");
		meter1.setBrand("人民电器");
		meter1.setModel("DS866");
		meter1.setProtocol(1);
		meter1.setBandrate(1200);
		meter1.setBoxImei("865501040775810");
		meter1.setMerchantName("富茂旗舰店");
		meterList.add(meter1);
		excelService.exportExcel(meterList, null, "电表模板", KwMeter.class, "电表模板.xlsx", response, true);
	}
}
