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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
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.basic.model.BasicSetEntity;
import com.mortals.xhx.module.basic.model.BasicSetQuery;
import com.mortals.xhx.module.basic.service.BasicSetService;
import com.mortals.xhx.module.device.model.*;
import com.mortals.xhx.module.device.service.DeviceFileService;
import com.mortals.xhx.module.device.service.DeviceService;
import com.mortals.xhx.module.device.service.DeviceWorkmanService;
import com.mortals.xhx.module.workman.model.WorkmanEntity;
import com.mortals.xhx.module.workman.model.WorkmanQuery;
import com.mortals.xhx.module.workman.service.WorkmanService;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备
 *
 * @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;
    @Value("${token.loginName:'admin'}")
    private String loginName;
    @Value("${token.password:'admin'}")
    private String password;
    @Autowired
    private WorkmanService workmanService;
    @Autowired
    private DeviceFileService deviceFileService;
    @Autowired
    private DeviceWorkmanService deviceWorkmanService;
    @Autowired
    private BasicSetService basicSetService;

    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());

        this.addDict(model, "workmanId", workmanService.find(new WorkmanQuery()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getName(), (o, n) -> n)));

        super.init(model, context);
    }

    @Override
    protected int editAfter(Long id, Map<String, Object> model, DeviceEntity entity, Context context) throws AppException {

        List<DeviceFileEntity> deviceFileEntities = deviceFileService.find(new DeviceFileQuery().deviceId(entity.getId()));
        if (!ObjectUtils.isEmpty(deviceFileEntities)) {
            entity.setDeviceFileEntityList(deviceFileEntities);
        }

        List<DeviceWorkmanEntity> deviceWorkmanEntityList = deviceWorkmanService.find(new DeviceWorkmanQuery().deviceId(entity.getId()));
        if (!ObjectUtils.isEmpty(deviceWorkmanEntityList)) {
            entity.setDeviceWorkmanEntityList(deviceWorkmanEntityList);
        }

        return super.editAfter(id, model, entity, context);
    }

    /**
     * 设备获取信息
     */
    @PostMapping(value = "infoByCode")
    @UnAuth
    public Rest<DeviceEntity> deviceInfoByCode(@RequestBody DeviceEntity deviceEntity) {
        log.info("设备信息获取：{}", deviceEntity.getDeviceCode());
        String busiDesc = this.getModuleDesc() + "设备信息获取";
        Rest<DeviceEntity> rest = Rest.ok(busiDesc + " 【成功】");
        if (ObjectUtils.isEmpty(deviceEntity.getDeviceCode())) throw new AppException("设备编码不能为空");
        try {
            rest = this.service.deviceInfoByCode(deviceEntity.getDeviceCode(), getContext());
            if (rest.getCode() != 1) {
                throw new AppException(rest.getMsg());
            }

            BasicSetEntity basicSetEntity = basicSetService.selectOne(new BasicSetQuery());
            if (!ObjectUtils.isEmpty(basicSetEntity)) {
                rest.getData().setPlayTime(basicSetEntity.getPlayTime());
                rest.getData().setLookUp(basicSetEntity.getLookUp());
            }

            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error("设备信息获取", e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }


    /**
     * 设备激活
     */
    @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())) {
            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;
    }

}