package com.supervision.web.peopleGateManage.Controller;

import com.supervision.web.peopleGateManage.Service.DeviceService;
import com.supervision.web.peopleGateManage.Service.PeopleDeviceService;
import com.supervision.web.peopleGateManage.Service.PeopleInfoService;
import com.supervision.web.peopleGateManage.enity.Device;
import com.supervision.web.peopleGateManage.enity.DeviceAddRequest;
import com.supervision.web.peopleGateManage.enity.PeopleInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/device")
public class DeviceManageController {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private PeopleInfoService peopleInfoService;

    @Autowired
    private PeopleDeviceService peopleDeviceService;

    /**
     * 获取所有设备
     */
    @GetMapping("/list")
    public List<Device> listDevices() {
        return deviceService.getAll();
    }

    /**
     * 新增设备（支持从指定设备或所有设备同步人员信息）
     */
    @PostMapping("/add")
    public String addDevice(@RequestBody DeviceAddRequest request) {
        // 1. 保存新设备
        Device device = new Device();
        device.setModel(request.getModel());
        device.setLocation(request.getLocation());
        device.setIp(request.getIp());
        device.setPort(request.getPort());
        device.setAccount(request.getAccount());
        device.setPassword(request.getPassword());
        deviceService.add(device);

        // 2. 同步逻辑
        if (request.getSyncMode() != null) {
            if (request.getSyncMode() == 1) {
                // 同步所有人员
                List<PeopleInfo> allPeople = peopleInfoService.getAll();
                for (PeopleInfo p : allPeople) {
                    peopleDeviceService.bindPersonToDevice(p.getPersonId(), device.getId());
                }
            } else if (request.getSyncMode() == 2 && request.getSyncFromDeviceId() != null) {
                // 从指定设备同步
                List<String> personIds = peopleDeviceService.getPersonsByDevice(request.getSyncFromDeviceId());
                for (String personId : personIds) {
                    peopleDeviceService.bindPersonToDevice(personId, device.getId());
                }
            }
        }

        return "success";
    }

    /**
     * 修改设备
     */
    @PutMapping("/update")
    public String updateDevice(@RequestBody Device device) {
        deviceService.update(device);
        return "success";
    }

    /**
     * 删除设备
     */
    @DeleteMapping("/delete/{id}")
    public String deleteDevice(@PathVariable Long id) {
        deviceService.delete(id);
        return "success";
    }

    /**
     * 查看单个设备详情
     */
    @GetMapping("/get/{id}")
    public Device getDevice(@PathVariable Long id) {
        return deviceService.getById(id);
    }
}

