<template>
  <Layout>
    <template #sidebar>
      <div class="ks-sidebar-header">
        <span class="ks-sidebar-title">指挥决策规则库管理</span>
        <a-button class="ks-sidebar-add" size="small" @click="handleCreate">
          <PlusOutlined />
          新增
        </a-button>
      </div>
      <a-list item-layout="horizontal" :data-source="algorithms" class="ks-algorithm-list">
        <template #renderItem="{ item }">
          <a-list-item @click="()=> handleSelect(item)" :class="selectedAlgorithm?.id === item.id ? 'selected' : null">
            <a-list-item-meta :description="substring(item.description,20)">
              <template #title>
                <span class="ks-algorithm-name">{{ substring(item.name, 20) }}</span>
                <span class="ks-algorithm-type"><a-badge size="small" :count="getAlgorithmTypeName(item.type)"></a-badge></span>
              </template>
            </a-list-item-meta>
          </a-list-item>
        </template>
      </a-list>

      <a-pagination
        v-model:current="query.pageNum"
        :page-size="query.pageSize"
        :total="algorithmsTotal"
        simple size="small" @change="handleChange" />
    </template>

    <div class="w-full h-full">

      <a-card class="ks-page-card ks-workspace-card ks-algorithm-card">

        <template #title>
          <a-space>
            <span class="point"></span>
            <span class="text">规则配置</span>
          </a-space>
        </template>

        <div class="ks-scrollable" style="height: 79vh;overflow-y: auto;padding-right: 10px">

          <a-row :gutter="15">
            <a-col :span="16">
              <a-form
                ref="formRef"
                :label-col="{span: 6}"
                :model="selectedAlgorithm"
                autocomplete="off"
                layout="horizontal"
                name="basic"
              >

                <a-form-item
                  label="规则名称"
                  :rules="[{ required: true, message: '请输入算法名称!', trigger: ['input', 'change'] }]"
                  :name="['name']"
                >
                  <a-input v-model:value="selectedAlgorithm.name" placeholder="请输入算法名称" />
                </a-form-item>

                <a-form-item
                  label="业务类型"
                  :rules="[{ required: true, message: '请输入业务类型!', trigger: ['input', 'change'] }]"
                  :name="['type']"
                >
                  <a-select allow-clear v-model:value="selectedAlgorithm.type" @change="(v: any)=> selectedAlgorithm.type = v">
                    <a-select-option v-for="a in algorithmTypes" :value="a.type">{{ a.name }}</a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item
                  label="算法文件路径"
                  :rules="[{ required: true, message: '请输入算法文件路径!', trigger: ['input', 'change'] }]"
                  :name="['codePath']"
                >
                  <a-input v-model:value="selectedAlgorithm.codePath" placeholder="请输入算法文件路径" />
                </a-form-item>

                <a-form-item
                  label="算法配置"
                  :rules="[{ required: true, message: '请输入算法配置', trigger: ['input', 'change'] }]"
                  :name="['algoConfig']"
                >
                  <a-textarea v-model:value="selectedAlgorithm.algoConfig" placeholder="请输入算法配置" />
                </a-form-item>

                <a-form-item
                  label="算法描述"
                  :rules="[{ required: false, message: '请输入算法描述', trigger: ['input', 'change'] }]"
                  :name="['description']"
                >
                  <a-textarea v-model:value="selectedAlgorithm.description" placeholder="请输入算法描述" />
                </a-form-item>

                <a-form-item
                  label="算法参数定义"
                  :rules="[{ required: true, message: '请输入算法参数定义', trigger: ['input', 'change'] }]"
                  :name="['algorithmParamList']"
                >
                  <a-form-item-rest>
                    <div class="ks-algorithm-param-list">
                      <div class="ks-algorithm-param-item" v-for="(item,index) in selectedAlgorithm.algorithmParamList">
                        <a-row :gutter="15">
                          <a-col :span="7">
                            <a-input v-model:value="item.paramName" placeholder="请输入参数名" />
                          </a-col>
                          <a-col :span="7">
                            <a-input v-model:value="item.defaultValue" placeholder="请输入默认值" />
                          </a-col>
                          <a-col :span="7">
                            <a-input v-model:value="item.description" placeholder="请输入描述" />
                          </a-col>
                          <a-col :span="3">
                            <a-space class="ks-algorithm-param-actions">
                              <MinusCircleOutlined @click="()=> handleMinus(index)" />
                              <PlusCircleOutlined @click="handleAdd" v-if="index === 0" />
                            </a-space>
                          </a-col>
                        </a-row>
                      </div>
                    </div>
                  </a-form-item-rest>
                </a-form-item>

                <a-form-item
                  :wrapper-col="{offset: 6}"
                >
                  <a-space>
                    <a-button @click="handleSave">保存规则</a-button>
                    <a-popconfirm
                      v-if="selectedAlgorithm && selectedAlgorithm.id > 0"
                      title="确定删除?"
                      @confirm="handleDelete"
                    >
                      <a-button danger>删除规则</a-button>
                    </a-popconfirm>
                  </a-space>
                </a-form-item>

              </a-form>
            </a-col>
          </a-row>

        </div>

      </a-card>

    </div>
  </Layout>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { type FormInstance, message } from 'ant-design-vue';
import { MinusCircleOutlined, PlusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
import Layout from '../layout.vue';
import { createAlgorithm, deleteAlgorithm, findAlgorithmsByQuery, updateAlgorithm } from './api';
import type { Algorithm, AlgorithmParam, AlgorithmRequest } from './types';
import { substring } from '@/utils/strings';
import { algorithmTypes } from './config';
import type { NullableString } from '@/types';

const query = ref<Partial<AlgorithmRequest>>({
  pageNum: 1,
  pageSize: 10,
});

const defaultAlgorithmParam: AlgorithmParam = {
  id: 0,
  algorithmId: 0,
  // 参数名
  paramName: null,
  // 默认值
  defaultValue: null,
  // 描述
  description: null,
};
const defaultAlgorithm: Algorithm = {
  id: 0,
  // 算法名称
  name: null,
  // 业务类型
  type: undefined,
  // 算法文件路径
  codePath: null,
  // 算法描述
  description: null,
  // 算法配置
  algoConfig: null,
  // 算法参数定义信息
  algorithmParamList: [
    { ...defaultAlgorithmParam },
  ],
};
const algorithms = ref<Algorithm[]>([]);
const algorithmsTotal = ref<number>(0);
const selectedAlgorithm = ref<Algorithm>(JSON.parse(JSON.stringify(defaultAlgorithm)));
const formRef = ref<FormInstance | null>(null);

const getAlgorithmTypeName = (type: NullableString): NullableString => {
  let v = algorithmTypes.find(c => c.type === type);
  return v && v.name ? v.name : type;
};

const load = () => {
  algorithms.value = [];
  algorithmsTotal.value = 0;
  formRef.value?.resetFields();
  selectedAlgorithm.value = JSON.parse(JSON.stringify(defaultAlgorithm));

  findAlgorithmsByQuery(query.value).then(r => {
    algorithms.value = r.rows ?? [];
    algorithmsTotal.value = r.total ?? 0;
  });
};

const handleCreate = () => {
  selectedAlgorithm.value = JSON.parse(JSON.stringify(defaultAlgorithm));
};

const handleSelect = (item: Algorithm) => {
  let newItem = JSON.parse(JSON.stringify(item))
  if (!newItem.algorithmParamList) {
    newItem.algorithmParamList = [];
  }
  if (newItem.algorithmParamList.length === 0) {
    newItem.algorithmParamList.push({ ...defaultAlgorithmParam });
  }
  selectedAlgorithm.value = newItem;
};

const handleAdd = () => {
  selectedAlgorithm.value.algorithmParamList.push({ ...defaultAlgorithmParam });
};

const handleMinus = (index: number) => {
  const paramList = selectedAlgorithm.value.algorithmParamList;
  if (index === 0 && selectedAlgorithm.value.algorithmParamList.length === 1) {
    selectedAlgorithm.value.algorithmParamList = [{ ...defaultAlgorithmParam }];
  } else if (index >= 0 && index < paramList.length && paramList.length > 1) {
    paramList.splice(index, 1);
    selectedAlgorithm.value.algorithmParamList = [...paramList];
  }
};

const handleDelete = () => {
  if (selectedAlgorithm.value && selectedAlgorithm.value.id > 0) {
    deleteAlgorithm(selectedAlgorithm.value.id).then(r => {
      if (r.code === 200) {
        load();
        message.info(r.msg ?? '删除成功');
      } else {
        message.error(r.msg ?? '删除失败');
      }
    });
  }
};

const handleSave = () => {
  if (formRef.value) {
    formRef.value.validate().then(() => {
      let res = null;
      if (selectedAlgorithm.value.id > 0) {
        res = updateAlgorithm(selectedAlgorithm.value);
      } else {
        res = createAlgorithm(selectedAlgorithm.value);
      }
      if (res) {
        res.then(r => {
          if (r.code === 200) {
            load();
            message.info(r.msg ?? '操作成功');
          } else {
            message.error(r.msg ?? '操作失败');
          }
        });
      }
    });
  }
};

const handleChange = (page: number, pageSize: number) => {
  query.value.pageNum = page;
  query.value.pageSize = pageSize;
  load();
};

onMounted(() => load());

</script>

<style lang="less">
.ks-algorithm-card {
  .ant-card-head-title {
    span.text {
      display: block;
      line-height: 30px;
    }
  }
}

.ks-sidebar-header {
  height: 50px;
  line-height: 40px;
  padding: 5px 15px;
  background: #081d36;

  .ks-sidebar-title {
    color: #7ae8fc;
    font-size: 16px;
  }

  .ks-sidebar-add {
    position: absolute;
    right: 15px;
    top: 14px;
    font-size: 12px;

    .anticon {
      display: block;
      float: left;
      line-height: 16px;
    }
  }
}

.ant-list {
  &.ks-algorithm-list {
    .ant-list-item {
      cursor: pointer;
      transition: all 0.5s;
      border-left: 2px solid transparent;
      position: relative;

      &.selected,
      &:hover {
        background: #0a1b3c;
        border-left: 2px solid #11377e;
      }
    }

    .ks-algorithm-type {
      position: absolute;
      right: 10px;

      .ant-badge {
        .ant-badge-count {
          color: #c3c2c2;
          background: #333f7d;
          box-shadow: 0 0 0 1px #325478;
        }
      }
    }

    .ant-list-item-meta {
      .ant-list-item-meta-title {
        color: #7ae8fc;
      }

      .ant-list-item-meta-description {
        color: #4d8c98;
        font-size: 13px;
      }
    }
  }
}

.ks-algorithm-param-list {
  padding: 15px;
  border: 1px solid #475f71;
  border-radius: 2px;

  .ks-algorithm-param-item {
    margin-bottom: 15px;

    &:last-child {
      margin-bottom: 0;
    }
  }

}


.ks-algorithm-param-actions {
  .anticon {
    color: #7ae8fc;
    font-size: 20px;
    display: block;
    line-height: 26px;
    cursor: pointer;
  }
}
</style>