package com.bonus.material.device.controller;

import cn.hutool.core.convert.Convert;
import com.bonus.common.biz.config.ListPagingUtil;
import com.bonus.common.biz.domain.BmCompanyInfo;
import com.bonus.common.core.utils.poi.ExcelUtil;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.device.domain.DevInfo;
import com.bonus.material.device.domain.dto.DevInfoImpDto;
import com.bonus.material.device.domain.dto.InfoMotionDto;
import com.bonus.material.device.domain.vo.DevInfoVo;
import com.bonus.material.device.domain.vo.DevTemplateVo;
import com.bonus.material.device.service.DevInfoService;
import com.bonus.system.api.domain.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * 设备信息Controller
 *
 * @author syruan
 */
@RestController
@RequestMapping("/dev")
@Api(value = "设备信息", tags = "设备管理")
public class DevInfoController extends BaseController {

    @Resource
    private DevInfoService devInfoService;

    /**
     * 查询设备信息列表(首页装备共享大厅查询列表专用)
     */
//    @RequiresPermissions("equip:info:list")
    @ApiOperation(value = "装备列表")
    @PostMapping("/list")
    public AjaxResult list(@RequestBody DevInfoVo devInfo) {
        List<DevInfoVo> list = devInfoService.selectDevInfoList(devInfo);
        Integer pageIndex = Convert.toInt(devInfo.getPageNum(), 1);
        Integer pageSize = Convert.toInt(devInfo.getPageSize(), 10);
        return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
    }

    @ApiOperation(value = "查询装备审批列表")
    @PostMapping("/checkList")
    public AjaxResult checkList(@RequestBody DevInfoVo devInfo) {
        List<DevInfoVo> list = devInfoService.selectCheckDevInfoList(devInfo);
        Integer pageIndex = Convert.toInt(devInfo.getPageNum(), 1);
        Integer pageSize = Convert.toInt(devInfo.getPageSize(), 10);
        return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
    }

    /**
     * 查询设备信息列表(首页企业专区列表)
     */
    @ApiOperation(value = "企业专区装备列表")
    @PostMapping("/zone_list")
    public AjaxResult zoneList(@RequestBody DevInfoVo devInfo) {
        List<DevInfoVo> list = devInfoService.selectZoneDevInfoList(devInfo);
        Integer pageIndex = Convert.toInt(devInfo.getPageNum(), 1);
        Integer pageSize = Convert.toInt(devInfo.getPageSize(), 10);
        return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
    }

    @ApiOperation(value = "统计公司上架数")
    @PostMapping("/getCompanyCount")
    public AjaxResult getCompanyCount(@RequestBody DevInfoVo devInfo) {
        Map<String, Long> map = devInfoService.getCompanyCount(devInfo);
        return AjaxResult.success(map);
    }

    /**
     * 获取公司列表(供装备新增及首页所属公司筛选使用)
     *
     * @param obj
     * @return
     */
    @GetMapping("/companyList")
    @ApiOperation("获取公司列表")
    public AjaxResult companyList(BmCompanyInfo obj) {
        List<BmCompanyInfo> list = devInfoService.selectCompanyList(obj);
        return success(list);
    }

    /**
     * 查询商品列表--分页
     */
    //@RequiresPermissions("equip:info:list")
    @ApiOperation(value = "查询装备列表--分页")
    @GetMapping("/devList")
    public TableDataInfo devList(DevInfoVo devInfo) {
        startPage();
        List<DevInfoVo> list = devInfoService.selectDevInfoLists(devInfo);
        return getDataTable(list);
    }

    @ApiOperation(value = "收藏装备列表")
    @PostMapping("/userCollectList")
    public TableDataInfo userCollectList(@RequestBody DevInfoVo devInfo) {
        startPage();
        List<DevInfoVo> list = devInfoService.selectUserCollectList(devInfo);
        return getDataTable(list);
    }

    // @RequiresPermissions("equip:info:list")
    @ApiOperation(value = "装备推荐列表")
    @GetMapping("/hotList")
    public AjaxResult hotList(DevInfoVo devInfo) {
        return devInfoService.selectDevInfoHotList(devInfo);
    }

    @ApiOperation(value = "关联装备列表")
    @GetMapping("/associationList")
    public AjaxResult associationList(DevInfoVo devInfo) {
        return AjaxResult.success(devInfoService.selectAssociationList(devInfo));
    }

    /**
     * 获取设备信息详细信息
     */
    //@RequiresPermissions("equip:info:query")
    @ApiOperation(value = "装备详情")
    @GetMapping(value = "/getInfo/{maId}")
    public AjaxResult getInfo(@PathVariable("maId") Long maId,
                              @RequestParam(value = "isHome", required = false) Boolean isHome) {
        return success(devInfoService.selectDevInfoByMaId(maId, isHome));
    }


    /**
     * 获取设备信息详细信息
     */
    //@RequiresPermissions("equip:info:query")
    @ApiOperation(value = "装备详情")
    @GetMapping(value = "/getInfo")
    public AjaxResult getInfoById(Long id, String devType,
                                  @RequestParam(value = "isHome", required = false) Boolean isHome) {
        return success(devType.equals("0") ? devInfoService.selectDevInfoByMaId(id, isHome) : devInfoService.selectToolByMaId(id, isHome));
    }


    /**
     * 上下架（批量）
     */
    // @RequiresPermissions("equip:info:edit")
    @ApiOperation(value = "上下架（批量）")
    @PostMapping("updateUpDown")
    public AjaxResult updateUp(@RequestBody DevInfo devInfo) {
        return devInfoService.updateUpDown(devInfo);
    }

    /**
     * 修改设备信息
     */
    // @RequiresPermissions("equip:info:edit")
    @ApiOperation(value = "修改装备信息")
    @PostMapping("edit")
    public AjaxResult edit(@RequestBody @Valid DevInfo devInfo) {
        return devInfoService.updateDevInfo(devInfo);
    }

    /**
     * 删除设备信息
     */
    //@RequiresPermissions("equip:info:remove")
    @ApiOperation(value = "删除装备")
    @PostMapping("/remove")
    public AjaxResult remove(@RequestBody Long[] maIds) {
        return toAjax(devInfoService.deleteDevInfoByMaIds(maIds));
    }


    /**
     * 设备信息录入---录入经纬度
     *
     * @param infoMotionDto 设备信息
     */
    @ApiOperation(value = "装备信息录入--含经纬度")
    @PostMapping("/insertInfoMotionDto")
    public AjaxResult insertInfoMotionDto(@RequestBody InfoMotionDto infoMotionDto) {
        return toAjax(devInfoService.insertInfoMotionDto(infoMotionDto));
    }

    /**
     * 添加设备--UUID生成CODE--字符串
     *
     * @param devInfo 设备信息
     */
    @ApiOperation(value = "添加设备--字符串传入--UUID生成CODE")
    @PostMapping("/outType")
    public void outType(@RequestBody String devInfo) {
        devInfoService.insertOutType(devInfo);
    }

    /**
     * 新增设备信息--包含附件上传
     */
    //@RequiresPermissions("equip:info:add")
    @ApiOperation(value = "新增装备(包含草稿)--含附件上传")
    @PostMapping
    public AjaxResult add(@RequestBody @Valid DevInfo devInfo) {
        //0914 添加字段
        devInfo.setEntryStatus("0");
        return devInfoService.insertDevInfo(devInfo);
    }

    /**
     * 统计装备
     */
    @ApiOperation(value = "装备统计")
    @GetMapping("/sumType")
    public AjaxResult sumType() {
        return success(devInfoService.sumType());
    }

    /**
     * 导出设备信息列表
     */
    // @RequiresPermissions("equip:info:export")
    @ApiOperation(value = "导出装备信息")
    @PostMapping("/export")
    public void export(HttpServletResponse response, DevInfoVo devInfo) {
        List<DevInfoVo> list = devInfoService.selectDevInfoList(devInfo);
        ExcelUtil<DevInfoVo> util = new ExcelUtil<>(DevInfoVo.class);
        util.exportExcel(response, list, "设备信息数据");
    }

    /*@ApiOperation(value = "装备批量录入")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        String fileName = file.getOriginalFilename();
        if (fileName != null) {
            String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
            long fileSize = file.getSize();
            if (!fileExtension.equalsIgnoreCase("xls") && !fileExtension.equalsIgnoreCase("xlsx")) {
                // 文件后缀名不符合要求
                return error("文件后缀名不符合要求");
            } else if (fileSize > 10 * 1024 * 1024) {
                // 文件大小超过10M
                return error("文件大小超过10M");
            }
        }
        ExcelUtil<DevInfoImpDto> util = new ExcelUtil<DevInfoImpDto>(DevInfoImpDto.class);
        List<DevInfoImpDto> maPropInfoList = util.importExcel(file.getInputStream());
        Long userId = SecurityUtils.getLoginUser().getUserid();
        String message = devInfoService.importMaProp(maPropInfoList, updateSupport, userId);
        return success(message);
    }*/


    @ApiOperation(value = "装备模版下载")
    @PostMapping("/downLoad")
    public void downLoadExcelFile() throws IOException {
        HttpServletResponse resp = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        devInfoService.downLoadTemplate(resp);
    }

    /**
     * 设备批量导入模版下载
     */
    @ApiOperation(value = "设备批量导入模版下载")
    @PostMapping("/downLoadDev")
    public void downLoadDev() {
        HttpServletResponse resp = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        devInfoService.downLoadDev(resp);
    }

    /**
     * 设备信息导入
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "设备信息导入")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) {
        return devInfoService.importTbPeople(file);
    }

    @ApiOperation(value = "设备信息-审核")
    @PostMapping("/updateDeviceStatus")
    public AjaxResult updateDeviceStatus(String ids, String status) {
        try {
            Integer i = devInfoService.updateCheckStatus(ids, status);
            if (i > 0) {
                return AjaxResult.success("审核成功");
            } else {
                return AjaxResult.error("审核失败");
            }
        } catch (Exception e) {
            logger.error("报错啦", e);
            return AjaxResult.error("调用异常，请联系管理员");
        }
    }
}
