package org.jeecg.modules.system.app.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.system.app.entity.AppDevice;
import org.jeecg.modules.system.app.entity.AppSite;
import org.jeecg.modules.system.app.mapper.AppSiteMapper;
import org.jeecg.modules.system.app.service.IAppDeviceService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

import static org.jeecg.modules.hikiot.HikiotTool.*;

/**
 * @Description: nm_device
 * @Author: jeecg-boot
 * @Date:   2025-08-19
 * @Version: V1.0
 */
@Tag(name="nm_device")
@RestController
@RequestMapping("/com/AppDevice")
@Slf4j
public class AppDeviceController extends JeecgController<AppDevice, IAppDeviceService> {
	@Resource
	private IAppDeviceService AppDeviceService;
	@Resource
	private AppSiteMapper appSiteMapper;

	/**
	 * 分页列表查询
	 *
	 * @param AppDevice
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "nm_device-分页列表查询")
	@Operation(summary = "nm_device-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<AppDevice>> queryPageList(AppDevice AppDevice,
												  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
												  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
												  HttpServletRequest req) {


		QueryWrapper<AppDevice> queryWrapper = QueryGenerator.initQueryWrapper(AppDevice, req.getParameterMap());
		Page<AppDevice> page = new Page<AppDevice>(pageNo, pageSize);
		IPage<AppDevice> pageList = AppDeviceService.page(page, queryWrapper);
		if (CollUtil.isEmpty(pageList.getRecords())) {
			return Result.OK(pageList);
		}
		pageList.getRecords().forEach(item -> {
			if (null != item.getSiteId() && !item.getSiteId().isEmpty()) {
				item.setSiteName(appSiteMapper.selectById(item.getSiteId()).getName());
			}
		});
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 *
	 * @return
	 */
	@AutoLog(value = "nm_device-添加")
	@Operation(summary = "nm_device-添加")
	@PostMapping(value = "/add")
	@Transactional
	public Result<String> add(@RequestBody AppDevice appDevice) {
		if (AppDeviceService.getOne(Wrappers.<AppDevice>lambdaQuery()
				.eq(AppDevice::getDeviceSerial, appDevice.getDeviceSerial())) != null) {
			return Result.error("设备已存在！");
		}
		AppDeviceService.save(appDevice);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 *
	 * @param appDevice
	 * @return
	 */
	@AutoLog(value = "nm_device-编辑")
	@Operation(summary = "nm_device-编辑")
	@PostMapping(value = "/edit")
	@Transactional
	public Result<String> edit(@RequestBody AppDevice appDevice) {
		AppSite appSite = appSiteMapper.selectById(appDevice.getSiteId());
		appDevice.setOrgCode(appSite.getOrgCode());
		if (AppDeviceService.getOne(Wrappers.<AppDevice>lambdaQuery()
				.eq(AppDevice::getDeviceSerial, appDevice.getDeviceSerial())
				.eq(AppDevice::getSiteId, appDevice.getSiteId())
				.eq(AppDevice::getDeviceType, appDevice.getDeviceType())) != null) {
			return Result.error("设备已存在！");
		}
		AppDeviceService.updateById(appDevice);
		if (appDevice.getDeviceSerial() != null && appDevice.getValidateCode() != null && appDevice.getSiteId() != null) {
			String addDevice = addDevice(appDevice.getDeviceSerial(), appDevice.getValidateCode());
			String userWeekPlan = addUserWeekPlan(appDevice.getDeviceSerial());
			String userPlanTemplate = addUserPlanTemplate(appDevice.getDeviceSerial());
			JsonObject deviceJson = JsonParser.parseString(addDevice).getAsJsonObject();
			JsonObject userWeekPlanJson = JsonParser.parseString(userWeekPlan).getAsJsonObject();
			JsonObject userPlanTemplateJson = JsonParser.parseString(userPlanTemplate).getAsJsonObject();
			if (deviceJson.get("code").getAsInt() == 0
					&& userWeekPlanJson.get("code").getAsInt() == 0
					&& userPlanTemplateJson.get("code").getAsInt() == 0) {
				return Result.OK("添加成功！");
			} else {
				return Result.OK("添加失败！");
			}
		}
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "nm_device-通过id删除")
	@Operation(summary = "nm_device-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
		AppDeviceService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "nm_device-批量删除")
	@Operation(summary = "nm_device-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		this.AppDeviceService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "nm_device-通过id查询")
	@Operation(summary = "nm_device-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<AppDevice> queryById(@RequestParam(name = "id", required = true) String id) {
		AppDevice appDevice = AppDeviceService.getById(id);
		if (appDevice == null) {
			return Result.error("未找到对应数据");
		}
		if (null != appDevice.getSiteId() && !appDevice.getSiteId().isEmpty()) {
			appDevice.setSiteName(appSiteMapper.selectById(appDevice.getSiteId()).getName());
		}
		return Result.OK(appDevice);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param appDevice
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, AppDevice appDevice) {
		return super.exportXls(request, appDevice, AppDevice.class, "nm_device");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, AppDevice.class);
	}
}
