package com.limap.controller.manager;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.limap.common.core.domain.AjaxResult1;
import com.limap.common.core.domain.entity.SysUser;
import com.limap.common.core.page.PageDomain;
import com.limap.common.core.page.TableSupport;
import com.limap.common.utils.StringUtils;
import com.limap.core.basic.vo.BasicDeviceSearchVO;
import com.limap.core.screen.service.IScreenService;
import com.limap.core.screen.vo.AppEquipmentVo;
import com.limap.core.screen.vo.ControlSwitch;
import com.limap.core.screen.vo.EquipmentHistory;
import com.limap.core.screen.vo.WarnVo;
import com.limap.system.service.ISysUserService;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.limap.common.log.annotation.Log;
import io.swagger.annotations.Api;
import com.limap.common.core.controller.BaseController;
import com.limap.common.core.domain.AjaxResult;
import com.limap.common.enums.BusinessType;
import io.swagger.annotations.ApiOperation;
import com.limap.core.basic.domain.BasicUserBindInfo;
import com.limap.core.basic.service.IBasicUserBindInfoService;
import com.limap.common.utils.poi.ExcelUtil;
import com.limap.common.core.page.TableDataInfo;

/**
 * 用户设备绑定信息Controller
 *
 * @author jjb
 * @date 2025-04-11
 */
@Api(tags = "用户设备绑定信息")
@RestController
@RequestMapping("/basic/userBind")
public class BasicUserBindInfoController extends BaseController {
    @Autowired
    private IBasicUserBindInfoService basicUserBindInfoService;
    @Resource
    private IScreenService screenService;
    @Resource
    private ISysUserService userService;

    /**
     * 查询用户设备绑定信息列表
     */
    @ApiOperation("查询用户设备绑定信息列表")
    @PreAuthorize("@ss.hasPermi('basic:userBind:list')")
    @GetMapping("/list")
    public TableDataInfo list(BasicUserBindInfo basicUserBindInfo) {
        startPage();
        Long userId = getUserId();
        boolean b = getLoginUser().getUser().getRoles().stream().anyMatch(role -> role.getRoleId() == 2L || role.getRoleId() == 4L);
        basicUserBindInfo.setUserId(userId);
        if(userId == 1L || b){
            basicUserBindInfo.setUserId(null);
        }
        List<BasicUserBindInfo> list = basicUserBindInfoService.selectBasicUserBindInfoList(basicUserBindInfo);
        return getDataTable(list);
    }

    /**
     * 导出用户设备绑定信息列表
     */
    @ApiOperation("导出用户设备绑定信息列表")
    @PreAuthorize("@ss.hasPermi('basic:userBind:export')")
    @Log(title = "用户设备绑定信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BasicUserBindInfo basicUserBindInfo) {
        List<BasicUserBindInfo> list = basicUserBindInfoService.selectBasicUserBindInfoList(basicUserBindInfo);
        ExcelUtil<BasicUserBindInfo> util = new ExcelUtil<BasicUserBindInfo>(BasicUserBindInfo.class);
        util.exportExcel(response, list, "用户设备绑定信息数据");
    }

    /**
     * 获取用户设备绑定信息详细信息
     */
    @ApiOperation("获取用户设备绑定信息详细信息")
    @PreAuthorize("@ss.hasPermi('basic:userBind:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        BasicUserBindInfo byId = basicUserBindInfoService.getById(id);
        BasicUserBindInfo b = basicUserBindInfoService.selectAppUserInfo(byId);
        return success(b);
    }

    @ApiOperation("获取设备监测数据")
    @PostMapping(value = "data")
    public AjaxResult getMonitorData(@RequestBody @Valid BasicDeviceSearchVO vo) {
        Map<String, Object> map = new HashMap<>();
        BasicUserBindInfo byId = basicUserBindInfoService.getInfoByDeviceId(vo.getDeviceId());
        AppEquipmentVo equipmentById = screenService.getEquipmentByDeviceNo(byId.getDeviceName());
        if (equipmentById != null) {
            List<EquipmentHistory> equipmentHistory = screenService.getEquipmentHistory(vo.getDays(), equipmentById.getId());
            map.put("history", equipmentHistory);
        }else{
            map.put("history", Collections.emptyList());
        }
        map.put("equipment", equipmentById);

        return success(map);
    }

    @ApiOperation("获取控制器信息")
    @PostMapping(value = "control")
    @ApiResponse(code = 200,message = "获取控制器信息",response = ControlSwitch.class)
    public AjaxResult getControlData(@RequestBody @Valid BasicDeviceSearchVO vo) {
        BasicUserBindInfo byId = basicUserBindInfoService.getInfoByDeviceId(vo.getDeviceId());
        return success(basicUserBindInfoService.getcControlInfo(byId.getDeviceName()));
    }

    @ApiOperation("获取控制器信息")
    @PostMapping(value = "control1")
    public AjaxResult1<List<ControlSwitch>> getControlData1(@RequestBody @Valid BasicDeviceSearchVO vo) {
        BasicUserBindInfo byId = basicUserBindInfoService.getInfoByDeviceId(vo.getDeviceId());
        return AjaxResult1.success(basicUserBindInfoService.getcControlInfo(byId.getDeviceName()));
    }


    @ApiOperation("获取告警数据")
    @GetMapping("warn")
    public TableDataInfo getWarnList(Long deviceId){
        BasicUserBindInfo byId = basicUserBindInfoService.getInfoByDeviceId(deviceId);
        if(byId==null){
            return getDataTable(Collections.emptyList());
        }
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        List<WarnVo> list = screenService.getWarnListByDevice(byId.getDeviceId(),pageNum,pageSize);
        long total = screenService.getWarnListCountByDevice(deviceId);
        return getDataTable(list,total);
    }
    /**
     * 新增用户设备绑定信息
     */
    @ApiOperation("新增用户设备绑定信息")
    @PreAuthorize("@ss.hasPermi('basic:userBind:add')")
    @Log(title = "用户设备绑定信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BasicUserBindInfo basicUserBindInfo) {
        if(basicUserBindInfo.getUserId() == null){
            basicUserBindInfo.setUserId(getUserId());
        }else if(basicUserBindInfo.getUserName() == null){
            SysUser sysUser = userService.selectUserById(basicUserBindInfo.getUserId());
            if(sysUser == null){
                return AjaxResult.error("用户不存在,请先创建用户");
            }
            basicUserBindInfo.setUserName(sysUser.getNickName());
        }


        if(basicUserBindInfoService.count(new QueryWrapper<BasicUserBindInfo>().eq("device_name",basicUserBindInfo.getDeviceName()))>0){
            return AjaxResult.error("设备已绑定");
        }
        BasicUserBindInfo b = basicUserBindInfoService.selectAppUserInfo(basicUserBindInfo);
        if(b==null){
            b = basicUserBindInfo;
        }else{
            b.setUserId(basicUserBindInfo.getUserId());
            b.setUserName(basicUserBindInfo.getUserName());
        }
        return toAjax(basicUserBindInfoService.save(b));
    }

    /**
     * 修改用户设备绑定信息
     */
    @ApiOperation("修改用户设备绑定信息")
    @PreAuthorize("@ss.hasPermi('basic:userBind:edit')")
    @Log(title = "用户设备绑定信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BasicUserBindInfo basicUserBindInfo) {
        return toAjax(basicUserBindInfoService.updateById(basicUserBindInfo));
    }

    /**
     * 删除用户设备绑定信息
     */
    @ApiOperation("删除用户设备绑定信息")
    @PreAuthorize("@ss.hasPermi('basic:userBind:remove')")
    @Log(title = "用户设备绑定信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(basicUserBindInfoService.removeByIds(Arrays.asList(ids)));
    }



	@GetMapping("/test")
    public AjaxResult remove() throws IOException {
        FileInputStream fis = new FileInputStream("C:\\Users\\17863\\Desktop\\星途瑞销售明细(2).xlsx");
        Workbook workbook = new XSSFWorkbook(fis);
        Sheet sheet = workbook.getSheetAt(0);

        String lastCustomerName = "";
        String lastContactPerson = "";

        Iterator<Row> iterator = sheet.iterator();
        int rowIndex = 0;
        List<BasicUserBindInfo> list = new ArrayList<>();
        List<SysUser> sysUsers = userService.selectUserList(new SysUser());
        Map<String, List<SysUser>> name = sysUsers.stream().collect(Collectors.groupingBy(SysUser::getUserName));
        Map<String, List<SysUser>> nick = sysUsers.stream().collect(Collectors.groupingBy(SysUser::getNickName));

        while (iterator.hasNext()) {
            Row row = iterator.next();
            if (rowIndex++ == 0) continue; // 跳过标题行

            Cell customerCell = row.getCell(1); // 客户名称
            Cell contactCell = row.getCell(2);  // 联系人

            String customerName = getCellString(customerCell);
            String contactPerson = getCellString(contactCell);

            if (customerName.isEmpty()) {
                customerName = lastCustomerName;
            } else {
                lastCustomerName = customerName;
            }

            if (contactPerson.isEmpty()) {
                contactPerson = lastContactPerson;
            } else {
                lastContactPerson = contactPerson;
            }

            String deviceCode = getCellString(row.getCell(7));
            if(StringUtils.isNotBlank(deviceCode)){
                BasicUserBindInfo basicUserBindInfo = new BasicUserBindInfo();
                if(nick.containsKey(customerName)){
                    SysUser sysUser = nick.get(customerName).get(0);
                    basicUserBindInfo.setUserId(sysUser.getUserId());
                    basicUserBindInfo.setUserId(sysUser.getUserId());
                    basicUserBindInfo.setUserName(sysUser.getUserName());
                }else if(name.containsKey(contactPerson)){
                    SysUser sysUser = name.get(contactPerson).get(0);
                    basicUserBindInfo.setUserId(sysUser.getUserId());
                    basicUserBindInfo.setUserName(contactPerson);
                }
                basicUserBindInfo.setDeviceName(deviceCode);
                list.add(basicUserBindInfo);
            }
        }
        list.forEach(e-> {
            BasicUserBindInfo b = basicUserBindInfoService.selectAppUserInfo(e);
            if(b==null){
                b = e;
            }else{
                b.setUserId(e.getUserId());
                b.setUserName(e.getUserName());
            }
            basicUserBindInfoService.save(b);
        });

        return success();
    }


        private static String getCellString(Cell cell) {
            if (cell == null) return "";
            if (cell.getCellType() == CellType.STRING) return cell.getStringCellValue().trim();
            if (cell.getCellType() == CellType.NUMERIC) return String.valueOf((long)cell.getNumericCellValue());
            return "";
        }

}
