package com.yeejoin.amos.boot.module.jcs.biz.controller;

import java.util.Arrays;
import java.util.Objects;

import com.yeejoin.amos.boot.module.common.biz.service.impl.SourceFileServiceImpl;
import com.yeejoin.amos.boot.module.jcs.api.entity.JcSituationDetail;
import com.yeejoin.amos.boot.module.jcs.api.mapper.JcSituationDetailMapper;
import com.yeejoin.amos.component.rule.config.RuleConfig;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.module.jcs.api.entity.PowerTransferCompany;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.PowerTransferCompanyServiceImpl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;


/**
 * 调派单位
 *
 * @author tb
 * @date 2021-06-17
 */
@RestController
@Api(tags = "调派单位Api")
@RequestMapping(value = "/power-transfer-company")
public class PowerTransferCompanyController extends BaseController {

    @Autowired
    PowerTransferCompanyServiceImpl powerTransferCompanyService;

    @Autowired
    SourceFileServiceImpl sourceFileService;

    @Autowired
    JcSituationDetailMapper jcSituationDetailMapper;

    @Autowired
    private EmqKeeper emqKeeper;

    @Value("${mqtt.topic.command.power.deployment}")
    private String topic;

    /**
     * 新增调派单位
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增调派单位", notes = "新增调派单位")
    public boolean savePowerTransferCompany(@RequestBody PowerTransferCompany powerTransferCompany) {
        return powerTransferCompanyService.save(powerTransferCompany);
    }

    /**
     * 根据id删除
     *
     * @param id id
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public boolean deleteById(@PathVariable Long id) {
        return powerTransferCompanyService.removeById(id);
    }


    /**
     * 修改调派单位
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "修改调派单位", notes = "修改调派单位")
    public boolean updateByIdPowerTransferCompany(@RequestBody PowerTransferCompany powerTransferCompany) {
        return powerTransferCompanyService.updateById(powerTransferCompany);
    }


    /**
     * 根据id查询
     *
     * @param id id
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public PowerTransferCompany selectById(@PathVariable Long id) {
        return powerTransferCompanyService.getById(id);
    }


    /**
     * 列表分页查询
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public IPage<PowerTransferCompany> listPage(String pageNum, String pageSize,
                                                PowerTransferCompany powerTransferCompany) {

        Page<PowerTransferCompany> pageBean;
        QueryWrapper<PowerTransferCompany> powerTransferCompanyQueryWrapper = new QueryWrapper<>();
        Class<? extends PowerTransferCompany> aClass = powerTransferCompany.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(powerTransferCompany);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(powerTransferCompany);
                        powerTransferCompanyQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(powerTransferCompany);
                        powerTransferCompanyQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(powerTransferCompany);
                        powerTransferCompanyQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) field.get(powerTransferCompany);
                        powerTransferCompanyQueryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException("系统异常");
            }
        });
        IPage<PowerTransferCompany> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = powerTransferCompanyService.page(pageBean, powerTransferCompanyQueryWrapper);
        return page;
    }

    /**
     * 新增文字信息图片信息
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/jcSituationDetail/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增文字信息图片信息", notes = "新增文字信息图片信息")
    public ResponseModel<Boolean> saveJcSituationDetail(@RequestBody JcSituationDetail jcSituationDetail) throws MqttException {
        if (Objects.isNull(jcSituationDetail.getAlertCalledId())) {
            throw new BadRequest("警情ID不能为空");
        }
        jcSituationDetailMapper.insert(jcSituationDetail);
//        if (ObjectUtils.isNotEmpty(jcSituationDetail.getAttachments())) {
//            sourceFileService.saveAttachments(jcSituationDetail.getSequenceNbr(), jcSituationDetail.getAttachments());
//        }

        // 自定义指令信息消息推送
        // 定义指令信息消息推送 页面发送mqtt 默认发送 String 类型 0, 新警情 1 警情状态变化
        emqKeeper.getMqttClient().publish(topic, "0".getBytes(), RuleConfig.DEFAULT_QOS, false);
        return ResponseHelper.buildResponse(Boolean.TRUE);
    }

}

