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

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.feign.AmosFeignService;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.cylinder.biz.utils.BeanDtoVoUtils;
import com.yeejoin.amos.boot.module.cylinder.api.dto.UseUnitDto;
import com.yeejoin.amos.boot.module.cylinder.api.entity.Elevator;
import com.yeejoin.amos.boot.module.cylinder.api.entity.UseUnit;
import com.yeejoin.amos.boot.module.cylinder.api.service.IUseUnitService;
import com.yeejoin.amos.boot.module.cylinder.api.dto.DutyPersonDto;
import com.yeejoin.amos.boot.module.cylinder.biz.service.impl.ElevatorServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
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;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//import com.yeejoin.amos.boot.module.cylinder.api.service.EquipFeignService;


/**
 * 使用单位
 *
 * @author tb
 * @date 2021-06-01
 */
@RestController
@Api(tags = "使用单位Api")
@RequestMapping(value = "/use-unit")
public class UseUnitController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(UseUnitController.class);

    @Autowired
    IUseUnitService iUseUnitService;

    @Autowired
    EquipFeignClient equipFeignClient;

    @Autowired
    AmosFeignService amosFeignService;

    @Autowired
    ElevatorServiceImpl elevatorServiceImpl;

    /**
     * 新增使用单位
     *
     * @param useUnit 使用单位
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增使用单位", notes = "新增使用单位")
    public ResponseModel<Boolean> saveUseUnit(@RequestBody UseUnit useUnit) {
        boolean save = iUseUnitService.save(useUnit);
        return ResponseHelper.buildResponse(save);
    }

    /**
     * 根据id删除
     *
     * @param id id
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public ResponseModel<Boolean> deleteById(@PathVariable Long id) {
        boolean remove = iUseUnitService.removeById(id);
        return ResponseHelper.buildResponse(remove);
    }

    /**
     * 修改使用单位
     *
     * @param useUnit 使用单位
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "修改使用单位", notes = "修改使用单位")
    public ResponseModel<Boolean> updateByIdUseUnit(@RequestBody UseUnit useUnit) {
        boolean update = iUseUnitService.updateById(useUnit);
        return ResponseHelper.buildResponse(update);
    }

    /**
     * 获取消防建筑树
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/buildingTree", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取消防建筑树", notes = "获取消防建筑树")
    public ResponseModel<Object> getBuildingTreeAndEquip() {
        return equipFeignClient.getBuildingTreeAndEquip();
    }

    /**
     * 根据id查询
     *
     * @param id id
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public ResponseModel<UseUnitDto> selectById(@PathVariable Long id) {
        UseUnit useUnit = iUseUnitService.getById(id);
        UseUnitDto useUnitDto = BeanDtoVoUtils.convert(useUnit, UseUnitDto.class);
        return ResponseHelper.buildResponse(useUnitDto);
    }

    /**
     * 获取平台字典
     *
     * @param dictCode 字典编号
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/dict/{dictCode}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取平台字典", notes = "获取平台字典")
    public ResponseModel<Object> getDict(@PathVariable(value = "dictCode") String dictCode) {
        ResponseModel<Object> result = new ResponseModel<>();
        try {
            result = ResponseHelper.buildResponse(amosFeignService.listDictionaryByDictCode(dictCode));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 列表分页查询
     *
     * @param pageNum  页码
     * @param pageSize 每页大小
     * @param useUnit  查询参数
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public ResponseModel<IPage<UseUnit>> listPage(String pageNum, String pageSize, UseUnit useUnit) {

        Page<UseUnit> pageBean;
        QueryWrapper<UseUnit> useUnitQueryWrapper = new QueryWrapper<>();
        Class<? extends UseUnit> aClass = useUnit.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(useUnit);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(useUnit);
                        useUnitQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(useUnit);
                        useUnitQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(useUnit);
                        useUnitQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) field.get(useUnit);
                        useUnitQueryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        });
        IPage<UseUnit> 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 = iUseUnitService.page(pageBean, useUnitQueryWrapper);
        return ResponseHelper.buildResponse(page);
    }

    /**
     * 根据警情id 查找设备使用单位信息
     * @param alertId
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/alert/{alertId}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据警情id 查找设备使用单位信息", notes = "根据警情id 查找设备使用单位信息")
    public ResponseModel<UseUnitDto> selectByAlertId(@PathVariable Long alertId) {
        // 获取根据警情获取电梯信息
        Elevator elevator  = elevatorServiceImpl.selectByAlertId(alertId);
        // 根据设备使用单位id 获取使用单位信息
        UseUnit useUnit = iUseUnitService.getById(elevator.getUseUnitId());
        if (ValidationUtil.isEmpty(useUnit)) {
            throw new BadRequest("使用单位未找到");
        }
        UseUnitDto useUnitVo = BeanDtoVoUtils.convert(useUnit, UseUnitDto.class);
        List<DutyPersonDto> dutyPersonList = new ArrayList<DutyPersonDto>();
        DutyPersonDto principal = new DutyPersonDto();
        principal.setDeptName("主要负责人");
        principal.setPhone(useUnitVo.getPrincipalPhone());
        principal.setUserId(useUnitVo.getPrincipalId()+"");
        principal.setUserName(useUnitVo.getPrincipal());
        dutyPersonList.add(principal);
        DutyPersonDto manager = new DutyPersonDto();
        manager.setDeptName("电梯安全管理员");
        manager.setPhone(useUnitVo.getManagerPhone());
        manager.setUserId(useUnitVo.getManagerId()+"");
        manager.setUserName(useUnitVo.getManager());
        dutyPersonList.add(manager);
        useUnitVo.setDutyPersonList(dutyPersonList);
        return ResponseHelper.buildResponse(useUnitVo);
    }
}

