package com.dcsoft.system.controller;

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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.system.domain.SysPeopleRule;
import com.dcsoft.system.service.ISysConfigService;
import com.dcsoft.system.service.ISysPeopleRuleService;
import com.dcsoft.system.uniubi.service.ISysApiService;
import com.dcsoft.system.uniubi.service.ISysSdkService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
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.dcsoft.common.log.annotation.Log;
import com.dcsoft.common.log.enums.BusinessType;
import com.dcsoft.common.security.annotation.RequiresPermissions;
import com.dcsoft.system.domain.SysEquipment;
import com.dcsoft.system.service.ISysEquipmentService;
import com.dcsoft.common.core.web.controller.BaseController;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.core.utils.poi.ExcelUtil;
import com.dcsoft.common.core.web.page.TableDataInfo;

/**
 * 设备信息Controller
 *
 * @author nichun
 * @date 2023-03-08
 */
@RestController
@RequestMapping("/equipment")
public class SysEquipmentController extends BaseController
{
    @Autowired
    private ISysEquipmentService sysEquipmentService;

    @Autowired
    private ISysApiService sysApiService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysSdkService sdkService;

    @Autowired
    private ISysPeopleRuleService sysPeopleRuleService;



    /**
     * 查询设备信息列表
     */
    @RequiresPermissions("system:equipment:list")
    @GetMapping("/list")
    public TableDataInfo list(SysEquipment sysEquipment)
    {
        startPage();
        List<SysEquipment> list = sysEquipmentService.selectSysEquipmentList(sysEquipment);
        return getDataTable(list);
    }

    @GetMapping("/alllist")
    public AjaxResult alllist(SysEquipment sysEquipment)
    {
        List<SysEquipment> list = sysEquipmentService.selectSysEquipmentList(sysEquipment);
        return AjaxResult.success(list);
    }

    /**
     * 导出设备信息列表
     */
    @RequiresPermissions("system:equipment:export")
    @Log(title = "设备信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysEquipment sysEquipment)
    {
        List<SysEquipment> list = sysEquipmentService.selectSysEquipmentList(sysEquipment);
        ExcelUtil<SysEquipment> util = new ExcelUtil<SysEquipment>(SysEquipment.class);
        util.exportExcel(response, list, "设备信息数据");
    }

    /**
     * 获取设备信息详细信息
     */
    @RequiresPermissions("system:equipment:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        //判断设备是否上云
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        if("true".equals(cloud)){
            //获取设备配置参数
            SysEquipment equipment=sysEquipmentService.selectSysEquipmentById(id);
            if(StringUtils.isEmpty(equipment.getFaceEnable())){
                String datas=sysApiService.deviceSettingQuery(equipment);
                JSONObject jsons= JSONObject.parseObject(datas);
                if("1".equals(jsons.get("result")+"")) {
                    JSONArray objs= (JSONArray) jsons.get("data");
                    Map map = JSON.parseObject(JSON.toJSONString(equipment), Map.class);
                    for(int i=0;i<objs.size();i++){
                        JSONObject obj= (JSONObject) objs.get(i);
                        map.put((String) obj.get("key"),obj.get("value"));
                    }
                    String toJSON = JSONObject.toJSONString(map);
                    equipment = JSONObject.toJavaObject(JSON.parseObject(toJSON), SysEquipment.class);
                }
                sysEquipmentService.updateSysEquipment(equipment);
            }
        }
        return success(sysEquipmentService.selectSysEquipmentById(id));
    }

    /**
     * 新增设备信息
     */
    @RequiresPermissions("system:equipment:add")
    @Log(title = "设备信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysEquipment sysEquipment)
    {
        //判断设备是否上云
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        if("true".equals(cloud)){
            String data=sysApiService.deviceCreate(sysEquipment);
            JSONObject json= JSONObject.parseObject(data);
            if("1".equals(json.get("result")+"")){
                sysEquipment.setState(1L);//对接成功
            }else{
                return error(json.get("msg")+"");
            }
        }else{
            if(StringUtils.isNotEmpty(sysEquipment.getBackUrl())){
                sdkService.setIdentifyCallBack(sysEquipment.getBackUrl(),sysEquipment.getIp(),sysEquipment.getPassword());
                //sdkService.setQRCodeCallback(sysEquipment.getBackUrl(),sysEquipment.getIp(),sysEquipment.getPassword());
                sdkService.setDeviceHeartBeat(sysEquipment.getBackUrl(),sysEquipment.getIp(),sysEquipment.getPassword());
            }
            sysEquipment.setState(1L);//对接成功
        }
        int i = sysEquipmentService.insertSysEquipment(sysEquipment);
        if(!CollectionUtils.isEmpty(sysEquipment.getFileList())) {
            sysEquipmentService.saveFile(sysEquipment);
        }
        return toAjax(i);
    }

    /**
     * 修改设备信息
     */
    @RequiresPermissions("system:equipment:edit")
    @Log(title = "设备信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysEquipment sysEquipment)
    {
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        if("true".equals(cloud)) {
            Long id = sysEquipment.getId();
            if (StringUtils.isEmpty(sysEquipment.getHandle())) {
                String data = sysApiService.deviceUpdate(sysEquipment);
                JSONObject json = JSONObject.parseObject(data);
                if (!"1".equals(json.get("result") + "")) {
                    return error(json.get("msg") + "");
                } else {
                    return toAjax(sysEquipmentService.updateSysEquipment(sysEquipment));
                }
            } else {
                //设备信息-远程配置设备参数
                String datas = sysApiService.deviceSettingUpdate(sysEquipment);
                JSONObject jsons = JSONObject.parseObject(datas);
                if (!"1".equals(jsons.get("result") + "")) {
                    return error(jsons.get("msg") + "");
                } else {
                    sysEquipment = sysEquipmentService.selectSysEquipmentById(id);
                    //获取设备配置参数
                    String datas1 = sysApiService.deviceSettingQuery(sysEquipment);
                    JSONObject jsons1 = JSONObject.parseObject(datas1);
                    if ("1".equals(jsons1.get("result") + "")) {
                        JSONArray objs = (JSONArray) jsons1.get("data");
                        Map map = JSON.parseObject(JSON.toJSONString(sysEquipment), Map.class);
                        for (int i = 0; i < objs.size(); i++) {
                            JSONObject obj = (JSONObject) objs.get(i);
                            map.put((String) obj.get("key"), obj.get("value"));
                        }
                        String toJSON = JSONObject.toJSONString(map);
                        sysEquipment = JSONObject.toJavaObject(JSON.parseObject(toJSON), SysEquipment.class);

                    }
                    return toAjax(sysEquipmentService.updateSysEquipment(sysEquipment));
                }
            }
        }else{
            if(StringUtils.isNotEmpty(sysEquipment.getBackUrl())){
                sdkService.setIdentifyCallBack(sysEquipment.getBackUrl(),sysEquipment.getIp(),sysEquipment.getPassword());
                //sdkService.setQRCodeCallback(sysEquipment.getBackUrl(),sysEquipment.getIp(),sysEquipment.getPassword());
                sdkService.setDeviceHeartBeat(sysEquipment.getBackUrl(),sysEquipment.getIp(),sysEquipment.getPassword());
            }

            sysEquipmentService.saveFile(sysEquipment);

            return toAjax(sysEquipmentService.updateSysEquipment(sysEquipment));
        }
    }


    /**
     * 删除设备信息
     */
    @RequiresPermissions("system:equipment:remove")
    @Log(title = "设备信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        if("true".equals(cloud)) {
            for (Long id : ids) {
                SysEquipment equipment = sysEquipmentService.selectSysEquipmentById(id);
                sysApiService.deviceDelete(equipment);
            }
        }
        return toAjax(sysEquipmentService.deleteSysEquipmentByIds(ids));
    }

    /**
     * 设备控制
     */
    @GetMapping("/command/{id}/{type}")
    public AjaxResult command(@PathVariable Long id, @PathVariable Integer type) {
        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        SysEquipment equipment=sysEquipmentService.selectSysEquipmentById(id);
        if("true".equals(cloud)) {
            String data =sysApiService.deviceCommand(equipment,type);
            JSONObject jsons= JSONObject.parseObject(data);
            if(!"1".equals(jsons.get("result")+"")) {
                return error(jsons.get("msg")+"");
            }
        }else{
            String data="";
            if(type==1){//重启
                 data =sdkService.restartDevice(equipment.getIp(),equipment.getPassword());
            }else{//重置
                 data =sdkService.resetDevice(equipment.getIp(),equipment.getPassword());
            }
            JSONObject jsons= JSONObject.parseObject(data);
            if(!"1".equals(jsons.get("result")+"")) {
                return error(jsons.get("msg")+"");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 设备控制
     */
    @GetMapping("/interactive/{id}")
    public AjaxResult interactive(@PathVariable Long id) {

        String cloud = configService.selectConfigByKey("sys.equipment.cloud");
        SysEquipment equipment=sysEquipmentService.selectSysEquipmentById(id);
        if("true".equals(cloud)) {
            String data =sysApiService.deviceInteractive(equipment);
            JSONObject jsons= JSONObject.parseObject(data);
            if(!"1".equals(jsons.get("result")+"")) {
                return error(jsons.get("msg")+"");
            }
        }else{
            String data =sdkService.openDoorControl(equipment.getIp(),equipment.getPassword());
            JSONObject jsons= JSONObject.parseObject(data);
            if(!"1".equals(jsons.get("result")+"")) {
                return error(jsons.get("msg")+"");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 获取设备信息详细信息
     */
    @GetMapping(value = "/empty/{id}")
    public AjaxResult empty(@PathVariable("id") Long id)
    {
        //判断设备是否上云
        SysEquipment equipment=sysEquipmentService.selectSysEquipmentById(id);
        sdkService.personDelete("-1",equipment.getIp(),equipment.getPassword());
        return success(equipment);
    }

    /**
     * 获取设备信息详细信息
     */
    @GetMapping(value = "/recover/{id}")
    public AjaxResult recover(@PathVariable("id") Long id)
    {
        //判断设备是否上云
        //查询已经受过这设备的权限人员放入到关联表中
        List<Map<String,Object>> list=sysEquipmentService.selectSysEquipmentPeopleById(id);
        for(Map<String,Object> obj:list){
            Long peopleId=Long.parseLong(obj.get("people_id")+"");
            SysPeopleRule sysPeopleRule=new SysPeopleRule();
            sysPeopleRule.setPeopleId(peopleId);
            sysPeopleRule.setEquipmentId(id);
            sysPeopleRuleService.insertSysPeopleRule(sysPeopleRule);
        }
        return success(list);
    }

    /**
     * 根据设备序列号查询设备信息
     * @param sysEquipment
     * @return
     */
    @PostMapping(value = "/queryEquipmentByDeviceKey")
    public AjaxResult queryEquipmentByDeviceKey(@RequestBody SysEquipment sysEquipment) {
        return success(sysEquipmentService.queryEquipmentByDeviceKey(sysEquipment));
    }

    /**
     * 根据设备序列号修改设备密码
     * @param sysEquipment
     * @return
     */
    @PostMapping(value = "/updateEquipmentByDeviceKey")
    public AjaxResult updateEquipmentByDeviceKey(@RequestBody SysEquipment sysEquipment) {
        sysEquipmentService.updateEquipmentByDeviceKey(sysEquipment);
        return success();
    }

    /**
     * 根据设备序列号修改设备轮播文件
     * @param sysEquipment
     * @return
     */
    @PostMapping(value = "/updateEquipmentFile")
    public AjaxResult updateEquipmentFile(@RequestBody SysEquipment sysEquipment) {
        sysEquipmentService.updateEquipmentFile(sysEquipment);
        return success();
    }

}
