package com.lsw.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.lsw.utils.TimeUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class IndexController extends Controller {

    public void index() {
        long start = System.currentTimeMillis();
        String table = getPara("table", "TLK_MYJCS");
        String ITEM_VALUE = getPara("ITEM_VALUE");
        String bh = getPara("bh", "102");
        String type = getPara("type", "form");
        String user = getPara("user", "基栋");
        set("look", getPara("look"));
        List<Record> all = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        Record v = Db.findFirst("SELECT ITEM_VERSION,ITEM_BH,ITEM_NAME FROM TLK_MYJCS WHERE ITEM_XL_NUM=? and ITEM_UPBH IS  NULL ORDER BY ITEM_VERSION DESC", bh);
        sb.append("SELECT ID,ITEM_BH,ITEM_PX,ITEM_NAME,ITEM_UPBH,ITEM_TYPE FROM " + table);
        if (type.equals("form")) {
            sb.append(" WHERE ITEM_KEY=?");
        }
        if (type.equals("json")) {
            sb.append(" WHERE ITEM_XL_NUM=?");
            sb.append(" AND ITEM_VERSION=?");
        }
        sb.append(" AND ITEM_UPBH IS NOT NULL");
        if (StrKit.notBlank(ITEM_VALUE)) {
            sb.append(" AND ITEM_VALUE=?");
            sb.append(" ORDER BY ITEM_PX ASC");
            all = Db.find(sb.toString(), bh, ITEM_VALUE);
        } else {
            sb.append(" ORDER BY TO_NUMBER(ITEM_PX) ASC");
            if (type.equals("json")) {
                all = Db.find(sb.toString(), bh, v.getStr("ITEM_VERSION"));
            } else {
                all = Db.find(sb.toString(), bh);
            }

        }
        List<Record> list = all.stream().filter(r -> r.getStr("ITEM_UPBH").equals(type.equals("form") ? bh : v.getStr("ITEM_BH"))).collect(Collectors.toList());
        for (Record record : list) {
            int rowspan = 0; //总的合并行
            record.set("type", 0);
            //二级
            List<Record> list2 = all.stream().filter(r -> r.getStr("ITEM_UPBH").equals(record.getStr("ITEM_BH"))).collect(Collectors.toList());
            record.set("child", list2);
            rowspan++;
            for (Record record2 : list2) {
                int rowspan2 = 0; //二级合并行
                //三级
                List<Record> list3 = all.stream().filter(r -> r.getStr("ITEM_UPBH").equals(record2.getStr("ITEM_BH"))).collect(Collectors.toList());
                record2.set("child", list3);
                rowspan++;
                rowspan2++;
                for (Record record3 : list3) {
                    //四级
                    List<Record> list4 = all.stream().filter(r -> r.getStr("ITEM_UPBH").equals(record3.getStr("ITEM_BH"))).collect(Collectors.toList());
                    if (!list4.isEmpty()) {
                        record.set("type", 1);
                    }
                    if (record3.getStr("ITEM_TYPE").equals("1")) {
                        rowspan++;
                        rowspan2++;
                    }
                    for (Record record4 : list4) {
                        if (record4.getStr("ITEM_TYPE").equals("1")) {
                            rowspan++;
                            rowspan2++;
                        }
                        //五级
                        List<Record> list5 = all.stream().filter(r -> r.getStr("ITEM_UPBH").equals(record4.getStr("ITEM_BH"))).collect(Collectors.toList());
                        if (!list5.isEmpty()) {
                            record.set("type", 1);
                            record2.set("type", 1);
                        }
                        record4.set("child", list5);
                    }
                    record3.set("child", list4);
                }
                record2.set("rowspan2", rowspan2);
            }
            record.set("rowspan", rowspan);
        }
        long end = System.currentTimeMillis();
        if (type.equals("form")) {
            setAttr("list", list);
            setAttr("table", table);
            setAttr("user", user);
            setAttr("time", mul((end - start), (float) 0.001) + "s");
            render("index.html");
        } else {
            Record record = new Record();
            record.set("code", 200);
            record.set("msg", "请求成功");
            record.set("time", mul((end - start), (float) 0.001) + "s");
            Record child = new Record();
            child.set("ITEM_NAME", v.getStr("ITEM_NAME"));
            child.set("ITEM_XL_NUM", bh);
            child.set("ITEM_VERSION", v.getStr("ITEM_VERSION"));
            child.set("data", list);
            record.set("data", child);
            renderJson(record);
        }
    }

    public void edit() {
        if (StrKit.isBlank(getPara("ITEM_NAME")) && StrKit.isBlank(getPara("ID"))) {
            renderJson(new Record().set("code", 500));
            return;
        }
        String table = getPara("table", "TLK_YJCS");

        Record record = Db.findFirst("SELECT * FROM " + table + " WHERE ID=?", getPara("ID"));
        JSONArray log_list = new JSONArray();
        if (record.get("ITEM_TLOG") == null) {
            //原记录
            Record log = new Record();
            log.set("DAY", "原记录");
            log.set("ITEM_NAME", record.getStr("ITEM_NAME"));
            log_list.add(log);
        } else {
            log_list = JSON.parseArray(record.get("ITEM_TLOG"));
        }
        //编辑记录
        Record log = new Record();
        log.set("DAY", StrKit.isBlank(getPara("day")) ? TimeUtil.getNow() : getPara("day"));
        log.set("ITEM_NAME", getPara("ITEM_NAME"));
        log.set("USER", getPara("user"));
        log_list.add(log);

        Record update = new Record();
        update.set("ITEM_NAME", getPara("ITEM_NAME"));
        update.set("ID", getPara("ID"));
        update.set("ITEM_TLOG", JsonKit.toJson(log_list));
        boolean result = Db.update(table, "ID", update);

        if (record.get("ITEM_FID") != null) {
            Record TLK_MYJCS = Db.findFirst("SELECT * FROM TLK_MYJCS WHERE ID=?", record.getStr("ITEM_FID"));
            JSONArray log_list2 = new JSONArray();
            if (TLK_MYJCS.get("ITEM_TLOG") == null) {
                //原记录
                Record log2 = new Record();
                log2.set("DAY", "原记录");
                log2.set("ITEM_NAME", TLK_MYJCS.getStr("ITEM_NAME"));
                log_list2.add(log2);
            } else {
                log_list2 = JSON.parseArray(TLK_MYJCS.get("ITEM_TLOG"));
            }
            update.set("ID", record.get("ITEM_FID"));
            log_list2.add(log);
            update.set("ITEM_TLOG", JsonKit.toJson(log_list2));
            Db.update("TLK_MYJCS", "ID", update);
        }
        renderJson(new Record().set("code", result ? 200 : 500));
    }

    @Before(Tx.class)
    public void move() {
        String table = getPara("table", "TLK_YJCS");
        String op = getPara("op", "add"); //操作上移，下移
        String id = getPara("id");
        Record up = Db.findFirst("SELECT * FROM " + table + " WHERE ID=? ", id);
        List<Record> list = Db.find("SELECT * FROM " + table + " WHERE ITEM_UPBH=? ORDER BY ITEM_PX ASC", up.getStr("ITEM_UPBH"));
        if (up.getStr("ITEM_PX") == null) {
            up.set("ITEM_PX", 0);
        }
        for (Record r : list) {
            if (r.getStr("ITEM_PX") == null) {
                r.set("ITEM_PX", 0);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            if (op.equals("add") && up.getStr("ID").equals(list.get(i).getStr("ID"))) {
                Db.update("UPDATE " + table + " SET ITEM_PX=? WHERE ID=?", Integer.parseInt(up.getStr("ITEM_PX")) - 1, up.getStr("ID"));
                Db.update("UPDATE " + table + " SET ITEM_PX=? WHERE ID=?", Integer.parseInt(list.get(i - 1).getStr("ITEM_PX")) + 1, list.get(i - 1).getStr("ID"));
                break;
            }
            if (op.equals("down") && up.getStr("ID").equals(list.get(i).getStr("ID"))) {
                System.out.println("ITEM_PX：" + list.get(i).getStr("ITEM_PX"));
                System.out.println("索引：" + i);
                Db.update("UPDATE " + table + " SET ITEM_PX=? WHERE ID=?", Integer.parseInt(up.getStr("ITEM_PX")) + 1, up.getStr("ID"));
                Db.update("UPDATE " + table + " SET ITEM_PX=? WHERE ID=?", Integer.parseInt(list.get(i + 1).getStr("ITEM_PX")) - 1, list.get(i + 1).getStr("ID"));
                break;
            }
        }
        renderJson(new Record().set("code", 200));
    }

    public void log() {
        String table = getPara("table", "TLK_YJCS");
        Record record = Db.findFirst("SELECT * FROM " + table + " WHERE ID=?", getPara("ID"));
        renderJson(record.getStr("ITEM_TLOG"));
    }

    private double mul(long v1, float v2) {
        BigDecimal b1 = new BigDecimal(Float.toString(v1));
        BigDecimal b2 = new BigDecimal(Float.toString(v2));
        return b1.multiply(b2).doubleValue();
    }
}