<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :inline="true"
      :model="queryParams"
      :size="productId ? 'small' : ''"
      label-width="68px"
    >
      <!--      <el-form-item label="" prop="tenantId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.tenantId"-->
      <!--          clearable-->
      <!--          placeholder="请输入"-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="告警名称" prop="alertName">
        <el-input
          v-model="queryParams.alertName"
          clearable
          placeholder="请输入告警名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="告警级别" prop="alertLevel">
        <el-select
          v-model="queryParams.alertLevel"
          clearable
          placeholder="请选择告警级别"
          style="width: 100%"
        >
          <el-option
            v-for="dict in iot_alert_level"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="!product" label="产品" prop="productId">
        <el-select
          v-model="queryParams.productId"
          :remote-method="getProductOptions"
          clearable
          filterable
          placeholder="请选择产品"
          remote
          remote-show-suffix
        >
          <el-option
            v-for="item in productOptions"
            :key="item.productId"
            :label="item.productName"
            :value="item.productId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @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
          v-if="productId"
          v-hasPermi="['product:alertRule:add']"
          :size="productId ? 'small' : ''"
          icon="Plus"
          plain
          type="primary"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :size="productId ? 'small' : ''"
          icon="refresh"
          plain
          type="success"
          @click="getList"
          >刷新
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          :size="productId ? 'small' : ''"-->
      <!--          icon="refresh"-->
      <!--          plain-->
      <!--          type="success"-->
      <!--          @click="showSelect = true"-->
      <!--        >刷新-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          v-hasPermi="['device:alert:edit']"-->
      <!--          :disabled="single"-->
      <!--          icon="Edit"-->
      <!--          plain-->
      <!--          type="success"-->
      <!--          @click="handleUpdate"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          v-hasPermi="['device:alert:remove']"-->
      <!--          :disabled="multiple"-->
      <!--          icon="Delete"-->
      <!--          plain-->
      <!--          type="danger"-->
      <!--          @click="handleDelete"-->
      <!--        >删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          v-hasPermi="['device:alert:export']"-->
      <!--          icon="Download"-->
      <!--          plain-->
      <!--          type="warning"-->
      <!--          @click="handleExport"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!--    <table-select-->
    <!--      v-model="showSelect"-->
    <!--      :request-method="listDevice"-->
    <!--      select-key="deviceId"-->
    <!--      @select-add="handleAddSelect"-->
    <!--    />-->
    <el-table
      v-loading="loading"
      :data="alertList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="告警名称" prop="alertName" />
      <el-table-column align="center" label="告警级别" prop="alertLevel">
        <template #default="{ row }">
          <dict-tag
            :options="iot_alert_level"
            :value="row.alertLevel"
          ></dict-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="产品" prop="productName" />
      <el-table-column align="center" label="告警状态" prop="status">
        <template #default="{ row }">
          <dict-tag :options="alertStatusDict" :value="[row.status]" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark" />
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
      >
        <template #default="{ row }">
          <el-button
            v-hasPermi="['product:alertRule:edit']"
            icon="Edit"
            link
            type="warning"
            @click="handleUpdate(row)"
            >{{ productId ? "修改" : "查看" }}
          </el-button>
          <el-button
            v-hasPermi="['product:alertRule:remove']"
            icon="Delete"
            link
            type="danger"
            @click="handleDelete(row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改设备告警对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="800px">
      <div
        class="el-divider el-divider--horizontal"
        style="margin-top: -25px"
      ></div>
      <el-form ref="alertRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="告警名称" prop="alertName">
              <el-input v-model="form.alertName" placeholder="请输入告警名称" />
            </el-form-item>
            <el-form-item label="告警级别" prop="alertLevel">
              <el-select
                v-model="form.alertLevel"
                placeholder="请选择告警级别"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in iot_alert_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="启动状态">
              <el-switch
                v-model="form.status"
                :active-value="1"
                :inactive-value="2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                placeholder="请输入内容"
                rows="6"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider></el-divider>
        <el-form-item label="触发器" prop="triggers">
          <el-select
            v-model="form.conditions"
            placeholder="请选择"
            style="margin-bottom: 10px; width: 100%"
          >
            <el-option
              v-for="item in triggerConditions"
              :key="item.value"
              :disabled="form.triggers.length === 1 && item.value === '2'"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <div
            v-for="(item, index) in form.triggers"
            :key="index"
            style="
              margin-bottom: 15px;
              border: 1px solid #ddd;
              padding: 10px;
              width: 100%;
            "
          >
            <el-row>
              <el-col :span="4">
                <el-select
                  v-model="item.triggerType"
                  placeholder="请选择"
                  size="small"
                >
                  <!--                  @change="changeTriggerSource"-->
                  <el-option
                    v-for="subItem in triggerSource.filter(
                      (el) => form.triggers.length <= 1 || el.value === '1'
                    )"
                    :key="subItem.value"
                    :label="subItem.label"
                    :value="subItem.value"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <!--              <el-col v-if="item.triggerType === '1'" :offset="1" :span="16">-->
              <!--              </el-col>-->
              <el-col v-if="item.triggerType === '2'" :offset="1" :span="16">
                <!--                TODO:HIDE-->
                <!--                <el-time-picker-->
                <!--                  v-model="timerTimeValue"-->
                <!--                  :disabled="item.isAdvance === 1"-->
                <!--                  placeholder="选择执行时间"-->
                <!--                  size="small"-->
                <!--                  value-format="HH:mm"-->
                <!--                  @change="timeChange"-->
                <!--                ></el-time-picker>-->
              </el-col>
              <el-col
                v-if="index !== 0"
                :offset="item.triggerType === '1' ? 17 : 1"
                :span="2"
              >
                <el-button
                  link
                  size="small"
                  type="danger"
                  @click="removeTriggerItem(index)"
                  >删除
                </el-button>
              </el-col>
            </el-row>

            <!--定时-->
            <el-row v-if="item.triggerType === '2'">
              <el-col :span="24">
                <el-row style="margin-bottom: 5px">
                  <el-col :span="4">
                    <!--                    TODO:HIDE-->
                    <!--                    <el-select-->
                    <!--                      v-model="timerWeekRepeatValue"-->
                    <!--                      :disabled="item.isAdvance === 1"-->
                    <!--                      placeholder="请选择"-->
                    <!--                      size="small"-->
                    <!--                      @change="repeatChange"-->
                    <!--                    >-->
                    <!--                      <el-option-->
                    <!--                        v-for="item in timerWeekRepeats"-->
                    <!--                        :key="item.value"-->
                    <!--                        :label="item.label"-->
                    <!--                        :value="item.value"-->
                    <!--                      >-->
                    <!--                      </el-option>-->
                    <!--                    </el-select>-->
                  </el-col>
                  <el-col
                    v-if="timerWeekRepeatValue === '3'"
                    :offset="1"
                    :span="15"
                  >
                    <!--                    TODO:hide-->
                    <!--                    <el-select-->
                    <!--                      v-model="timerWeekValue"-->
                    <!--                      :disabled="item.isAdvance === 1"-->
                    <!--                      multiple-->
                    <!--                      placeholder="请选择"-->
                    <!--                      size="small"-->
                    <!--                      style="width: 485px"-->
                    <!--                      @change="weekChange"-->
                    <!--                    >-->
                    <!--                      <el-option-->
                    <!--                        v-for="item in timerWeeks"-->
                    <!--                        :key="item.value"-->
                    <!--                        :label="item.label"-->
                    <!--                        :value="item.value"-->
                    <!--                      >-->
                    <!--                      </el-option>-->
                    <!--                    </el-select>-->
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="24">
                <el-row>
                  <el-col :span="18">
                    <!--                      :disabled="item.isAdvance === 0"-->
                    <el-input
                      v-model="item.cronExpression"
                      placeholder="cron执行表达式"
                      size="small"
                    >
                      <!--                          :disabled="item.isAdvance === 0"-->
                      <template #append>
                        <el-button
                          size="small"
                          type="primary"
                          @click="handleShowCron(item, index)"
                        >
                          生成表达式
                          <i class="el-icon-time el-icon--right"></i>
                        </el-button>
                      </template>
                    </el-input>
                  </el-col>
                  <el-col :offset="1" :span="4">
                    <!--                    TODO:hide-->
                    <!--                    <el-checkbox-->
                    <!--                      v-model="item.isAdvance"-->
                    <!--                      :false-label="0"-->
                    <!--                      :true-label="1"-->
                    <!--                      @change="customerCronChange"-->
                    <!--                    >-->
                    <!--                      自定义表达式-->
                    <!--                    </el-checkbox>-->
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!--设备-->
            <el-row v-if="item.triggerType === '1'">
              <el-col :span="4">
                <el-select
                  v-model="item.modelType"
                  placeholder="请选择"
                  size="small"
                  @change="item.modelId = null"
                >
                  <el-option
                    v-for="subItem in modelTypes"
                    :key="subItem.value"
                    :label="subItem.label"
                    :value="subItem.value"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col
                v-if="['1', '2', '3'].includes(item.modelType)"
                :offset="1"
                :span="4"
              >
                <el-select
                  v-model="item.modelId"
                  placeholder="请选择"
                  size="small"
                  @change="handleTriggerModelChange($event, index)"
                >
                  <el-option
                    v-for="subItem in modelList.filter(
                      (el) => el.type === parseInt(item.modelType)
                    )"
                    :key="subItem.modelId"
                    :label="subItem.modelName"
                    :value="subItem.modelId"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col
                v-if="['1', '2', '3'].includes(item.modelType)"
                :offset="1"
                :span="5"
              >
                <el-select
                  v-model="item.operator"
                  placeholder="请选择操作符"
                  size="small"
                >
                  <el-option key="=" label="等于(=)" value="=" />
                  <el-option key="!=" label="不等于(!=)" value="!=" />
                  <el-option key=">" label="大于(>)" value=">" />
                  <el-option key="<" label="小于(<)" value="<" />
                  <el-option key=">=" label="大于等于(>=)" value=">=" />
                  <el-option key="<=" label="小于等于(<=)" value="<=" />
                  <el-option
                    key="contain"
                    label="包含(contain)"
                    value="contain"
                  />
                  <el-option
                    key="notcontain"
                    label="不包含(not contain)"
                    value="notcontain"
                  />
                </el-select>
              </el-col>
              <el-col
                v-if="['1', '2', '3'].includes(item.modelType)"
                :offset="1"
                :span="5"
              >
                <el-input
                  v-model="item.modelValue"
                  placeholder="值"
                  size="small"
                />
              </el-col>
            </el-row>
          </div>
          <el-button
            v-if="form.triggers[0].triggerType === '1'"
            link
            size="small"
            type="primary"
            @click="addTriggerItem"
          >
            添加触发器
          </el-button>
        </el-form-item>

        <el-divider></el-divider>
        <el-form-item label="执行动作">
          <el-row
            v-for="(item, index) in form.actions"
            :key="index"
            style="margin-bottom: 10px"
          >
            <el-col :span="4">
              <!-- 选择物模型类型 -->
              <el-select v-model="item.modelType" placeholder="请选择">
                <el-option
                  v-for="subItem in modelTypes.filter((el) =>
                    ['1', '2', '3'].includes(el.value)
                  )"
                  :key="subItem.value"
                  :label="subItem.label"
                  :value="subItem.value"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :offset="1" :span="4">
              <!-- 物模型选择 -->
              <el-select
                v-model="item.modelId"
                placeholder="请选择"
                @change="handleActionsModelChange($event, index)"
              >
                <el-option
                  v-for="subItem in modelList.filter(
                    (el) => el.type === parseInt(item.modelType)
                  )"
                  :key="subItem.modelId"
                  :label="subItem.modelName"
                  :value="subItem.modelId"
                >
                </el-option>
              </el-select>
              <!--              <el-select v-model="item.modelType" placeholder="请选择">-->
              <!--                <el-option-->
              <!--                  v-for="subItem in modelTypes"-->
              <!--                  :key="subItem.value"-->
              <!--                  :label="subItem.label"-->
              <!--                  :value="subItem.value"-->
              <!--                >-->
              <!--                </el-option>-->
              <!--              </el-select>-->
            </el-col>
            <el-col :offset="1" :span="5">
              <el-select v-model="item.operator" placeholder="请选择操作符">
                <el-option key="=" label="等于(=)" value="=" />
                <el-option key="!=" label="不等于(!=)" value="!=" />
                <el-option key=">" label="大于(>)" value=">" />
                <el-option key="<" label="小于(<)" value="<" />
                <el-option key=">=" label="大于等于(>=)" value=">=" />
                <el-option key="<=" label="小于等于(<=)" value="<=" />
                <el-option
                  key="contain"
                  label="包含(contain)"
                  value="contain"
                />
                <el-option
                  key="notcontain"
                  label="不包含(not contain)"
                  value="notcontain"
                />
              </el-select>
            </el-col>
            <el-col :offset="1" :span="5">
              <el-input v-model="item.modelValue" placeholder="值" />
            </el-col>
            <el-col v-if="index !== 0" :offset="1" :span="2">
              <!--              <a style="color: #f56c6c" @click="removeActionItem(index)"-->
              <!--              >删除</a-->
              <!--              >-->
              <el-button
                link
                plus
                size="small"
                type="danger"
                @click="removeActionItem(index)"
                >删除
              </el-button>
            </el-col>
          </el-row>
          <el-button link size="small" type="primary" @click="addActionItem"
            >添加执行动作
          </el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="productId" type="primary" @click="submitForm"
            >确 定
          </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="openCron"
      append-to-body
      class="scrollbar"
      destroy-on-close
      title="Cron表达式生成器"
    >
      <crontab
        :expression="expression"
        style="padding-bottom: 80px"
        @fill="crontabFill"
        @hide="openCron = false"
      ></crontab>
    </el-dialog>

    <!-- 添加或修改设备告警对话框 -->
    <!--    <el-dialog v-model="open" :title="title" append-to-body width="500px">-->
    <!--      <el-form ref="alertRef" :model="form" :rules="rules" label-width="80px">-->
    <!--        <el-form-item label="" prop="tenantId">-->
    <!--          <el-input v-model="form.tenantId" placeholder="请输入" />-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="告警名称" prop="alertName">-->
    <!--          <el-input v-model="form.alertName" placeholder="请输入告警名称" />-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="告警级别" prop="alertLevel">-->
    <!--          <el-input v-model="form.alertLevel" placeholder="请输入告警级别" />-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="产品ID" prop="productId">-->
    <!--          <el-input v-model="form.productId" placeholder="请输入产品ID" />-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="备注" prop="remark">-->
    <!--          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea" />-->
    <!--        </el-form-item>-->
    <!--      </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>-->
  </div>
</template>

<script name="Alert" setup>
import Crontab from "@/components/Crontab/index.vue";
import {
  addAlertRule,
  delAlertRule,
  getAlertRule,
  listAlertRule,
  updateAlertRule,
} from "@/api/product/alertRule";
import { getCurrentInstance, reactive, ref, toRefs, watch } from "vue";
import { useDict } from "@/utils/dict";
import { listProduct } from "@/api/product/product";
import { listDevice } from "@/api/iot/device";
import { listModel } from "@/api/thingsmodel/model";
import DictTag from "@/components/DictTag/index.vue";
import { alertStatusDict } from "@/constant/dict";

const { proxy } = getCurrentInstance();
const props = defineProps({
  product: {
    type: Object,
    default: null,
  },
  productId: {
    type: Number,
    default: null,
  },
});

const { product, productId } = toRefs(props);
const timerWeeks = [
  {
    value: 1,
    label: "周一",
  },
  {
    value: 2,
    label: "周二",
  },
  {
    value: 3,
    label: "周三",
  },
  {
    value: 4,
    label: "周四",
  },
  {
    value: 5,
    label: "周五",
  },
  {
    value: 6,
    label: "周六",
  },
  {
    value: 7,
    label: "周日",
  },
];

// 执行动作源
const actionSource = [
  {
    value: 1,
    label: "设备",
  },
  {
    value: 3,
    label: "告警输出",
  },
];
// 物模型类别
const modelTypes = [
  {
    value: "1",
    label: "属性",
  },
  {
    value: "2",
    label: "功能",
  },
  {
    value: "3",
    label: "事件",
  },
  {
    value: "4",
    label: "设备上线",
  },
  {
    value: "5",
    label: "设备下线",
  },
];
// 触发器条件
const triggerConditions = [
  {
    value: "2",
    label: "满足所有条件",
  },
  {
    value: "1",
    label: "满足任一条件",
  },
];
// 告警状态
const alertType = [
  {
    value: 1,
    label: "启动",
  },
  {
    value: 2,
    label: "停止",
  },
];
// 周
const timerWeekRepeats = ref([
  {
    value: "1",
    label: "每天",
  },
  {
    value: "2",
    label: "仅此一次",
  },
  {
    value: "3",
    label: "指定",
  },
]);
const productOptions = ref([]);
const deviceOptions = ref([]);
const alertList = ref([]);
const open = ref(false);
const openCron = 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 expression = ref(""); // 传入的表达式
const triggerIndex = ref(0); // 触发器的索引，用于接收传入的表达式
const timerWeekRepeatValue = ref("1");
const timerWeekValue = ref([1, 2, 3, 4, 5, 6, 7]);
const timerTimeValue = ref("");
const modelList = ref([]);
const triggerSource = ref([
  {
    value: "1",
    label: "设备触发",
  },
  {
    value: "2",
    label: "定时触发",
  },
]);

const { iot_alert_level, sys_job_status } = useDict(
  "iot_alert_level",
  "sys_job_status"
);
const data = reactive({
  form: {
    conditions: "1", // 触发器条件
    triggers: [],
    actions: [],
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tenantId: null,
    alertName: null,
    alertLevel: null,
    productId: null,
    triggers: null,
    actions: null,
    status: null,
  },
  rules: {
    alertName: [
      { required: true, message: "告警名称不能为空", trigger: "blur" },
    ],
    alertLevel: [
      { required: true, message: "告警级别不能为空", trigger: "change" },
    ],
    productId: [{ required: true, message: "产品不能为空", trigger: "change" }],
    triggers: [{ required: true, message: "触发器不能为空", trigger: "blur" }],
    actions: [{ required: true, message: "执行动作不能为空", trigger: "blur" }],
  },
  // 产品
  productInfo: {},
  thingsModel: {},
});

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

/** 查询设备告警列表 */
function getList() {
  loading.value = true;
  listAlertRule(queryParams.value).then((response) => {
    alertList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

// 表单重置
function reset() {
  form.value = {
    alertId: null,
    tenantId: null,
    alertName: null,
    alertLevel: null,
    productId: null,
    // triggers: null,
    // actions: null,
    status: null,
    createBy: null,
    createTime: null,
    remark: null,
    conditions: "1", // 触发器条件
    triggers: [
      {
        productId: productId.value,
        productSn: product.value?.productSn,
        modelValue: null,
        triggerType: "1", //1=设备，2=定时，3=告警输出
        modelType: "1", // 1=属性，2=功能
        cronExpression: null,
        // jobId: 0,
        // deviceId: 0,
        // deviceName: "请选择一个设备",
        // id: "",
        // name: "",
        // isAdvance: 1
      },
    ],
    actions: [
      {
        productId: productId.value,
        modelId: null,
        modelValue: null,
        modelKey: null,
        operator: null,
        modelType: "1", // 1=属性，2=功能
        // id: "",
        // name: "",
        // deviceId: 0,
        // deviceName: "请选择一个设备",
        // triggerType: "1", //1=设备，2=定时，3=告警输出
      },
    ],
  };
  proxy.resetForm("alertRef");
}

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

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

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

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备告警";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _alertId = row.alertId || ids.value;
  getAlertRule(_alertId).then((response) => {
    form.value = response.data;
    try {
      form.value.triggers = JSON.parse(response.data.triggersStr);
    } catch (e) {
      console.log("fail parse triggers str");
    }
    form.value.conditions = form.value.triggers[0]?.conditions;
    try {
      form.value.actions = JSON.parse(response.data.actionsStr);
    } catch (e) {
      console.log("fail parse actions str");
    }
    open.value = true;
    title.value = "修改设备告警";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["alertRef"].validate((valid) => {
    if (valid) {
      if (product.value) {
        form.value.productId = product.value.productId;
        form.value.productSn = product.value.productSn;
      }
      form.value.triggers.forEach((el) => {
        el.conditions = form.value.conditions;
        el.status = form.value.status;
      });
      if (form.value.alertId != null) {
        updateAlertRule(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAlertRule(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _alertIds = row.alertId || ids.value;
  proxy.$modal
    .confirm('是否确认删除设备告警编号为"' + _alertIds + '"的数据项？')
    .then(function () {
      return delAlertRule(_alertIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "device/alert/export",
    {
      ...queryParams.value,
    },
    `alert_${new Date().getTime()}.xlsx`
  );
}

/** 添加动作 */
const addActionItem = () => {
  form.value.actions.push({
    productId: productId.value,
    modelId: null,
    modelValue: "",
    modelKey: "",
    operator: "",
    modelType: "1", // 1=属性，2=功能
    // id: "",
    // name: "",
    // value: ""
  });
};
/** 删除动作 */
const removeActionItem = (index) => {
  form.value.actions.splice(index, 1);
};
/** 触发器源改变事件 **/
const changeTriggerSource = () => {
  setTriggerSource();
};
/** 设置触发器源 **/
const setTriggerSource = () => {
  // 触发器只能包含一个定时
  let hasTimer = false;
  for (let i = 0; i < form.value.triggers.length; i++) {
    if (form.value.triggers[i].triggerType === "2") {
      hasTimer = true;
    }
  }
  if (hasTimer) {
    triggerSource.value = [
      {
        value: "1",
        label: "设备触发",
      },
    ];
  } else {
    //定时
    triggerSource.value = [
      {
        value: "1",
        label: "设备触发",
      },
      {
        value: "2",
        label: "定时触发",
      },
    ];
  }
  /**/
};
/** 添加触发器 */
const addTriggerItem = () => {
  // setTriggerSource();
  form.value.triggers.push({
    productId: productId.value,
    productSn: product.value?.productSn,
    triggerType: "1", // 1=设备，2=定时，3=告警输出
    modelType: "1", // 1=属性，2=功能
    cronExpression: null,
    modelKey: null,
    modelValue: null,
    // conditions: "2",
    operator: null,
    modelId: null,
    // value: "",
    // id: "",
    // name: "",
    // jobId: 0,
    // deviceId: 0,
    // deviceName: "请选择一个设备",
    // isAdvance: 1
  });
};
/** 删除触发器 */
const removeTriggerItem = (index) => {
  form.value.triggers.splice(index, 1);
  if (form.value.triggers.length === 1) {
    form.value.conditions = "1";
  }
  // setTriggerSource();
};
/** cron表达式按钮操作 */
const handleShowCron = (item, index) => {
  expression.value = item.cronExpression;
  triggerIndex.value = index;
  openCron.value = true;
};
/** 确定后回传值 */
const crontabFill = (value) => {
  form.value.triggers[triggerIndex.value].cronExpression = value;
};
/** 修改重复事件 **/
const repeatChange = (data) => {
  if (timerWeekRepeatValue.value === "1") {
    // 每天
    timerWeekValue.value = [1, 2, 3, 4, 5, 6, 7];
    form.value.repeat = 1;
  } else if (timerWeekRepeatValue.value === "2") {
    // 仅此一次
    timerWeekValue.value = [];
    form.value.isRepeat = 0;
  } else {
    // 指定
    form.value.isRepeat = 1;
  }
  gentCronExpression();
};
/** 星期改变事件 **/
const weekChange = (data) => {
  gentCronExpression();
};
/** 时间改变事件 **/
const timeChange = (data) => {
  gentCronExpression();
};
/**自定义cron表达式选项改变事件 */
const customerCronChange = (data) => {
  gentCronExpression();
};
/** 生成cron表达式**/
const gentCronExpression = () => {
  if (timerTimeValue.value === "") {
    proxy.$modal.alertError("执行时间不能为空");
  }
  let minute = timerTimeValue.value.substring(0, 2);
  let hour = timerTimeValue.value.substring(3);
  let week = "*";
  if (timerWeekValue.value.length > 0) {
    week = timerWeekValue.value;
  }
  form.value.triggers[triggerIndex.value].cronExpression =
    "0 " + minute + " " + hour + " ? * " + week;
};

function getProductOptions(keyword) {
  listProduct({
    productName: keyword,
    pageNum: 1,
    pageSize: 20,
  }).then((resp) => {
    productOptions.value = resp.rows;
  });
}

function getDeviceOptions(keyword) {
  listDevice({
    deviceName: keyword,
    pageNum: 1,
    pageSize: 20,
  }).then((resp) => {
    deviceOptions.value = resp.rows;
  });
}

const getThingsModelOptions = (productId) => {
  listModel({
    productId,
  }).then((resp) => {
    modelList.value = resp.rows;
  });
};

const handleTriggerModelChange = (data, index) => {
  const _model = modelList.value.find((el) => el.modelId === data);
  form.value.triggers[index].modelKey = _model?.identifier;
  form.value.triggers[index].datatype = _model?.datatype;
};
const handleActionsModelChange = (data, index) => {
  form.value.actions[index].modelKey = modelList.value.find(
    (el) => el.modelId === data
  ).identifier;
};

watch(
  productId,
  (val) => {
    queryParams.value.productId = val;
    getList();
  },
  {
    immediate: true,
  }
);

if (!productId.value) {
  getProductOptions();
}
if (productId.value) {
  getThingsModelOptions(productId.value);
}
</script>
