<script setup lang="tsx">

import {storeToRefs} from "pinia";
import {Input} from "tdesign-vue-next";
import {Ref, ref, watch} from "vue";
import useExpr2Store from "@/store/expr2/expr2Store.ts";
import {Operation} from "@/store/expr2/defaultOperation.ts";

let expr2Store = useExpr2Store();
let {
    startTrack,
    operations,
    originOperations,
    tableChanged,
    currentTrack,
    trackFromIndex,
    trackToIndex,
    selectTrackFromIndex,
    selectTrackToIndex,
    tableUpdate
} = storeToRefs(expr2Store);
let data: Ref<{ key: string, id: number, track: number }[]> = ref<{
    key: string,
    id: number,
    track: number
}[]>([{track: startTrack.value, id: 0}, ...operations.value].map((operation: Operation, index: number) => {
    return {
        key: String(index + 1),
        id: operation.id,
        track: operation.track,
    }
}));

watch(tableUpdate, (newVal) => {
    if (newVal === false)
        return;
    data.value = [{track: startTrack.value, id: 0}, ...operations.value].map((operation: Operation, index: number) => {
        return {
            key: String(index + 1),
            id: operation.id,
            track: operation.track,
        }
    });
    tableUpdate.value = false;
});
let beforeKey = -1;
let beforeFromKey = -1;
let beforeToKey = -1;

function FindOriginOperationIndex(key: string): number {
    let index = parseInt(key) - 1;
    index = data.value[index].id;
    console.log("index", index)
    if (index === 0)
        return -1;
    for (let i = 0; i < originOperations.value.length; i++) {
        if (originOperations.value[i].id === index)
            return i;
    }
    return -1;
}

function OnTableBlur(col: number, {key: editedRowKey}: { key: string }, value: number | string) {
    console.log(editedRowKey);
    let index = FindOriginOperationIndex(editedRowKey);
    console.log(index, col, value)
    if (index === -1) {
        if (col === 2) {
            startTrack.value = value as number;
            tableChanged.value = true;
        }
        return;
    }
    switch (col) {
        case 1:
            originOperations.value[index].id = value as number;
            break;
        case 2:
            originOperations.value[index].track = value as number;
            break;
    }
    tableChanged.value = true;
}

const columns = [
    {
        title: '序号',
        colKey: 'key'
    },
    {
        title: '任务编号',
        colKey: 'id',
        edit: {
            component: Input,
            props: {
                clearable: true,
                autofocus: true,
                autoWidth: true,
            },
            rules: [
                {
                    required: true,
                    message: '不能为空',
                },
                {
                    pattern: /^\d+$/,
                    message: '请输入数字',
                }],
            on: ({colIndex, editedRow}: {
                colIndex: number,
                editedRow: { key: string }
            }) => ({
                onBlur: (value: number) => OnTableBlur(colIndex, editedRow, value)
            })
        }
    },
    {
        title: '目标磁道',
        colKey: 'track',
        edit: {
            component: Input,
            props: {
                clearable: true,
                autofocus: true,
                autoWidth: true,
            },
            rules: [
                {
                    required: true,
                    message: '不能为空',
                },
                {
                    pattern: /^\d+$/,
                    message: '请输入数字',
                }],
            on: ({colIndex, editedRow}: {
                colIndex: number,
                editedRow: { key: string }
            }) => ({
                onBlur: (value: number) => OnTableBlur(colIndex, editedRow, value)
            })
        }
    },
    {
        colKey: 'operation',
        title: '操作',
        width: 140
    }
];


function MouseEnter({row, index}: { row: { track: number }, index: number }) {
    beforeKey = currentTrack.value;
    beforeFromKey = trackFromIndex.value;
    beforeToKey = trackToIndex.value;
    currentTrack.value = row.track;
    trackFromIndex.value = Math.max(-1, index - 2);
    trackToIndex.value = index - 1;
}

function MouseLeave() {
    currentTrack.value = beforeKey;
}

// function MouseClick({row}: { row: { track: number } }) {
//     currentTrack.value = -1;
//     beforeKey = row.track;
//     currentTrack.value = beforeKey;
// }
function ActiveChange(rows: string[]) {
    console.log(rows);
    if (rows.length === 0)
        return;
    selectTrackFromIndex.value = parseInt(rows[0]) - 2;
    selectTrackToIndex.value = parseInt(rows[rows.length - 1]) - 2;
    if (selectTrackToIndex.value === selectTrackFromIndex.value) {
        if (selectTrackFromIndex.value >= 0 && selectTrackFromIndex.value < operations.value.length)
            beforeKey = operations.value[selectTrackFromIndex.value].track;
        else if (selectTrackFromIndex.value === -1)
            beforeKey = startTrack.value;
        else
            beforeKey = currentTrack.value;
    }
}

// row Error
function InsertBefore(row: number) {
    if (row === 1)
        originOperations.value.splice(0, 0, {
            id: 0,
            track: -1
        });
    else
        originOperations.value.splice(row - 2, 0, {
            id: 0,
            track: -1
        });
    tableChanged.value = true;
}

function InsertEnd() {
    originOperations.value.push({
        id: 0,
        track: -1
    });
    tableChanged.value = true;
}

// row Error
function Delete(row: number) {
    let key = data.value[row - 1].key;
    let index = FindOriginOperationIndex(key);
    originOperations.value.splice(index, 1);
    tableChanged.value = true;
}

</script>

<template>
    <div id="operations">
        <t-table row-key="key" :columns="columns" :data="data" :hover="true"
                 :resizable=true @row-mouseenter="MouseEnter" @row-mouseleave="MouseLeave" @active-change="ActiveChange"
                 :column-controller="{displayType: 'auto-width',hideTriggerButton: true}" :active-row-type="'single'">
            <template #operation="{ row }">
                <t-link style="display: inline" theme="primary" hover="color" @click="InsertBefore(parseInt(row.key))">
                    在之前插入
                </t-link>
                <t-link theme="primary" hover="color" @click.stop="Delete(parseInt(row.key))">
                    删除
                </t-link>
            </template>
        </t-table>
        <t-button @click="InsertEnd">新增一条操作</t-button>
    </div>
</template>

<style scoped lang="less">

</style>