package com.dcsoft.system.controller;

import cn.hutool.core.util.ObjectUtil;
import com.dcsoft.common.core.utils.CollUtil;
import com.dcsoft.common.core.web.controller.BaseController;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.core.web.page.TableDataInfo;
import com.dcsoft.common.log.annotation.Log;
import com.dcsoft.common.log.enums.BusinessType;
import com.dcsoft.common.security.annotation.RequiresPermissions;
import com.dcsoft.system.domain.SysEqDownRecord;
import com.dcsoft.system.domain.SysPeopleEqDown;
import com.dcsoft.system.service.ISysEqDownRecordService;
import com.dcsoft.system.uniubi.service.ISysSdkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/sysEqDownRecord")
@Slf4j
public class SysEqDownRecordController extends BaseController {

    @Autowired
    private ISysEqDownRecordService sysEqDownRecordService;

    @Autowired
    protected ISysSdkService sdkService;

    /**
     * 分页查询设备下机记录列表
     */
    @RequiresPermissions("system:eqDown:list")
    @GetMapping("/pageList")
    public TableDataInfo pageList(SysEqDownRecord sysEqDownRecord) {
        List<SysEqDownRecord> list = sysEqDownRecordService.pageList(sysEqDownRecord);
        return getDataTable(list);
    }

    /**
     *
     */
    @RequiresPermissions("system:eqDown:down")
    @Log(title = "人员重新下发", businessType = BusinessType.UPDATE)
    @PostMapping("/down")
    public AjaxResult down(@RequestBody List<Long> ids) {
        List<Long> failIds = new ArrayList<>();
        List<SysEqDownRecord> downRecordList = new ArrayList<>();
        List<SysPeopleEqDown> list = sysEqDownRecordService.selectListByIds(ids,null);
        for (SysPeopleEqDown sysPeopleEqDown : list) {
            SysEqDownRecord sysEqDownRecord = sdkService.authDeviceDown(sysPeopleEqDown);
            downRecordList.add(sysEqDownRecord);
            if (ObjectUtil.isNotNull(sysEqDownRecord) && sysEqDownRecord.getDownResult() == 1) {
                failIds.add(sysPeopleEqDown.getId());
            }
        }

        //保存下发记录
        if (CollUtil.isNotEmpty(downRecordList)) {
            sysEqDownRecordService.saveBatch(downRecordList);
        }

        if (CollUtil.isNotEmpty(failIds)) {
            return AjaxResult.error("下发失败的ID：" + failIds);
        }

        return AjaxResult.success();
    }


}
