package jtznyj.engineer.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jtznyj.common.api.ICommonApi;
import jtznyj.engineer.common.FileUtil;
import jtznyj.engineer.entity.BWellOwnEngineer;
import jtznyj.engineer.service.IBWellEngineerService;
import jtznyj.engineer.service.IWellDataDiagnosticService;
import jtznyj.engineer.service.dataDiagnosticService.models.AlarmType;
import jtznyj.engineer.service.dataDiagnosticService.models.DoorList;
import jtznyj.engineer.service.dataDiagnosticService.models.FieldRule;
import jtznyj.engineer.service.dataDiagnosticService.models.WellOwn;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import net.sf.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/engineer/template")
@Slf4j
public class EngineerTemplateController {
    @Autowired
    IBWellEngineerService ibWellEngineerService;
    @Autowired
    ICommonApi iCommonApi;

    @RequestMapping(value = "getWellOwnEngineer", method = RequestMethod.GET)
    public Result<?> getWellOwnEngineer(String jh) {
        HashMap<String, Object> temp = new HashMap();
        List<Map<String, Object>> list = iCommonApi.queryDefaultEngineerLogic();
        if (list.size() == 0) {
            list = iCommonApi.queryWellEngineerLogic(jh);
        }

        String json = IWellDataDiagnosticService.GetNClobWithColorChange(list.get(0).get("LARGETEXT"));

        /**
         * 新功能增加项数据处理
         */
        WellOwn wellOwn = JSON.parseObject(json, WellOwn.class);
        for (AlarmType type : wellOwn.AlarmTypeList) {
            for (FieldRule rules : type.FieldRules) {
                if (rules.doorList.size() == 0) {
                    DoorList doorList = new DoorList();
                    rules.doorList.add(doorList);
                }
            }
        }
        String json2 = JSON.toJSONString(wellOwn);
        //初始化预警参数列表


        temp.put("template", json2);
        Result<HashMap<String, Object>> result = new Result();
        result.setResult(temp);
        return result;
    }


    @RequestMapping(value = "saveEngineer", method = RequestMethod.POST)
    public Result<String> saveWellEngineerTemplate(@RequestBody BWellOwnEngineer form) {
        Result<String> result = new Result<>();
        try {
            QueryWrapper<BWellOwnEngineer> queryWrapper = new QueryWrapper<BWellOwnEngineer>();
            queryWrapper.eq("jh", form.getJh());
            int count = ibWellEngineerService.count(queryWrapper);
            BWellOwnEngineer t = new BWellOwnEngineer();
            t.setJh(form.getJh());
            t.setLargeText(form.getLargeText());
            t.setCreateBy("wd");
            t.setUpdateBy("wx");
            if (count == 0) {
                ibWellEngineerService.save(t);
            } else {
//                UpdateWrapper<BWellOwnEngineer> updateWrapper = new UpdateWrapper<>();
//                updateWrapper.eq("JH",form.getJh());
//                updateWrapper.set("UPDATE_BY","wx");
//                updateWrapper.set("LARGE_TEXT",form.getLargeText());
                ibWellEngineerService.update(t, queryWrapper);
            }
            this.saveEngineerJson(form.getLargeText());
            result.success("保存成功");
        } catch (Exception ex) {
            result.error500("保存失败");
        }
        return result;
    }

    @RequestMapping(value = "revertEngineer", method = RequestMethod.GET)
    public Result<String> revertEngineer(@RequestParam(value = "jh") String jh) {
        Result<String> result = new Result<>();
        try {
            if (StringUtils.isNotEmpty(jh)) {
                QueryWrapper<BWellOwnEngineer> queryWrapper = new QueryWrapper<BWellOwnEngineer>();
                queryWrapper.eq("jh", jh);
                ibWellEngineerService.remove(queryWrapper);
                result.success("恢复默认成功");
            } else {
                result.error500("井号不允许为空");
            }
        } catch (Exception ex) {
            result.error500("恢复默认失败");
        }
        return result;
    }

    /**
     * 将颜色写入文件（领导的需求）
     */
    private void saveEngineerJson(String json) {
        try {
            String FileJson = FileUtil.read();

            Map FileMap = JSON.parseObject(FileJson);

            Map mapTypes = JSON.parseObject(json);
//                System.out.println(mapTypes.get("AlarmTypeList"));
            List<Map<String, Object>> typeList = (List<Map<String, Object>>) mapTypes.get("AlarmTypeList");
            for (Map<String, Object> type : typeList) {
                if (type.get("curveColor") == null) {
                    type.put("curveColor", "#e2534d");
                }
                FileMap.put(type.get("name"), type.get("curveColor"));
            }

            JSONObject jsonObject = JSONObject.fromObject(FileMap);
            FileUtil.write(jsonObject.toString());
        } catch (Exception e) {

        }
    }

    /**
     * 恢复默认预警模板
     *
     * @return
     */
    @RequestMapping(value = "restoreDefault", method = RequestMethod.POST)
    public Result<String> restoreDefault() {
        Result<String> result = new Result<>();
        try {
            QueryWrapper<BWellOwnEngineer> queryWrapper = new QueryWrapper<BWellOwnEngineer>();
            queryWrapper.eq("jh", "默认");
            BWellOwnEngineer engineer = ibWellEngineerService.getOne(queryWrapper);

            QueryWrapper<BWellOwnEngineer> backupsWrapper = new QueryWrapper<BWellOwnEngineer>();
            backupsWrapper.eq("jh", "恢复默认模型");
            BWellOwnEngineer backupsEngineer = ibWellEngineerService.getOne(backupsWrapper);

            if (backupsEngineer != null && engineer != null) {
                engineer.setLargeText(backupsEngineer.getLargeText());
                ibWellEngineerService.update(engineer, queryWrapper);
            }

            result.success("保存成功");
        } catch (Exception ex) {
            result.error500("保存失败");
        }
        return result;
    }

    /**
     * 保存默认模板
     * 需求: 点到第二层时只改当前对象，其他数据不做更改
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "saveDefault", method = RequestMethod.POST)
    public Result<String> saveDefault(@RequestBody Map<String, Object> template) {
        Result<String> result = new Result<>();
        try {
            QueryWrapper<BWellOwnEngineer> queryWrapper = new QueryWrapper<BWellOwnEngineer>();
            queryWrapper.eq("jh", "默认");
            BWellOwnEngineer engineer = ibWellEngineerService.getOne(queryWrapper);

            FieldRule fieldRule = JSON.parseObject(template.get("template").toString(), FieldRule.class);
            Integer modelKey = new Integer(template.get("modelKey").toString());
            Integer paramKey = new Integer(template.get("paramKey").toString());

            WellOwn wellOwn = JSON.parseObject(engineer.getLargeText(), WellOwn.class);

            if (wellOwn.AlarmTypeList.get(modelKey) != null && wellOwn.AlarmTypeList.get(modelKey).FieldRules.size() < paramKey + 1) {
                wellOwn.AlarmTypeList.get(modelKey).FieldRules.add(fieldRule);
                engineer.setLargeText(JSON.toJSONString(wellOwn));
                ibWellEngineerService.update(engineer, queryWrapper);
                return result.success("保存成功");
            }


            if (wellOwn.AlarmTypeList.get(modelKey) != null && wellOwn.AlarmTypeList.get(modelKey).FieldRules.get(paramKey) != null) {
                wellOwn.AlarmTypeList.get(modelKey).FieldRules.set(paramKey, fieldRule);
            }
            engineer.setLargeText(JSON.toJSONString(wellOwn));
            ibWellEngineerService.update(engineer, queryWrapper);

            result.success("保存成功");
        } catch (Exception ex) {
            System.out.println(ex);
            result.error500("保存失败");
        }
        return result;
    }
}
