package com.unis.crk.hardware.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONObject;
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.unis.crk.cplbusiness.entity.DataCrkywCplspDefault;
import com.unis.crk.hardware.entity.Unithardware;
import com.unis.crk.hardware.entity.vo.UnithardwareVo;
import com.unis.crk.hardware.service.IUnithardwareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.unis.crk.utils.ResultUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 单位硬件管理表 前端控制器
 * </p>
 *
 * @author ghh
 * @since 2021-09-15
 */
@Api(value = "单位硬件管理",tags = {"单位硬件管理表"})
@RestController
@RequestMapping("unithardware")
@CrossOrigin
public class UnithardwareController {

    private final static Logger LOGGER = LoggerFactory.getLogger(UnithardwareController.class);


    @Autowired
    private IUnithardwareService unithardwareService;

    @ApiOperation(value="查询", notes="pageNum,pageSize,UnitId分页高级查询")
    @PostMapping(value="/getUnithardwareByUnitId")
    public ResultUtil getUnithardwareByUnitId(@RequestBody UnithardwareVo unithardwareVo) {
        ResultUtil<IPage<Map<String,Object>>> data = new ResultUtil<>();
        Page<Unithardware> objectPage = new Page<>(unithardwareVo.getPageNum(), unithardwareVo.getPageSize());
        QueryWrapper<Unithardware> unithardwareQueryWrapper = new QueryWrapper<>();
        if(StrUtil.isNotBlank(unithardwareVo.getUnitId())){
            unithardwareQueryWrapper.eq("u.UnitId",unithardwareVo.getUnitId());
        }
        if(StrUtil.isNotBlank(unithardwareVo.getHIID())){
            unithardwareQueryWrapper.eq("u.HIID",unithardwareVo.getHIID());
        }
        if(!ObjectUtils.isEmpty(unithardwareVo.getFilterIps())){
            unithardwareQueryWrapper.in("u.Filter_IP",unithardwareVo.getFilterIps());
        }
        if(unithardwareVo.getIsUsed()!=null){
            unithardwareQueryWrapper.eq("u.IsUsed",unithardwareVo.getIsUsed());
        }
        if(StrUtil.isNotBlank(unithardwareVo.getFilterIp())){
            unithardwareQueryWrapper.eq("u.Filter_IP",unithardwareVo.getFilterIp());
        }
        //分页相关
        IPage<Map<String, Object>> mapIPage = unithardwareService.getPageByUnitId(objectPage, unithardwareQueryWrapper);
        data.success(mapIPage);
        return data;
    }


    /**
     * 根据ID查询数据
     * @return
     */
    @ApiOperation(value="查询", notes="根据sbbh查询数据")
    @PostMapping(value="/getOne")
    public ResultUtil getOne(@RequestBody UnithardwareVo unithardwareVo){
        LOGGER.info("入参为:{}",unithardwareVo.getUnitHIID());
        ResultUtil<Unithardware> data = new ResultUtil<>();
        if (StringUtils.isEmpty(unithardwareVo.getUnitHIID())){
            data.failed("传入的主键为空");
            return data;
        }
        ResultUtil<Unithardware> success = data.success(this.unithardwareService.getById(unithardwareVo.getUnitHIID()));
        return data;
    }



    /**
     * 新增一条数据
     * @param param
     * @return
     */
    @ApiOperation(value="新增", notes="新增一条数据")
    @PostMapping("add")
    public ResultUtil add(@RequestBody Unithardware param){
        LOGGER.info("入参为:{}", param);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (ObjectUtils.isEmpty(param)){
            data.failed("所接收对象为null");
            return data;
        }
        data.success(this.unithardwareService.save(param));
        return data;
    }


    /**
     * 修改一条数据
     * @param param
     * @return
     */
    @ApiOperation(value="修改", notes="修改一条数据")
    @PatchMapping("edit")
    public ResultUtil edit(@RequestBody Unithardware param){
        LOGGER.info("入参为:{}", param);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (ObjectUtils.isEmpty(param)){
            data.failed("所接收对象为null");
            return data;
        }
        data.success(this.unithardwareService.updateById(param));
        return data;
    }


    /**
     * 根据ID删除数据
     * @return
     */
    @ApiOperation(value="删除", notes="根据HIID删除数据")
    @PostMapping(value="/delete")
    public ResultUtil delete(@RequestBody UnithardwareVo unithardwareVo){
        LOGGER.info("入参为:{}", unithardwareVo.getUnitHIID());
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (StringUtils.isEmpty(unithardwareVo.getUnitHIID())){
            data.failed("所接收id为null");
            return data;
        }
        data.success(this.unithardwareService.removeById(unithardwareVo.getUnitHIID()));
        return data;
    }



    @ApiOperation(value="根据单位id,工作机IP,查询已启用地磅信息", notes="UnitId 根据单位id,FilterIP 工作机IP,IsUsed 是否启用,HIID 硬件编码类型")
    @PatchMapping("getUnithardware")
    public ResultUtil getUnithardware(@RequestBody UnithardwareVo unithardwareVo){
        ResultUtil<List> data = new ResultUtil<>();
        if (StrUtil.isBlank(unithardwareVo.getHIID()) || StrUtil.isBlank(unithardwareVo.getUnitId()) ){
            data.failed("传入的参数为空");
            return data;
        }
        List<Unithardware> deviceType = this.unithardwareService.findDeviceType(unithardwareVo.getHIID(), unithardwareVo.getFilterIp(), unithardwareVo.getUnitId(), unithardwareVo.getIsUsed());
        data.success(deviceType);
        return data;
    }
    /**
     * 地磅选择页面选择摄像头和LED
     * @return
     */
    @ApiOperation(value="查询", notes="根据硬件类型(必传),工作机IP(可传),单位ID（必传）,是否启用(可传)")
    @PostMapping(value="/DropDown")
    public ResultUtil getUnithardwareDropDown(@RequestBody UnithardwareVo unithardwareVo){
        ResultUtil<List> data = new ResultUtil<>();
        List<Unithardware> list = unithardwareService.getUnithardwareDropDown(unithardwareVo);
        data.success(list);
        return data;
    }











    @RequestMapping(value = "/multiImport", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> multiImport(@RequestParam("uploadFile") MultipartFile[] uploadFile, HttpServletRequest request) throws IOException {
        Map<String, Object> result = new HashMap<String, Object>();
        String path;
        System.out.println(uploadFile.length);
        for (MultipartFile file:uploadFile) {
            if (file != null) {// 判断上传的文件是否为空
                String type = null;// 文件类型
                String fileName = file.getOriginalFilename();// 文件原名称
                LOGGER.info("上传的文件原名称", fileName);
                // 判断文件类型
                type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
                if (type != null) {// 判断文件类型是否为空

                    if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {

                        // 项目在容器中实际发布运行的根路径
                        String realPath = request.getSession().getServletContext().getRealPath("/");
                        String[] split = realPath.split("\\\\");
                        path=split[0]+"\\"+split[1]+"\\CameraImg\\";
                        // 自定义的文件名称
                        String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
                        File file1=new File(path);
                        //如果文件夹不存在则创建
                        if(!file1.exists()  && !file1.isDirectory()){
                            file1.mkdirs();
                        }

                        // 设置存放图片文件的路径

                        String filepath = path + fileName;
                        // 转存文件到指定的路径
                        file.transferTo(new File(filepath));
                        LOGGER.info("文件成功上传到指定目录下", filepath);
                        result.put(filepath,"true");
                    }

                } else {
                    System.out.println("");
                    result.put(fileName,"不是我们想要的文件类型,请按要求重新上传");
                    LOGGER.info("不是我们想要的文件类型,请按要求重新上传", fileName);
                }
            } else {
                System.out.println("文件类型为空");
                result.put("false","文件类型为空");
                LOGGER.info("此文件上传失败", "文件类型为空");
            }
        }
        return result;
    }

    /**
     * 修改一条数据
     * @param id
     * @return
     */
    @ApiOperation(value="修改数据", notes="根据硬件标识和数据id修改状态(只能存在一个启用)")
    @PatchMapping("/updataIsUsed")
    public ResultUtil updataIsUsedsbyIp(@RequestParam String id,@RequestParam String ip){
        LOGGER.info("入参为:{}", id+ip);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (ObjectUtils.isEmpty(id)){
            data.failed("所接收参数为null");
            return data;
        }
        JSONObject ret  = this.unithardwareService.updataIsUsed(id,ip);
        if (ret.getBool("success")){
            data.success(ret.getStr("msg"));
        }else {
            data.failed(ret.getStr("msg"));
        }

        return data;
    }
}




