package com.agri.system.controller;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import com.agri.common.annotation.Log;
import com.agri.common.core.controller.BaseController;
import com.agri.common.core.domain.AjaxResult;
import com.agri.common.core.page.TableDataInfo;
import com.agri.common.enums.BusinessType;
import com.agri.common.utils.SecurityUtils;
import com.agri.common.utils.poi.ExcelUtil;
import com.agri.system.domain.SysAgriInfo;
import com.agri.system.domain.SysUserAgri;
import com.agri.system.service.ISysUserAgriService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.sql.Wrapper;
import java.util.List;
import java.util.Map;

/**
 * 大棚信息（用户-设备关联）Controller
 * 
 * @author lld
 * @date 2026-01-25
 */
@RestController
@RequestMapping("/assets/userAgri")
public class SysUserAgriController extends BaseController {
    @Autowired
    private ISysUserAgriService sysUserAgriService;

    /**
     * 查询大棚信息（用户-设备关联）列表
     */
    @PreAuthorize("@ss.hasPermi('assets:userAgri:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUserAgri sysUserAgri) {
        startPage();
        List<SysUserAgri> list = sysUserAgriService.selectSysUserAgriList(sysUserAgri);
        return getDataTable(list);
    }

    /**
     * 导出大棚信息（用户-设备关联）列表
     */
    @PreAuthorize("@ss.hasPermi('assets:userAgri:export')")
    @Log(title = "大棚信息（用户-设备关联）", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUserAgri sysUserAgri) {
        List<SysUserAgri> list = sysUserAgriService.selectSysUserAgriList(sysUserAgri);
        ExcelUtil<SysUserAgri> util = new ExcelUtil<SysUserAgri>(SysUserAgri.class);
        util.exportExcel(response, list, "大棚信息（用户-设备关联）数据");
    }

    /**
     * 获取大棚信息（用户-设备关联）详细信息
     */
    @PreAuthorize("@ss.hasPermi('assets:userAgri:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sysUserAgriService.selectSysUserAgriById(id));
    }

    /**
     * 新增大棚信息（用户-设备关联）
     */
    @PreAuthorize("@ss.hasPermi('assets:userAgri:add')")
    @Log(title = "大棚信息（用户-设备关联）", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysUserAgri sysUserAgri) {
        return toAjax(sysUserAgriService.save(sysUserAgri));
    }

    /**
     * 修改大棚信息（用户-设备关联）
     */
    @PreAuthorize("@ss.hasPermi('assets:userAgri:edit')")
    @Log(title = "大棚信息（用户-设备关联）", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysUserAgri sysUserAgri) {
        return toAjax(sysUserAgriService.updateSysUserAgri(sysUserAgri));
    }

    /**
     * 删除大棚信息（用户-设备关联）
     */
    @PreAuthorize("@ss.hasPermi('assets:userAgri:remove')")
    @Log(title = "大棚信息（用户-设备关联）", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysUserAgriService.deleteSysUserAgriByIds(ids));
    }


    @PreAuthorize("@ss.hasPermi('assets:userAgri:list')")
    @GetMapping("/findAgriUser")
    public TableDataInfo findAgriUser(SysUserAgri sysUserAgri) {
        startPage();
        List<SysUserAgri> list = sysUserAgriService.findAgriUser(sysUserAgri);
        return getDataTable(list);
    }
    @PreAuthorize("@ss.hasPermi('assets:userAgri:list')")
    @GetMapping("/findAllUser")
    public TableDataInfo findAllUser(SysUserAgri sysUserAgri) {
        List<SysUserAgri> list = sysUserAgriService.findAllUser(sysUserAgri);
        return getDataTable(list);
    }


    /**
     * 新增大棚信息（用户-设备关联）
     */
    @PreAuthorize("@ss.hasPermi('assets:userAgri:add')")
    @Log(title = "大棚信息（用户-设备批量关联）", businessType = BusinessType.INSERT)
    @PostMapping("/batchAssociaUser")
    public AjaxResult batchAssociaUser(@RequestBody List<SysUserAgri> userList) {
        if (CollectionUtils.isNotEmpty(userList) && !userList.isEmpty()) {
            String agriId = userList.get(0).getAgriId();
            if (ObjectUtils.isNotEmpty(agriId)) {
                QueryWrapper<SysUserAgri> wrapper = new QueryWrapper<>();
                wrapper.eq("agri_id",agriId);
                sysUserAgriService.remove(wrapper);

                boolean saveBatch = sysUserAgriService.saveBatch(userList);
                if (!saveBatch) {
                    return error("更新用户失败");
                }
            }
        }
        return success();
    }


    /**
     * 删除大棚管理
     */
    @PreAuthorize("@ss.hasPermi('assets:userAgri:remove')")
    @Log(title = "大棚管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeAgri")
    public AjaxResult removeAgri(@RequestBody SysUserAgri userAgri)
    {
        if (!SecurityUtils.isAdmin()) {
            QueryWrapper<SysUserAgri> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("agri_id", userAgri.getImei());
            queryWrapper.eq("user_id", SecurityUtils.getUserId());
            boolean remove = sysUserAgriService.remove(queryWrapper);
        }
        return success();
    }
}
