<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="指标自动ID" prop="autoId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.autoId"-->
      <!--          placeholder="请输入指标自动ID"-->
      <!--          clearable-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="算法名称" prop="algoId">
        <el-select v-model="queryParams.algoId" placeholder="请选择算法" style="width: 260px" clearable
                   filterable remote reserve-keyword>
          <el-option
              v-for="dict in algoList"
              :key="dict.algoId"
              :label="dict.algoName"
              :value="dict.algoId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="定时分析" prop="timeSwitch">
        <el-select v-model="queryParams.timeSwitch" placeholder="请选择定时分析" clearable>
          <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否告警" prop="alarmWitch">
        <el-select v-model="queryParams.alarmWitch" placeholder="请选择是否告警" clearable>
          <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleSelect"
        >选择指标
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            type="success"-->
      <!--            plain-->
      <!--            icon="Edit"-->
      <!--            :disabled="single"-->
      <!--            @click="handleUpdate"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="analyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="分析ID" align="center" prop="analyId" />-->
      <el-table-column label="算法名称" align="center" prop="algoName"/>
      <el-table-column label="模型名称" align="center" prop="modelName"/>
      <el-table-column label="指标名称" align="center" prop="metricsName"/>
      <el-table-column label="对象类型" align="center" prop="objType"/>
      <el-table-column label="对象名称" align="center" prop="objName"/>
      <el-table-column label="是否告警" align="center" prop="alarmWitch">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.alarmWitch"/>
        </template>
      </el-table-column>
      <el-table-column label="定时分析" align="center" prop="timeSwitch">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.timeSwitch"/>
        </template>
      </el-table-column>
      <el-table-column label="执行周期" align="center" prop="scheduleCycle"/>
      <el-table-column label="上次执行时间" align="center" prop="lastTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastTime, '{y}-{m}-{d} {h}:{mi}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="指标恶化包含关键字" align="center" prop="alarmKey"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">配置算法</el-button>
          <el-button link type="primary" icon="DataAnalysis" v-if="scope.row.algoId!=null"
                     @click="handleAnaly(scope.row)">立即分析
          </el-button>
          <el-button link type="primary" icon="Grid" v-if="scope.row.algoId!=null" @click="handleHistory(scope.row)">
            历史记录
          </el-button>
          <el-button link type="primary" icon="Delete" v-if="scope.row.algoId==null" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改模型指标分析对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="analyRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="10" :xs="24">
            <el-form-item label="算法名称">
              {{ form.algoName }}
            </el-form-item>
            <el-form-item label="模型名称">
              {{ form.modelName }}
            </el-form-item>
            <el-form-item label="指标名称">
              {{ form.metricsName }}
            </el-form-item>
            <el-form-item label="对象类型">
              {{ form.objType }}
            </el-form-item>
            <el-form-item label="对象名称">
              {{ form.objName }}
            </el-form-item>
            <el-form-item label="告警说明">
              <el-alert
                  title="启用告警后，系统将在满足算法返回结果包含选择的关键字时，在运行风险监测系统中产生告警记录。"
                  type="warning"
                  show-icon
                  :closable="false"
                  style="margin-top: 10px;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="14" :xs="24">
            <!--          <el-table-column label="算法名称" align="center" prop="algoName"/>-->
            <!--          <el-table-column label="模型名称" align="center" prop="modelName"/>-->
            <!--          <el-table-column label="指标名称" align="center" prop="metricsName"/>-->
            <!--          <el-table-column label="对象类型" align="center" prop="objType"/>-->
            <!--          <el-table-column label="对象名称" align="center" prop="objName"/>-->
            <!--          <el-input v-model="form.autoId" placeholder="请输入指标自动ID"/>-->
            <el-form-item label="指标自动ID" prop="autoId">
              <el-text v-model="form.autoId" placeholder="请输入指标自动ID"/>
            </el-form-item>
            <el-form-item label="算法名称" prop="algoId">
              <el-select v-model="form.algoId" placeholder="请选择算法" style="width: 260px" clearable filterable remote
                         reserve-keyword @change="handleAlgoChange">
                <el-option
                    v-for="dict in algoList"
                    :key="dict.algoId"
                    :label="dict.algoName"
                    :value="dict.algoId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="定时分析" prop="timeSwitch">
              <el-select v-model="form.timeSwitch" placeholder="请选择定时分析">
                <el-option
                    v-for="dict in sys_yes_no"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="执行周期（天）" prop="scheduleCycle">
              <el-input-number v-model="form.scheduleCycle" placeholder="请输入执行周期" :min="1"/>
            </el-form-item>
            <!--        <el-form-item label="上次执行时间" prop="lastTime">-->
            <!--          <el-date-picker clearable-->
            <!--                          v-model="form.lastTime"-->
            <!--                          type="date"-->
            <!--                          value-format="YYYY-MM-DD"-->
            <!--                          placeholder="请选择上次执行时间">-->
            <!--          </el-date-picker>-->
            <!--        </el-form-item>-->
            <el-form-item label="是否告警" prop="alarmWitch">
              <el-select v-model="form.alarmWitch" placeholder="请选择是否告警">
                <el-option
                    v-for="dict in sys_yes_no"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="指标恶化包含关键字" prop="alarmKey" v-if="form.alarmWitch === 'Y'" label-width="150px">
              <el-select
                  v-model="form.alarmKey"
                  placeholder="指标恶化包含关键字"
                  clearable
              >
                <el-option
                    v-for="item in algoResultList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <!--                    <el-form-item label="告警内容">-->
            <!--                      <editor v-model="form.alarmContent" :min-height="192"/>-->
            <!--                    </el-form-item>-->
            <el-form-item label="告警内容" prop="alarmContent" v-if="form.alarmWitch === 'Y'" >
              <el-input v-model="form.alarmContent" type="textarea" placeholder="请输入告警内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改业务模型对话框 -->
    <el-dialog :title="titleS" v-model="openS" width="1300" append-to-body>
      <select-metrics ref="selectMetricsRef" style="height: 600px; overflow-y: auto;"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="selectOK">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="titleH" v-model="openH" width="1300" append-to-body>
      <history v-if="openH" ref="historyRef" :analy-id="_analyId" style="height: 600px; overflow-y: auto;"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="selectOK">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Analy">
import {addAnaly, analy, batchInsert, delAnaly, getAnaly, listAnaly, updateAnaly} from "@/api/ripa/analy";
import {listAlgo} from "@/api/ripa/algo";
import selectMetrics from "@/views/ripa/analy/component/selectMetrics.vue"
import history from "@/views/ripa/record/index.vue"

const {proxy} = getCurrentInstance();
const {sys_yes_no} = proxy.useDict('sys_yes_no');
// 添加这行确保组件被视为已使用
const _unused = selectMetrics; // 防止IDE认为组件未被使用
const _unused1 = history; // 防止IDE认为组件未被使用
const analyList = ref([]);
const algoList = ref([]);
const algoResultList = ref([]);
const open = ref(false);
const openS = ref(false);
const openH = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const titleS = ref("");
const titleH = ref("");
const selectMetricsRef = ref(null);
const historyRef = ref(null);
const _analyId = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    autoId: null,
    algoId: null,
    timeSwitch: null,
    scheduleCycle: null,
    lastTime: null,
    alarmWitch: null,
    alarmKey: null,
    alarmContent: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  },
  rules: {
    algoId: [
      {required: true, message: "算法不能为空", trigger: "blur"}
    ],
    alarmKey: [
      {
        required: true,
        message: "告警包含关键字不能为空",
        trigger: "blur",
        validator: (rule, value, callback) => {
          // 只有当 alarmWitch 为 'Y' 时才验证
          if (form.value.alarmWitch === 'Y' && (!value || value.trim() === '')) {
            callback(new Error('告警包含关键字不能为空'));
          } else {
            callback();
          }
        }
      }
    ],
    alarmContent: [
      {
        required: true,
        message: "告警内容不能为空",
        trigger: "blur",
        validator: (rule, value, callback) => {
          // 只有当 alarmWitch 为 'Y' 时才验证
          if (form.value.alarmWitch === 'Y' && (!value || value.trim() === '')) {
            callback(new Error('告警内容不能为空'));
          } else {
            callback();
          }
        }
      }
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

// 监听算法选择变化
function handleAlgoChange(newVal) {
  if (newVal) {
    // 找到选中的算法
    const selectedAlgo = algoList.value.find(algo => algo.algoId === newVal);
    const defaultTemplate = `使用算法"${selectedAlgo.algoName}"检测，发现指标恶化，请注意！`;
    form.value.alarmContent = defaultTemplate;
    form.value.algoName = selectedAlgo.algoName;
    if (selectedAlgo && selectedAlgo.remark) {
      // 将remark按||拆分并转换为选项列表
      algoResultList.value = selectedAlgo.remark.split('||').map(item => ({
        value: item,
        label: item
      }));
      // 只有当 alarmContent 为空时才设置默认值
      // 检查是否使用默认模板或为空，如果是则更新
    } else {
      algoResultList.value = [];
    }
  } else {
    algoResultList.value = [];
  }
}

/** 选择指标确定按钮 */
function selectOK() {
  try {
    // 调用子组件的方法获取选中的数据
    const selectedIds = selectMetricsRef.value.getSelectedData();

    if (!selectedIds || selectedIds.length === 0) {
      proxy.$modal.msgWarning("请先选择指标");
      return;
    }

    const analyDataList = selectedIds.map(id => ({
      autoId: id
    }));

    // 显示加载状态
    proxy.$modal.loading("正在处理...");

    batchInsert(analyDataList)
        .then(response => {
          proxy.$modal.closeLoading();
          proxy.$modal.msgSuccess("操作成功");
          getList();
          openS.value = false;
        })
        .catch(error => {
          proxy.$modal.closeLoading();
          console.error('操作失败:', error);
          proxy.$modal.msgError("操作失败: " + (error.message || "请检查网络连接或联系管理员"));
        });
  } catch (error) {
    proxy.$modal.closeLoading();
    console.error('发生错误:', error);
    proxy.$modal.msgError("发生错误: " + error.message);
  }
}

function getAlgoList() {
  listAlgo({
    algoOk: '0',
    pageNum: 1,
    pageSize: 9999
  }).then(response => {
    algoList.value = response.rows;
  });
}

/** 查询模型指标分析列表 */
function getList() {
  loading.value = true;
  listAnaly(queryParams.value).then(response => {
    analyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  openS.value = false;
  openH.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    analyId: null,
    autoId: null,
    algoId: null,
    timeSwitch: null,
    scheduleCycle: 7,
    lastTime: null,
    alarmWitch: null,
    alarmKey: null,
    alarmContent: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("analyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.analyId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加模型指标分析";
}

/** 修改按钮操作 */
function handleSelect() {
  openS.value = true;
  titleS.value = "修改模型指标分析";
  // reset();
  // const _analyId = row.analyId || ids.value
  // getAnaly(_analyId).then(response => {
  //   form.value = response.data;
  // });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _analyId = row.analyId || ids.value
  getAnaly(_analyId).then(response => {
    form.value = response.data;
    if (!form.value.scheduleCycle) {
      form.value.scheduleCycle = 7;
    }
    if (!form.value.alarmWitch) {
      form.value.alarmWitch = 'Y';
    }
    if (!form.value.timeSwitch) {
      form.value.timeSwitch = 'Y';
    }
    open.value = true;
    title.value = "修改模型指标分析";
  });
}

/** 立即分析 */
function handleAnaly(row) {
  const _analyId = row.analyId || ids.value
  analy(_analyId).then(response => {
    if (response.code == 200) {
      proxy.$modal.confirm("分析结果:" + response.msg)
      // proxy.$modal.msgSuccess("分析结果:" + response.msg);
    } else {
      proxy.$modal.msgError("分析失败:" + response.msg);
    }
    getList()
  });
}

function handleHistory(row) {
  _analyId.value = row.analyId;
  openH.value = true;
  titleH.value = "模型指标分析历史记录";
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["analyRef"].validate(valid => {
    if (valid) {
      if (form.value.analyId != null) {
        updateAnaly(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAnaly(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _analyIds = row.analyId || ids.value;
  proxy.$modal.confirm('是否确认删除模型指标分析编号为"' + _analyIds + '"的数据项？').then(function () {
    return delAnaly(_analyIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('biz/analy/export', {
    ...queryParams.value
  }, `analy_${new Date().getTime()}.xlsx`)
}

getList();
getAlgoList();
</script>
