package com.yeejoin.amos.boot.module.jczs.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.utils.NameUtils;
import com.yeejoin.amos.boot.module.jczs.biz.service.impl.ElevatorServiceImpl;
import com.yeejoin.amos.boot.module.jczs.api.dto.DutyPersonDto;
import com.yeejoin.amos.boot.module.jczs.api.dto.MaintenanceUnitDto;
import com.yeejoin.amos.boot.module.jczs.api.dto.MaintenanceUnitNameDto;
import com.yeejoin.amos.boot.module.jczs.api.entity.Elevator;
import com.yeejoin.amos.boot.module.jczs.api.entity.MaintenanceUnit;
import com.yeejoin.amos.boot.module.jczs.api.service.IMaintenanceUnitService;
import com.yeejoin.amos.boot.module.jczs.biz.utils.BeanDtoVoUtils;
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;


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

    @Autowired
    IMaintenanceUnitService iMaintenanceUnitService;

    @Autowired
    ElevatorServiceImpl elevatorServiceImpl;

    /**
     * 新增维保单位
     *
     * @param maintenanceUnitDto 新增参数
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增维保单位", notes = "新增维保单位")
    public ResponseModel<Boolean> saveMaintenanceUnit(@RequestBody MaintenanceUnit maintenanceUnitDto) {
        MaintenanceUnit maintenanceUnit = BeanDtoVoUtils.convert(maintenanceUnitDto, MaintenanceUnit.class);
        boolean save = iMaintenanceUnitService.save(maintenanceUnit);
        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 = iMaintenanceUnitService.removeById(id);
        return ResponseHelper.buildResponse(remove);
    }

    /**
     * 修改维保单位
     *
     * @param maintenanceUnitDto 修改参数
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "修改维保单位", notes = "修改维保单位")
    public ResponseModel<Boolean> updateByIdMaintenanceUnit(@RequestBody MaintenanceUnit maintenanceUnitDto) {
        MaintenanceUnit maintenanceUnit = BeanDtoVoUtils.convert(maintenanceUnitDto, MaintenanceUnit.class);
        boolean update = iMaintenanceUnitService.updateById(maintenanceUnit);
        return ResponseHelper.buildResponse(update);
    }

    /**
     * 根据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<MaintenanceUnitDto> selectById(@PathVariable Long id) {
        MaintenanceUnit maintenanceUnit = iMaintenanceUnitService.getById(id);
        MaintenanceUnitDto maintenanceUnitDto = BeanDtoVoUtils.convertMaintenanceUnitToVo(maintenanceUnit, false);
        return ResponseHelper.buildResponse(maintenanceUnitDto);
    }

    /**
     * 列表分页查询
     *
     * @param pageNum            当前页
     * @param pageSize           每页大小
     * @param maintenanceUnitDto 查询参数
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public ResponseModel<IPage<MaintenanceUnitDto>> listPage(String pageNum, String pageSize,
                                                            MaintenanceUnit maintenanceUnitDto) {
        MaintenanceUnit maintenanceUnit = BeanDtoVoUtils.convert(maintenanceUnitDto, MaintenanceUnit.class);
        Page<MaintenanceUnit> pageBean;
        QueryWrapper<MaintenanceUnit> maintenanceUnitQueryWrapper = new QueryWrapper<>();
        Class<? extends MaintenanceUnit> aClass = maintenanceUnit.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(maintenanceUnit);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(maintenanceUnit);
                        maintenanceUnitQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(maintenanceUnit);
                        maintenanceUnitQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(maintenanceUnit);
                        maintenanceUnitQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) field.get(maintenanceUnit);
                        maintenanceUnitQueryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        });
        IPage<MaintenanceUnit> 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 = iMaintenanceUnitService.page(pageBean, maintenanceUnitQueryWrapper);
        IPage<MaintenanceUnitDto> maintenanceUnitDtoIPage = BeanDtoVoUtils.maintenanceUnitIPageDto(page);
        return ResponseHelper.buildResponse(maintenanceUnitDtoIPage);
    }

    /**
     * 分页查询维保单位信息
     *
     * @param pageNum            当前页
     * @param pageSize           每页大小
     * @param maintenanceUnitDto 查询参数
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/query_maintenance_unit_list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "分页查询维保单位信息", notes = "分页查询维保单位信息")
    public ResponseModel<IPage<MaintenanceUnitDto>> queryMaintenanceUnitList(String pageNum, String pageSize,
                                                                            MaintenanceUnit maintenanceUnitDto) {
        MaintenanceUnit maintenanceUnit = BeanDtoVoUtils.convert(maintenanceUnitDto, MaintenanceUnit.class);
        Page<MaintenanceUnit> pageBean;
        QueryWrapper<MaintenanceUnit> maintenanceUnitQueryWrapper = new QueryWrapper<>();
        Class<? extends MaintenanceUnit> aClass = maintenanceUnit.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(maintenanceUnit);
                if (o != null) {
                    String name = NameUtils.camel2Underline(field.getName());
                    if ("city".equalsIgnoreCase(name) || "district".equalsIgnoreCase(name) || "qualification_level".equalsIgnoreCase(name)) {
                        String fileValue = (String) o;
                        maintenanceUnitQueryWrapper.eq(name, fileValue);
                    } else if ("credit_level".equalsIgnoreCase(name)) {
                        Integer fileValue = (Integer) o;
                        maintenanceUnitQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) o;
                        maintenanceUnitQueryWrapper.like(name, fileValue);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        });
        IPage<MaintenanceUnit> 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 = iMaintenanceUnitService.page(pageBean, maintenanceUnitQueryWrapper);
        IPage<MaintenanceUnitDto> maintenanceUnitDtoIPage = BeanDtoVoUtils.maintenanceUnitIPageDto(page);
        return ResponseHelper.buildResponse(maintenanceUnitDtoIPage);
    }

    /**
     * 根据名称查询维保单位列表
     *
     * @param unitName 维保单位名称
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/query_maintenance_unit_name_list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据名称查询维保单位列表", notes = "根据名称查询维保单位列表")
    public ResponseModel<IPage<MaintenanceUnitNameDto>> queryMaintenanceUnitListWithName(@PathVariable(required =
            false) String unitName) {
        QueryWrapper<MaintenanceUnit> maintenanceUnitQueryWrapper = new QueryWrapper<>();
        maintenanceUnitQueryWrapper.select("distinct sequence_nbr,unit_name").like(StringUtils.isNotEmpty(unitName),
                "unit_name", unitName);
        Page<MaintenanceUnit> pageBean = new Page<>(0, Long.MAX_VALUE);
        IPage<MaintenanceUnit> page = iMaintenanceUnitService.page(pageBean, maintenanceUnitQueryWrapper);
        IPage<MaintenanceUnitNameDto> maintenanceUnitVoIPage = BeanDtoVoUtils.iPageVoStream(page,
                MaintenanceUnitNameDto.class);
        return ResponseHelper.buildResponse(maintenanceUnitVoIPage);
    }

    /**
     * 根据警情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<MaintenanceUnitDto> selectByAlertId(@PathVariable Long alertId) {
        // 获取根据警情获取电梯信息
        Elevator elevator  = elevatorServiceImpl.selectByAlertId(alertId);
        if (ValidationUtil.isEmpty(elevator)) {
            throw new BadRequest("设备未找到");
        }
        // 根据设备使用单位id 获取使用单位信息
        MaintenanceUnit maintenanceUnit = iMaintenanceUnitService.getById(elevator.getMaintainUnitId());
        if (ValidationUtil.isEmpty(maintenanceUnit)) {
            throw new BadRequest("维保单位未找到");
        }
        MaintenanceUnitDto maintenanceUnitVo = BeanDtoVoUtils.convert(maintenanceUnit, MaintenanceUnitDto.class);
        List<DutyPersonDto> dutyPersonList = new ArrayList<DutyPersonDto>();
        DutyPersonDto principal = new DutyPersonDto();
        principal.setDeptName("主要负责人1");
        principal.setPhone(maintenanceUnitVo.getPrincipalFirstPhone());
        principal.setUserId(maintenanceUnitVo.getPrincipalFirstId()+"");
        principal.setUserName(maintenanceUnitVo.getPrincipalFirst());
        dutyPersonList.add(principal);
        DutyPersonDto manager = new DutyPersonDto();
        manager.setDeptName("主要负责人2");
        manager.setPhone(maintenanceUnitVo.getPrincipalSecondPhone());
        manager.setUserId(maintenanceUnitVo.getPrincipalSecondId()+"");
        manager.setUserName(maintenanceUnitVo.getPrincipalSecond());
        dutyPersonList.add(manager);
        maintenanceUnitVo.setDutyPersonList(dutyPersonList);

        return ResponseHelper.buildResponse(maintenanceUnitVo);
    }

}

