package com.mortals.xhx.module.device.web;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.DeviceMethodEnum;
import com.mortals.xhx.common.code.EnabledEnum;
import com.mortals.xhx.common.pdu.LoginForm;
import com.mortals.xhx.common.pdu.device.DeviceReq;
import com.mortals.xhx.feign.device.IDeviceFeign;
import com.mortals.xhx.module.device.model.DeviceQuery;
import com.mortals.xhx.module.room.model.RoomQuery;
import com.mortals.xhx.module.room.service.RoomService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.model.Context;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.service.DeviceService;
import org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import static com.mortals.framework.ap.SysConstains.*;
/**
*
* 设备管理
*
* @author zxfei
* @date 2023-05-22
*/
@RestController
@RequestMapping("device")
@Slf4j
public class DeviceController extends BaseCRUDJsonBodyMappingController<DeviceService,DeviceEntity,Long> {

    @Autowired
    private ParamService paramService;

    @Autowired
    private RoomService roomService;

    @Autowired
    private IDeviceFeign deviceFeign;
    @Value("${token.loginName:'admin'}")
    private String loginName;
    @Value("${token.password:'admin'}")
    private String password;

    public DeviceController(){
        super.setModuleDesc( "设备管理");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "resolution", paramService.getParamBySecondOrganize("Device","resolution"));
        this.addDict(model, "deviceInBuilding", paramService.getParamBySecondOrganize("Device","deviceInBuilding"));
        this.addDict(model, "deviceInFloor", paramService.getParamBySecondOrganize("Device","deviceInFloor"));
        this.addDict(model, "deviceStatus", paramService.getParamBySecondOrganize("Device","deviceStatus"));
        this.addDict(model, "enabled", paramService.getParamBySecondOrganize("Device","enabled"));

        DeviceEntity entity = (DeviceEntity)model.get("entity");
        if(!ObjectUtils.isEmpty(entity)&&entity.newEntity()){
            Set<Long> roomSet = this.service.find(new DeviceQuery()).stream().map(item -> item.getRoomId()).collect(Collectors.toSet());
            //排除已经有设备的房间
            Map<String, String> roomMap = roomService.find(new RoomQuery()).stream().filter(f->roomSet.contains(f.getId())).collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getRoomName(), (o, n) -> n));
            this.addDict(model, "roomId", roomMap);
        }else{
            Map<String, String> roomMap = roomService.find(new RoomQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getRoomName(), (o, n) -> n));
            this.addDict(model, "roomId", roomMap);
        }
        super.init(model, context);
    }

    /**
     * 设备激活
     */
    @PostMapping(value = "active")
    public Rest<Void> deviceActive(@RequestBody DeviceEntity deviceEntity) {
        log.info("设备激活：{}", deviceEntity.getDeviceCode());
        String busiDesc = this.getModuleDesc() + "设备激活";
        Rest<Void> rest = Rest.ok(busiDesc + " 【成功】");
        try {
            this.service.active(deviceEntity.getDeviceCode(), getContext());
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error("设备激活消息", e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }

    /**
     * 设备启用停用
     */
    @PostMapping(value = "enable")
    public String deviceEnable(@RequestBody DeviceEntity deviceEntity) {
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> model = new HashMap<>();
        String busiDesc = this.getModuleDesc() + "设备";
        try {
            this.service.deviceEnabled(deviceEntity.getId(), deviceEntity.getEnabled(), getContext());
            recordSysLog(request, busiDesc + EnabledEnum.getByValue(deviceEntity.getEnabled()).getDesc() + " 【成功】");
            jsonObject.put(KEY_RESULT_DATA, model);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
        } catch (Exception e) {
            log.error("设备启用停用消息", e);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            jsonObject.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return jsonObject.toJSONString();
    }

    @Override
    protected int saveAfter(DeviceEntity entity, Map<String, Object> model, Context context) throws AppException {
        if(ObjectUtils.isEmpty(entity.getUpdateTime())){
            String token = getToken();
            DeviceReq deviceReq = new DeviceReq();
            deviceReq.setReceiveMethod(DeviceMethodEnum.ADD.getValue());
            deviceReq.setDeviceName(entity.getDeviceName());
            deviceReq.setDeviceCode(entity.getDeviceCode());
            deviceReq.setProductCode(entity.getProductCode());
            deviceReq.setIp(entity.getIp());
            deviceReq.setPort(entity.getPort());
            deviceReq.setSiteId(1L);
            deviceReq.setSiteCode("511500000000-0001");
            deviceReq.setSiteName("宜宾市民中心");
            deviceReq.setLeadingOfficial(entity.getLeadingOfficial());
            deviceReq.setLeadingOfficialTelephone(entity.getLeadingOfficialTelephone());
            deviceReq.setSource(1);
            deviceReq.setDeviceStatus(entity.getDeviceStatus());
            Rest<String> rest = deviceFeign.deviceCall(deviceReq, token);
            log.info("添加结果：{}", JSON.toJSONString(rest));
        }else{
            String token = getToken();
            DeviceReq deviceReq = new DeviceReq();
            deviceReq.setReceiveMethod(DeviceMethodEnum.UPDATE.getValue());
            deviceReq.setDeviceName(entity.getDeviceName());
            deviceReq.setDeviceCode(entity.getDeviceCode());
            deviceReq.setProductCode(entity.getProductCode());
            deviceReq.setIp(entity.getIp());
            deviceReq.setPort(entity.getPort());
            deviceReq.setSiteId(1L);
            deviceReq.setSiteCode("511500000000-0001");
            deviceReq.setSiteName("宜宾市民中心");
            deviceReq.setLeadingOfficial(entity.getLeadingOfficial());
            deviceReq.setLeadingOfficialTelephone(entity.getLeadingOfficialTelephone());
            deviceReq.setSource(1);
            deviceReq.setDeviceStatus(entity.getDeviceStatus());
            Rest<String> rest = deviceFeign.deviceCall(deviceReq, token);
            log.info("更新结果：{}", JSON.toJSONString(rest));
        }

        return super.saveAfter(entity, model, context);
    }

    @Override
    protected void deleteBefore(Long[] ids, Context context) throws AppException {
        super.deleteBefore(ids, context);
        String token = getToken();
        DeviceQuery deviceQuery = new DeviceQuery();
        deviceQuery.setIdList(Arrays.asList(ids));
        List<DeviceEntity> deviceEntities = this.service.find(deviceQuery, context);
        for (DeviceEntity entity : deviceEntities) {
            DeviceReq deviceReq = new DeviceReq();
            deviceReq.setReceiveMethod(DeviceMethodEnum.DEL.getValue());
            deviceReq.setDeviceCode(entity.getDeviceCode());
            Rest<String> rest = deviceFeign.deviceCall(deviceReq, token);
            log.info("删除结果：{}", JSON.toJSONString(rest));
        }


    }

    private String getToken() {
        LoginForm loginForm = new LoginForm();
        loginForm.setLoginName(loginName);
        loginForm.setPassword(password);
        Rest<String> rest = deviceFeign.getToken(loginForm);
        String token = rest.getData();
        return token;
    }
}