package com.mortals.xhx.module.device.web;

import com.alibaba.fastjson.JSON;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.DataUtil;
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.code.YesNoEnum;
import com.mortals.xhx.common.pdu.LoginForm;
import com.mortals.xhx.common.pdu.RespData;
import com.mortals.xhx.common.pdu.device.DeviceReq;
import com.mortals.xhx.common.pdu.firm.FirmPdu;
import com.mortals.xhx.feign.base.pdu.SitePdu;
import com.mortals.xhx.feign.device.IDeviceFeign;
import com.mortals.xhx.feign.firm.IFirmFeign;
import com.mortals.xhx.feign.rsp.ApiResp;
import com.mortals.xhx.module.device.model.DeviceQuery;
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-02-25
 */
@RestController
@RequestMapping("device")
@Slf4j
public class DeviceController extends BaseCRUDJsonBodyMappingController<DeviceService, DeviceEntity, Long> {

    @Autowired
    private ParamService paramService;

    @Autowired
    private IDeviceFeign deviceFeign;
    @Autowired
    private IFirmFeign firmFeign;
    @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, "deviceSrc", paramService.getParamBySecondOrganize("Device", "deviceSrc"));
        this.addDict(model, "deviceStatus", paramService.getParamBySecondOrganize("Device", "deviceStatus"));
        this.addDict(model, "source", paramService.getParamBySecondOrganize("Device", "source"));
        this.addDict(model, "enabled", EnabledEnum.getEnumMap());

        Rest<RespData<List<FirmPdu>>> restList = firmFeign.list(new FirmPdu());
        if (restList.getCode() == YesNoEnum.YES.getValue()) {
            Map<String, String> firmMap = restList.getData().getData().stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getFirmName(), (o, n) -> n));
            this.addDict(model, "deviceFirmId", firmMap);
        } else {
            this.addDict(model, "deviceFirmId", new JSONObject());
        }
        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();
    }


    /**
     * 检测设备状态
     */
    @PostMapping(value = "check")
    @UnAuth
    public String deviceCheck(@RequestBody DeviceEntity deviceEntity) {
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> model = new HashMap<>();
        String busiDesc = this.getModuleDesc() + "设备";
        try {
            DeviceEntity entity = this.service.getExtCache(deviceEntity.getDeviceCode());
            jsonObject.put(KEY_RESULT_DATA, entity);
            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())) {
            DeviceReq deviceReq = new DeviceReq();
            deviceReq.setReceiveMethod(DeviceMethodEnum.UPDATE.getValue());
            deviceReq.setIp(entity.getIp());
            deviceReq.setPort(entity.getPort());
            deviceReq.setLeadingOfficial(entity.getLeadingOfficial());
            deviceReq.setLeadingOfficialTelephone(entity.getLeadingOfficialTelephone());
            deviceReq.setSource(1);
            deviceReq.setDeviceStatus(entity.getDeviceStatus());
            Rest<String> rest = deviceFeign.deviceCall(deviceReq);
            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);
            log.info("删除结果：{}", JSON.toJSONString(rest));
        }
    }



    @PostMapping({"matter/list"})
    public Rest<Object> list() {

        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        String busiDesc = "查询第设备事项列表";

        int code = 1;
        try {

            model.put("message_info", busiDesc + "成功");
            this.recordSysLog(this.request, busiDesc + " 【成功】");
        } catch (Exception e) {
            code = VALUE_RESULT_FAILURE;
            this.doException(this.request, busiDesc, model, e);
        }

        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }
}