package com.pqs9900.controller.configuration;

import com.njcn.enums.LogTypeEnum;
import com.njcn.mapper.configuration.ConstantValueMapper;
import com.njcn.mapper.configuration.ProtectControlWordMapper;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.configuration.ConstantValue;
import com.njcn.pojo.configuration.ProtectControlWord;
import com.njcn.service.configuration.ConstantValueService;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.utils.PubUtils;
import com.njcn.utils.XssFilterUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.security.auth.login.AccountException;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author denghuajun
 * @Description //TODO 定值管理
 * @Date 2018/10/15 21:50
 **/
@Controller
@RequestMapping(value = "constant")
public class ConstantValueController {
    @Autowired
    private ConstantValueService cvs;
    @Autowired
    private ConstantValueMapper cvsm;
    @Autowired
    private ProtectControlWordMapper pcwm;
    @Resource
    UserLogDetailService userLog;

    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(ConstantValueController.class);

    @RequestMapping(value = "quarryOutValue", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult quarryOutValue(HttpServletRequest request, String devtype, String tltName, String isOutIn, long lineIndex) throws AccountException {
        HttpResult result = new HttpResult();
        List<ConstantValue> quarryOutValue = new ArrayList<>();//简谐波
        List<ConstantValue> quarryOutValue1 = new ArrayList<>();//谐波电压
        List<ConstantValue> quarryOutValue2 = new ArrayList<>();//谐波电流
        List<ConstantValue> quarryOutValue3 = new ArrayList<>();//基本定值
        List<List> quarryValue = new ArrayList<>();
        //后台Xss攻击处理、包括html/js/sql
        devtype = XssFilterUtil.dealString(devtype);
        try {
            if (isOutIn.equals("out")) {  //外部定值
                List<ConstantValue> constantValues = cvs.quarryOutValueBase(lineIndex);
                if (constantValues.size() != 0 || !constantValues.isEmpty()) {
                    for (int i = 0; i < constantValues.size(); i++) {
                        if (constantValues.get(i).getDzType() == 1) {
                            quarryOutValue3.add(constantValues.get(i));
                        } else if (constantValues.get(i).getDzType() == 2) {
                            quarryOutValue2.add(constantValues.get(i));
                        } else if (constantValues.get(i).getDzType() == 3) {
                            quarryOutValue1.add(constantValues.get(i));
                        } else if (constantValues.get(i).getDzType() == 4) {
                            quarryOutValue.add(constantValues.get(i));
                        }
                    }
                    quarryValue.add(quarryOutValue3);
                    quarryValue.add(quarryOutValue2);
                    quarryValue.add(quarryOutValue1);
                    quarryValue.add(quarryOutValue);
                    result.setCode(200);
                    result.setMessage("获取定值信息成功");
                    userLog.getLog("查询定值信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                    result.setBody(quarryValue);
                } else {
                    result.setCode(500);
                    result.setMessage("获取定值信息失败");
                    userLog.getLog("查询定值信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                    result.setBody(null);
                }
            } else if (isOutIn.equals("in")) { //内部定值
                List<ConstantValue> constantValues = cvs.quarryInValueBase(lineIndex);
                if (constantValues.isEmpty()) {
                    result.setCode(500);
                    userLog.getLog("查询定值信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                    result.setMessage("没有配置信息");
                } else {
                    result.setCode(200);
                    result.setMessage("获取定值信息成功");
                    userLog.getLog("查询定值信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
                    result.setBody(constantValues);
                }
            }
        } catch (Exception e) {
            logger.error("获取定值异常，异常是" + e.toString());
            userLog.getLog("查询定值信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 0);
            result = PubUtils.assignmentResult(null, 500, "获取定值失败");
        }
        return result;
    }

    //定值更新数据库
    @RequestMapping(value = "updateDatabaseValue", method = RequestMethod.POST)
    @ResponseBody
    public int updateDatabaseValue(HttpServletRequest request, String json) throws AccountException {
        int result = 0;
        List<Integer> inoutVaule = new ArrayList<>();
        try {
            JSONObject jsonObject = JSONObject.fromObject(json); //使用net.sf.json.JSONObject对象来解析json
            //区分内/外定值
            String type = jsonObject.getString("type");
            if (type.equals("80")) {//外部定值
                int cpuNo = jsonObject.getInt("cpu_no");
                inoutVaule = jsonObject.getJSONArray("data");
                for (int i = 0; i < inoutVaule.size(); i++) {
                    Float value = (float) ((JSONArray) inoutVaule).getDouble(i);
                    //进行外部定值的更正
                    cvs.updateOut(cpuNo, '%' + type + '%', i + 1, value);
                }
                result = 1;
            } else if (type.equals("90")) {//内部定值
                String devtype = jsonObject.getString("dev_type");
                int devIndex = jsonObject.getInt("devindex");
                inoutVaule = jsonObject.getJSONArray("data");
                for (int i = 0; i < inoutVaule.size(); i++) {
                    int value = inoutVaule.get(i);
                    try {
                        if (i == inoutVaule.size() - 1 || i == inoutVaule.size() - 2) {
                            value = value / 100;
                            //进行内部定值的更正
                            cvs.updateIn(devIndex, '%' + type + '%', i + 1, value);
                        } else {
                            //进行内部定值的更正
                            cvs.updateIn(devIndex, '%' + type + '%', i + 1, value);
                            ConstantValue constantValue = cvs.getConvId(devIndex, type, i + 1);
                            String property = "";
                            //根据装置类型和sort进行查询
                            String pvIndex = constantValue.getPvIndex();
                            property = Integer.toBinaryString(value);
                            int strLen = property.length();
                            if (strLen < 16) {
                                while (strLen < 16) {
                                    StringBuffer sb = new StringBuffer();
                                    sb.append("0").append(property);//左补0
                                    property = sb.toString();
                                    strLen = property.length();
                                }
                            }
                            char[] ar = property.toCharArray();
                            for (int j = 0; j < ar.length; j++) {
                                int flag = ar[j] - 48;
                                pcwm.updateWord(pvIndex, flag, (ar.length - 1) - j);
                            }
                        }
                        result = 1;
                    } catch (Exception e) {
                        result = 0;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("定值存库异常，异常是" + e.toString());
            userLog.getLog("配置定值信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 2);
            result = 0;
        }
        return result;
    }

    //定值描述更新数据库
    @RequestMapping(value = "updateDatabase", method = RequestMethod.POST)
    @ResponseBody
    public int updateDatabase(HttpServletRequest request, int hander, int type, String json1) throws AccountException {
        int result = 0;
        try {
            JSONObject json = JSONObject.fromObject(json1); //使用net.sf.json.JSONObject对象来解析json
            //获取方法类型methodname
            String methodname = json.getString("methodname");
            List<ConstantValue> inoutVaule = new ArrayList<>();
            //hander 用于匹配 0 定值 1 定值描述
            int handers = json.getInt("hander");
            //用于判断内外定值 80外部定值 90内部定值
            if (handers == handers) {
                int devIndex = json.getInt("devindex");//终端id
                inoutVaule = json.getJSONArray("data");
                JSONObject json_test1 = JSONObject.fromObject(inoutVaule.get(0));
                int isint = 0;//用于判断时候删除子表数据
                String devtype1 = json_test1.getString("dev_type");
                String type2 = json_test1.getString("type");
                if (type == 90) {
                    //cvsm.deleteWord(devtype1);
                    cvsm.deleteValue(devIndex, '%' + type2 + '%');
                    isint = 1;
                } else if (type == 80) {
                    int lineIndex = Integer.parseInt(json.getString("lineindex"));
                    isint = 0;
                    cvsm.deleteOutValue(lineIndex, '%' + type2 + '%');
                }
                for (int i = 0; i < inoutVaule.size(); i++) {
                    String pvIndex = UUID.randomUUID().toString();
                    List<ProtectControlWord> property = new ArrayList<>();
                    JSONObject json_test = JSONObject.fromObject(inoutVaule.get(i));
                    //获取监测点序号、终端类型、定值类型、单位、最大值、最小值、默认值、设定值、描述
                    int cpuNo = json_test.getInt("cpu_no");
                    String devType = json_test.getString("dev_type");
                    int type1 = json_test.getInt("type");
                    int dzType = 0;
                    if(type == 80){
                         dzType = json_test.getInt("dz_type");
                    }
                    String unit = json_test.getString("unit");
                    Float maxValue = (float) json_test.getDouble("maxvalue");
                    Float minValue = (float) json_test.getDouble("minvalue");
                    Float defaultvalue = (float) json_test.getDouble("defaultvalue");
                    Float value = (float) json_test.getDouble("value");
                    String describe = json_test.getString("describe");
                    int sort = json_test.getInt("sort");
                    if (isint == 1) {
                        property = json_test.getJSONArray("property");
                    }
                    ConstantValue constantValue = new ConstantValue();
                    constantValue.setPvIndex(pvIndex);
                    constantValue.setCpuNo(cpuNo);
                    constantValue.setDevType(devType);
                    constantValue.setType(type1);
                    constantValue.setDzType(dzType);
                    constantValue.setUnit(unit);
                    constantValue.setMaxValue(maxValue);
                    constantValue.setMinValue(minValue);
                    constantValue.setDefaultValue(defaultvalue);
                    constantValue.setValue(value);
                    constantValue.setDescribe(describe);
                    constantValue.setSort(sort);
                    //存库
                    cvsm.insert(constantValue);
                    //获取内部定值控制字
                    if (isint == 1) {
                        if (property.size() > 1) {
                            for (int j = 0; j < property.size(); j++) {
                                JSONObject json_test2 = JSONObject.fromObject(property.get(j));
                                int typeNum = json_test2.getInt("type_num");
                                String bit0 = json_test2.getString("bit0");
                                String bit1 = json_test2.getString("bit1");
                                String describe1 = json_test2.getString("describe");
                                int flag = json_test2.getInt("flag");
                                ProtectControlWord protectControlWord = new ProtectControlWord();
                                protectControlWord.setPvIndex(pvIndex);
                                protectControlWord.setTypeNum(typeNum);
                                protectControlWord.setBit0(bit0);
                                protectControlWord.setBit1(bit1);
                                protectControlWord.setDescribe(describe1);
                                protectControlWord.setFlag(flag);
                                pcwm.insert(protectControlWord);
                            }
                        }
                    }
                }
                userLog.getLog("配置定值信息", "成功", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 1);
                result = 1;
            } else {
                userLog.getLog("配置定值信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 2);
                result = 0;
            }
        } catch (Exception e) {
            userLog.getLog("配置定值信息", "失败", PubUtils.getIpAddr(request), LogTypeEnum.SYSTEM.toString(), 2);
            logger.error("定值存库异常，异常是" + e.toString());
            result = 0;
        }
        return result;
    }


}
