package com.chinaitop.depot.intelligent.grainsituation.controller;

import com.alibaba.fastjson.JSONObject;
import com.chinaitop.depot.intelligent.fumigation.model.TFumigationPlanExample;
import com.chinaitop.depot.intelligent.grainsituation.model.TCcdata;
import com.chinaitop.depot.intelligent.grainsituation.model.TCcdataExample;
import com.chinaitop.depot.intelligent.grainsituation.model.TCcvalue;
import com.chinaitop.depot.intelligent.grainsituation.service.InsectPestDetectionService;
import com.chinaitop.depot.intelligent.grainsituation.service.TemperatureRecordService;
import com.chinaitop.depot.intelligent.socket.SocketClient;
import com.chinaitop.depot.intelligent.utils.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.unissoft.model.ResponseEntity;
import com.unissoft.model.TypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/intelligents/insectPestDetection")
@Api(value = "InsectPestDetectionController", description = "虫害检测记录控制类")
@SuppressWarnings("all")
public class InsectPestDetectionController {

    @Resource
    InsectPestDetectionService insectPestDetectionService;
    @Autowired
    private TemperatureRecordService temperatureRecordService;
    @Resource
    private RemoteControlUtil remoteControlUtil;

    @Resource
    private UuidUtils uuidUtils;

    /**
     * 虫害信息列表
     *
     * @param pageNum
     * @param pageSize
     * @param iBeginTdh
     * @param iEndTdh
     * @return
     */
    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    @ApiOperation(value = "查询虫害信息列表", notes = "虫害信息列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "iBeginTdh", value = "开始通道号", paramType = "query"),
            @ApiImplicitParam(name = "iEndTdh", value = "结束通道号", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "组织机构id", paramType = "query")
    })
    public ResponseEntity<PageInfo<Map<String, Object>>> getList(Integer pageNum, Integer pageSize, String vCfCode, Integer iBeginTdh, Integer iEndTdh,String orgId, String startTime, String endTime) {
        List<Map<String, Object>> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = insectPestDetectionService.getList(vCfCode, iBeginTdh, iEndTdh,orgId,startTime,endTime);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("查询失败");
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
        return ResponseEntity.ok(pageInfo);
    }

    @RequestMapping(value = "/getByCfCode", method = RequestMethod.GET)
    @ApiOperation(value = "查询虫害信息列表", notes = "虫害信息列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "vCfCode", value = "仓房code", paramType = "query"),
            @ApiImplicitParam(name = "searchStartDate", value = "开始时间", paramType = "query"),
            @ApiImplicitParam(name = "searchEndDate", value = "结束时间", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "组织机构id", paramType = "query")
    })
    public ResponseEntity getByCfCode(String vCfCode, String searchStartDate, String searchEndDate,Integer orgId) {
        ResponseEntity byCfCode = null;
        try {
            byCfCode = insectPestDetectionService.getByCfCode(vCfCode, searchStartDate, searchEndDate,orgId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("查询图表数据失败");
        }
        return byCfCode;
    }

    /**
     * orgid下的逐仓粮情检测
     *
     * @param storeCode
     * @return
     */
    @Autowired
    private SocketClient socketClient;
    @Autowired
    private ConstUtils constUtils;

    @RequestMapping(value = "/sendNowInsectPest", method = RequestMethod.POST)
    @ApiOperation(value = "虫害实时检测", notes = "虫害实时检测")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeCode", defaultValue = "001", value = "仓库编号", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "组织机构编号", paramType = "query")
    })
    public ResponseEntity<Map<String, String>> sendNowInsectPest(String storeCode,Integer orgId) {
        // 1.获取库端url
        String url = temperatureRecordService.getRemoteUrl(orgId+"");
        if (StringUtils.isBlank(url))
            return ResponseEntity.failed("库端硬件地址未配置!");
        // 2.封装请求数据
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("storeCode", storeCode);
        return remoteControlUtil.remoteScan(
                String.format("%s%s", url, remoteControlUtil.nowInsectPest),
                requestEntity, "POST", null
        );
    }

    /**
     * 单仓检测接口
     *
     * @param vCfCode
     * @return
     */
    @RequestMapping(value = "/sendOnlyInsectPestDetection", method = RequestMethod.POST)
    @ApiOperation(value = "单仓虫情实时检测", notes = "单仓虫情实时检测")
    @ApiImplicitParams({
    @ApiImplicitParam(name = "vCfCode", defaultValue = "001", value = "仓库编号", paramType = "query"),
    @ApiImplicitParam(name = "orgId", value = "组织机构编号", paramType = "query")
    })
    public ResponseEntity sendOnlyInsectPestDetection(String vCfCode,Integer orgId) {
        // 1.获取库端url
        String url = temperatureRecordService.getRemoteUrl(orgId+"");
        if (StringUtils.isBlank(url))
            return ResponseEntity.failed("库端硬件地址未配置!");
        // 2.封装请求数据
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("vCfCode", vCfCode);
        return remoteControlUtil.remoteScan(
                String.format("%s%s", url, remoteControlUtil.onlyPest),
                requestEntity, "POST", null
        );
    }

    /**
     * 所有仓实时检测
     *
     * @return
     */
    @RequestMapping(value = "/sendInsectPestDetectionAll", method = RequestMethod.GET)
    @ApiOperation(value = "所有仓虫情实时检测", notes = "所有仓虫情实时检测")
    public ResponseEntity sendTemperatureDetectionAll(Integer orgId) {
        // 1.获取库端url
        String url = temperatureRecordService.getRemoteUrl(orgId+"");
        if (StringUtils.isBlank(url))
            return ResponseEntity.failed("库端硬件地址未配置!");
        // 2.封装请求数据
        Map<String, String> requestEntity = new HashMap<>();

        return remoteControlUtil.remoteScan(
                String.format("%s%s", url, remoteControlUtil.pestAll),
                null, "GET", requestEntity
        );

    }

    @RequestMapping(value = "/getOneByCfCode", method = RequestMethod.GET)
    @ApiOperation(value = "查询虫害信息", notes = "虫害信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "库点编码", paramType = "query"),
            @ApiImplicitParam(name = "vCfCode", value = "仓房code", paramType = "query")
    })
    public ResponseEntity getOneByCfCode(String orgId, String vCfCode) {
        TCcvalue ccvalue = null;
        try {
            ccvalue =  insectPestDetectionService.getOneByCfCode(orgId, vCfCode);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("查询测虫数据失败");
        }
        return ResponseEntity.ok(ccvalue);
    }


    @RequestMapping(value = "/addInsectPestData", method = RequestMethod.POST)
    @ApiOperation(value = "添加虫害", notes = "手工添加虫害数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "insectPests", value = "虫数据", paramType = "query")
    })
    public ResponseEntity addInsectPestData(String insectPests) {
        //先把传过来的json转换
        JSONObject jsStr = JSONObject.parseObject(insectPests);

        Map<String, Object> modelMap = new HashMap<String, Object>();
        TCcvalue tCcvalue = new TCcvalue();
        TCcdata tCcdata = new TCcdata();

//        if (jsStr.get("id") == null) {
            String orgId = jsStr.get("orgId").toString();
            tCcvalue.setvCfCode(jsStr.get("vCfCode").toString());//仓房code
            tCcvalue.setvCcCode(jsStr.get("vCfCode").toString());//仓房code
            tCcvalue.setOrgId(orgId);//组织机构id
            tCcvalue.setvUpdateTime(ParameterUtil.string2datetime(jsStr.get("vUpdateTime").toString()));//采集时间

            //害虫检测单号
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("orgId", orgId);
            map.put("vcfcode", jsStr.get("vCfCode").toString());
            map.put("updateTime", ParameterUtil.string2datetime(jsStr.get("vUpdateTime").toString()));
            List<Map<String,Object>> jcdList = insectPestDetectionService.getJcd(map);
            String jcd = ObjectUtils.toString(jcdList.get(0).get("jcd"));
            tCcvalue.setHcjcdh(jcd);
            tCcvalue.setId(uuidUtils.getCodeId(orgId, "t_ccvalue"));//唯一id

            tCcdata.setOrgId(orgId);//组织机构id
            tCcdata.setvHwCode(jsStr.get("vHwCode").toString());//货位code
            tCcdata.setvCcCode(jsStr.get("vCfCode").toString());//仓房code
            tCcdata.setStandOr(jsStr.get("standOr").toString());//扦养人
            tCcdata.setStandTime(ParameterUtil.string2datetime(jsStr.get("standTime").toString()));//扦养时间
            tCcdata.setHczl(jsStr.get("hczl").toString());//害虫种类
            tCcdata.setiValue(Integer.parseInt(jsStr.get("iValue").toString()));//数量
            tCcdata.setvUpdateTime(ParameterUtil.string2datetime(jsStr.get("vUpdateTime").toString()));//监测时间
            tCcdata.setvUpdatePeople(jsStr.get("vUpdatePeople").toString());//检测人
            tCcdata.setId(uuidUtils.getCodeId(orgId, "t_ccdata"));//唯一id
            tCcdata.setDataSource("1");//数据来源0是自动检测，1是手工录入
            tCcdata.setJchcff("0");
            insectPestDetectionService.add(tCcdata, tCcvalue);//熏蒸计划
//        } else {
//            tCcvalue.setvCfCode(jsStr.get("vCfCode").toString());//仓房code
//            tCcvalue.setvUpdateTime(ParameterUtil.string2date(jsStr.get("vUpdateTime").toString()));//采集时间
//            tCcvalue.setId(jsStr.get("ccvalueid").toString());
//
//            tCcdata.setId(jsStr.get("ccdataid").toString());
//            tCcdata.setvHwCode(jsStr.get("vHwCode").toString());//货位code
//            tCcdata.setStandOr(jsStr.get("standOr").toString());//扦养人
//            tCcdata.setStandTime(ParameterUtil.string2date(jsStr.get("standTime").toString()));//扦养时间
//            tCcdata.setHczl(jsStr.get("hczl").toString());//害虫种类
//            tCcdata.setiValue(Integer.parseInt(jsStr.get("iValue").toString()));//数量
//            tCcdata.setvUpdateTime(ParameterUtil.string2date(jsStr.get("vUpdateTime").toString()));//监测时间
//            tCcdata.setvUpdatePeople(jsStr.get("vUpdatePeople").toString());//检测人
//            insectPestDetectionService.update(tCcdata, tCcvalue);
//        }
        return ResponseEntity.ok(modelMap);
    }


    @RequestMapping(value = "/getInsectPestDeatil", method = RequestMethod.POST)
    @ApiOperation(value = "修改虫害单仓手工录入数据", notes = "修改虫害单仓手工录入数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "insectPestId", value = "虫害检测id", paramType = "query")
    })
    public ResponseEntity getInsectPestDeatil(String insectPestId) {
        TCcdata tCcdata = new TCcdata();
        TCcdataExample example = new TCcdataExample();
        TCcdataExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(insectPestId);
        List<TCcdata> tccdataList = insectPestDetectionService.getInsectPestDeatil(example);
        return ResponseEntity.ok(tccdataList);
    }
}
