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

import com.alibaba.fastjson.JSONObject;
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.socket.SocketClient;
import com.chinaitop.depot.intelligent.utils.ConstUtils;
import com.chinaitop.depot.intelligent.utils.HexConvertUtils;
import com.chinaitop.depot.intelligent.utils.ParameterUtil;
import com.chinaitop.depot.intelligent.utils.UuidUtils;
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.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;
    @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 createTime,String orgId) {
        List<Map<String, Object>> list = null;
        try {
            if (null != pageNum && null != pageSize) {
                PageHelper.startPage(pageNum, pageSize);
            }
            list = insectPestDetectionService.getList(vCfCode, iBeginTdh, iEndTdh,createTime,orgId);
        } 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")
    })
    public ResponseEntity getByCfCode(String vCfCode, String searchStartDate, String searchEndDate) {
        ResponseEntity byCfCode = null;
        try {
            byCfCode = insectPestDetectionService.getByCfCode(vCfCode, searchStartDate, searchEndDate);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("查询图表数据失败");
        }
        return byCfCode;
    }

    @RequestMapping(value = "/getByIdCcData", method = RequestMethod.GET)
    @ApiOperation(value = "查询一条虫害信息", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "仓房code", paramType = "query"),
            @ApiImplicitParam(name = "searchStartDate", value = "开始时间", paramType = "query"),
            @ApiImplicitParam(name = "searchEndDate", value = "结束时间", paramType = "query")
    })
    public ResponseEntity<TCcdata> getByIdTCcData(String id) {
        TCcdata tCcdata = null;
        try {
            tCcdata  = insectPestDetectionService.getByIdTCcData(id);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("error");
        }
        return ResponseEntity.ok(tCcdata);
    }

    /**
     * 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")
    })
    public ResponseEntity<Map<String, String>> sendNowInsectPest(String storeCode) {
        Map<String, String> map = new LinkedHashMap<>();
        if (StringUtils.isNotBlank(storeCode)) {
            String sTemp = storeCode.substring(0, storeCode.length());
            String[] sArray = sTemp.split(",");
            for (String cfCode : sArray) {
                // 0X07虫情数据采集,仓房号,设备编号若为0则控全部
                String dir = constUtils.directiveJoint(constUtils.F_EXTENT, constUtils.SUB_P, constUtils.WORM_TYPE, cfCode, "");
                // 16进制字符串转byte数组
                byte[] bytes = HexConvertUtils.hexStringToByte(dir);
                // 发送指令
                String s = socketClient.startClient(bytes);
                // 0：失败；1：成功；2：设备通讯异常；3：设备故障；4：未知原因; 5: 本地模式(有的设备有本地模式，即无法远程控制)
                if (s.contains("7E")) {
                    String substring = s.substring(s.length() - 2, s.length());
                    if ("00".equals(substring))
                        map.put(cfCode, TypeEnum.S_NUL.getDesc()); // 失败
                    else if ("01".equals(substring))
                        map.put(cfCode, TypeEnum.S_SOH.getDesc()); // 成功
                    else if ("02".equals(substring))
                        map.put(cfCode, TypeEnum.S_STX.getDesc()); // 设备通讯异常
                    else if ("03".equals(substring))
                        map.put(cfCode, TypeEnum.S_ETX.getDesc()); // 设备故障
                    else if ("04".equals(substring))
                        map.put(cfCode, TypeEnum.S_EOT.getDesc()); // 未知原因
                    else if ("05".equals(substring))
                        map.put(cfCode, TypeEnum.S_2D_SOH.getDesc()); // 本地模式,无法远程控制
                    else if ("06".equals(substring))
                        map.put(cfCode, TypeEnum.SM.getDesc()); // 设备正忙
                } else {
                    if (s.contains("323230")) { // 220-FileZilla Server 0.9.60 beta
                        map.put("error", "无法连接到服务器!");
                    } else {
                        map.put("error", s);
                    }
                    return ResponseEntity.failed(s);
                }
            }
        } else {
            return ResponseEntity.failed(TypeEnum.S_EM.getDesc());
        }
        return ResponseEntity.ok(map);
    }

    /**
     * 单仓检测接口
     *
     * @param vCfCode
     * @return
     */
    @RequestMapping(value = "/sendOnlyInsectPestDetection", method = RequestMethod.POST)
    @ApiOperation(value = "单仓虫情实时检测", notes = "单仓虫情实时检测")
    @ApiImplicitParam(name = "vCfCode", defaultValue = "001", value = "仓库编号", paramType = "query")
    public ResponseEntity sendOnlyInsectPestDetection(String vCfCode) {
        String result = "";
        try {
            if (StringUtils.isNotBlank(vCfCode)) {
                // 0X07虫情数据采集,仓房号,设备编号若为0则控全部
                String dir = constUtils.directiveJoint(constUtils.F_EXTENT, constUtils.SUB_P, constUtils.WORM_TYPE, vCfCode, "");
                // 16进制字符串转byte数组
                byte[] bytes = HexConvertUtils.hexStringToByte(dir);
                // 发送指令
                String s = socketClient.startClient(bytes);
                result = TypeEnum.resultDispose(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok("设备连接异常！");
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 所有仓实时检测
     *
     * @return
     */
    @RequestMapping(value = "/sendInsectPestDetectionAll", method = RequestMethod.GET)
    @ApiOperation(value = "所有仓虫情实时检测", notes = "所有仓虫情实时检测")
    public ResponseEntity sendTemperatureDetectionAll() {
        String result = "";
        try {
            // 0X07虫情数据采集,仓房号,设备编号若为0则控全部
            String dir = constUtils.HEADER + constUtils.F_EXTENT + constUtils.WORM_TYPE + constUtils.SUB_P + constUtils.ALL_STORE;
            // 16进制字符串转byte数组
            byte[] bytes = HexConvertUtils.hexStringToByte(dir);
            // 发送指令
            String s = socketClient.startClient(bytes);
            // 0：失败；1：成功；2：设备通讯异常；3：设备故障；4：未知原因; 5: 本地模式(有的设备有本地模式，即无法远程控制)
            result = TypeEnum.resultDispose(s);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok("设备连接异常！");
        }
        return ResponseEntity.ok(result);
    }

    @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 = "form")
    })
    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();

        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("warehouseId", jsStr.get("vHwCode").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")==null ? "":jsStr.get("standOr").toString());//扦养人
        tCcdata.setStandTime(ParameterUtil.string2datetime(jsStr.get("standTime").toString()));//扦养时间
        tCcdata.setHczl(jsStr.get("hczl").toString());//害虫种类
        tCcdata.setCkmdzjh(jsStr.get("ckmdzjh").toString());//虫口密度值集合
        /*tCcdata.setiValue(Integer.parseInt(jsStr.get("iValue").toString()));//数量*/
        tCcdata.setvUpdateTime(ParameterUtil.string2datetime(jsStr.get("vUpdateTime").toString()));//监测时间
        tCcdata.setJchcff(jsStr.get("jchcff")==null ? "":jsStr.get("jchcff").toString());//检查害虫方法
        tCcdata.setCldjpd(jsStr.get("cldjpd")==null ? "":jsStr.get("cldjpd").toString());//虫粮等级判定
        tCcdata.setHckyxfx(jsStr.get("hckyxfx")==null ? "":jsStr.get("hckyxfx").toString());//害虫抗药性分析
        tCcdata.setvUpdatePeople(jsStr.get("vUpdatePeople").toString());//检测人
        tCcdata.setId(uuidUtils.getCodeId(orgId, "t_ccdata"));//唯一id
        tCcdata.setDataSource("1");//数据来源0是自动检测，1是手工录入
        tCcdata.setJchcff("0");
        tCcdata.setFsbw(jsStr.get("fsbw")==null ? "":jsStr.get("fsbw").toString());
        insectPestDetectionService.add(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);
    }
}
