<template>
  <Layout>
    <template #sidebar>
      <div class="ks-sidebar-header">
        <a-flex class="ks-sidebar-title">
          <span class="icon"></span>
          <span class="text">指挥决策规则库管理</span>
        </a-flex>
        <a-button class="ks-sidebar-add" size="small" @click="handleCreate">
          <PlusOutlined />
          新增
        </a-button>
      </div>
      <a-list item-layout="horizontal" :data-source="algorithms" class="ks-sidebar-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-sidebar-list-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-algorithm-card">

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

        <div class="ks-scrollable" style="height: 80.5vh;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 placeholder="请选择业务类型" 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: 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-sidebar-list-param-list">
                      <div class="ks-sidebar-list-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-sidebar-list-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
                  label="算法配置"
                  :rules="[{ required: false, message: '请输入算法配置', trigger: ['input', 'change'] }]"
                  :name="['algoConfig']"
                >
                  <a-form-item-rest>
                    <div class="ks-sidebar-list-param-list">
                      <div class="ks-sidebar-list-param-item" v-for="(t,index) in selectedAlgorithm.algoConfigList">
                        <a-row :gutter="15">
                          <a-col :span="7">
                            <a-select placeholder="请选择参数" v-model:value="t.name" @change="(v: any)=> t.name = v">
                              <a-select-option :value="v.paramName" v-for="v in selectedAlgorithm.algorithmParamList">{{v.paramName}}</a-select-option>
                            </a-select>
                          </a-col>
                          <a-col :span="7">
                            <a-select placeholder="请选择操作" v-model:value="t.operation" @change="(v: any)=> t.operation = v">
                              <a-select-option :value="o.type" v-for="o in algorithmConfigOperations">{{o.name}} {{o.type}}</a-select-option>
                            </a-select>
                          </a-col>
                          <a-col :span="3">
                            <a-space class="ks-sidebar-list-param-actions">
                              <MinusCircleOutlined @click="()=> handleMinusConfig(index)" />
                              <PlusCircleOutlined @click="handleAddConfig" 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" type="primary">保存规则</a-button>
                    <a-popconfirm
                      v-if="selectedAlgorithm && selectedAlgorithm.id > 0"
                      title="确定运行?"
                      @confirm="handleRun"
                    >
                      <a-button>运行规则</a-button>
                    </a-popconfirm>
                    <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, runAlgorithm } from './api';
import type { Algorithm, AlgorithmParam, AlgorithmRequest } from './types';
import { substring } from '@/utils/strings';
import { algorithmTypes,algorithmConfigOperations } 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,
  // 算法配置
  algoConfigList: [],
  // 算法参数定义信息
  algorithmParamList: [
    { ...defaultAlgorithmParam },
  ],
};


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

  try{
    newItem.algoConfigList = JSON.parse(newItem.algoConfigList)
  } catch (e: any){
    console.error(e);
  }

  if(!newItem.algoConfigList){
    newItem.algoConfigList = []
  }

  if(newItem.algoConfigList.length === 0){
    newItem.algoConfigList.push({
      name: undefined,
      operation: undefined,
    })
  }
  return newItem;
};

const algorithms = ref<Algorithm[]>([]);
const algorithmsTotal = ref<number>(0);
const selectedAlgorithm = ref<Algorithm>(resolveItem(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;

  if(selectedAlgorithm.value.id <= 0){
    formRef.value?.resetFields();
    selectedAlgorithm.value = resolveItem(defaultAlgorithm);
  }

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


const handleCreate = () => {
  selectedAlgorithm.value = resolveItem(defaultAlgorithm);
};

const handleSelect = (item: Algorithm) => {
  selectedAlgorithm.value = resolveItem(item);
  formRef.value?.resetFields();
};

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 handleAddConfig = () => {
  selectedAlgorithm.value.algoConfigList.push({ name: null, operation: null });
};

const handleMinusConfig = (index: number) => {
  const paramList = selectedAlgorithm.value.algoConfigList;
  if (index === 0 && selectedAlgorithm.value.algoConfigList.length === 1) {
    selectedAlgorithm.value.algoConfigList = [{ name: null, operation: null }];
  } else if (index >= 0 && index < paramList.length && paramList.length > 1) {
    paramList.splice(index, 1);
    selectedAlgorithm.value.algoConfigList = [...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;
      let savedValue: Algorithm = JSON.parse(JSON.stringify(selectedAlgorithm.value)) as any as Algorithm;
      let algoConfig = '';
      if( savedValue.algoConfigList ){
        savedValue.algoConfigList.forEach(o=> {
          if(o.name){
            algoConfig = algoConfig + o.name;
          }
          if(o.operation){
            algoConfig = algoConfig + o.operation;
          }
        })
      }
      savedValue.algoConfig = algoConfig;

      if (savedValue.id > 0) {
        res = updateAlgorithm(savedValue);
      } else {
        res = createAlgorithm(savedValue);
      }

      if (res) {
        res.then(r => {
          if (r.code === 200) {
            load();
            message.info(r.msg ?? '操作成功');
          } else {
            message.error(r.msg ?? '操作失败');
          }
        });
      }
    });
  }
};

const handleRun = ()=> {
  if (formRef.value) {
    formRef.value.validate().then(() => {
      runAlgorithm(selectedAlgorithm.value).then(r => {
        if (r.code === 200) {
          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>
