<!-- 规则列表 -- 表格 -->
<template>
  <div class="layout-pd">
    <el-row>
      <!--操作-->
      <el-col :xs="24">
        <el-card class="mt8" shadow="hover">
          <el-form :model="Data.Filter" @submit.stop.prevent>
            <el-form-item prop="name" style="width: 100%">
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                <el-form-item label="规则名称">
                  <el-input v-model="Data.Filter.ruleName" placeholder="请输入规则名称" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                 <el-form-item label="状态">
                   <el-select v-model="Data.Filter.isActive" placeholder="请选择状态">
                     <el-option v-for="item in StatusOptions" :key="item.value" :label="item.label" :value="item.value" />
                   </el-select>
                 </el-form-item>
                           </el-col>
                           <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                              <el-form-item label="推送方式">
                                  <el-select  placeholder="请选择推送方式">
                                   <el-option label="所有" :value="''"></el-option>
                                   <el-option label="电子邮箱" :value="''"></el-option>
                                   <el-option label="微信" :value="''"></el-option>
                                 </el-select>
                             </el-form-item>
                           </el-col>
            </el-form-item>
          </el-form>

          <hr>

          <!-- 按钮 -->
          <el-row justify="space-between" class="submit-button" style="margin-bottom: -9px;">
            <el-row>
              <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
              <el-button type="primary" icon="ele-RefreshRight" @click="onReset"> 重置 </el-button>
            </el-row>
            <el-row>
              <el-button type="primary" icon="ele-Plus" @click="addAlarmRules('')"> 添加 </el-button>
            </el-row>
          </el-row>
        </el-card>
      </el-col>
      <!--表格-->
      <el-col :xs="24">
        <el-card style="height: 76vh;" class="my-fill mt8" shadow="hover">
          <el-table ref="multipleTableRef" v-loading="Data.loading" stripe :data="Data.tableModel" row-key="id"
            style="width: 100%">
            <el-table-column v-for="column in Data.dynamicColumns" :key="column.prop" :prop="column.prop"
              :label="column.label" />
            <el-table-column label="状态" width="80" align="center" show-overflow-tooltip>
              <template #default="{ row }">
                <StatusBox :status="row.isActive ? '启用' : '禁用'" />
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" header-align="center" align="center" class="right-operation"
              width="100">
              <template #default="{ row }">
                <el-link class="my-el-link mr12 ml12" @click="addAlarmRules(row)" type="primary" icon="ele-EditPen"
                  :underline="false" target="_blank">编辑</el-link>
                <el-link class="my-el-link mr12 ml12" @click="toDelete(row.id)" type="primary" icon="ele-Delete"
                  :underline="false" target="_blank">删除</el-link>
                <el-link class="my-el-link mr12 ml12" @click="toOpen(row)" type="primary" icon="ele-SwitchButton"
                  :underline="false" target="_blank">启用</el-link>
              </template>
            </el-table-column>

          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 20px">
            <el-pagination v-model:currentPage="Data.pageInput.currentPage" v-model:page-size="Data.pageInput.pageSize"
              :total="Data.total" :page-sizes="[5, 10, 15, 20, 50, 100]" small background @size-change="onSizeChange"
              @current-change="onCurrentChange" layout="total, sizes, prev, pager, next, jumper" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <EditDialog ref="editDialogRef" />

  </div>

</template>

<script setup lang="ts" name="partsManagement/oilGun">
import { defineAsyncComponent, onBeforeMount, onMounted, reactive, ref, watch } from "vue";
import { alarmRluesFilterModel_SearchFilter, alarmRluesFilterModel, PageInputAlarmRluesFilterModel } from "/@/api/admin/AlarmService/alarmRulesDto";
import { alarmRulesApi } from "/@/api/admin/AlarmService/alarmRulesApi";
import eventBus from "/@/utils/mitt";
import StatusBox from '/@/components/StatusBox.vue';
import { useDynamicPageSize } from "/@/composables/useDynamicPageSize";


// 使用组合式函数获取分页状态
const pageState = useDynamicPageSize(10, 15);

/**页面对象 */
const Data = reactive({
  time1: '',
  /** 选择框列表 */
  statusList: [] as any,
  supplierList: [] as any,
  /**加载显示 */
  loading: false,
  /**条件查询模块 */
  Filter: {
    /** 规则名称 */
    ruleName: "",
    Status:"",
    upload:"",
    isActive:undefined
  } as alarmRluesFilterModel_SearchFilter,
  /**表格信息 */
  tableModel: [] as alarmRluesFilterModel[],
  /**动态表头 */
  dynamicColumns: [
    { prop: 'ruleName', label: '规则名称' },
    { prop: 'userName', label: '用户' },
    { prop: 'pushMethod', label: '推送方式' },
    { prop: 'triggerMethod', label: '触发方式' },
    { prop: 'regular', label: '正则匹配' },
    { prop: 'taskPriority', label: '优先级' },
    { prop: 'isExclusive', label: '是否互斥' },
    // { prop: 'stationName', label: '推送方式' },
    { prop: 'pushTemplateMappingID', label: '模板' },
    { prop: 'remark', label: '备注' },

  ],
  /**分页总数 */
  total: 0,
  /**分页标识 */
  pageInput: {
    currentPage: 1,
    pageSize: 10,
  } as PageInputAlarmRluesFilterModel,
})

// 定义状态选项
const StatusOptions = [
  { value: undefined, label: '所有' },
  { value: true, label: '启用' },
  { value: false, label: '禁用' }
];

enum upload {
  email="电子邮箱",
  vx="微信"
}

/**引入组件*/
const EditDialog = defineAsyncComponent(() => import('./components/add-alarmRules.vue'))
const editDialogRef = ref()


// // 条件查询
const init = async () => {
  Data.loading = true
  const res: any = await new alarmRulesApi().getData({ ...Data.pageInput, filter: Data.Filter })
  console.log(res)
  Data.tableModel = res?.data.list ?? []
  Data.total = res?.data?.list.length ?? 0   // 接口中没有总的数据量
  Data.loading = false
  pushMethodChange()
}

const onQuery = () => {
  init()
  console.log("查询")
}

/**重置查询条件 */
const resetQuery = () => {
  Data.Filter.ruleName = ''
}
/**重置 */
const onReset = () => {
  resetQuery()
  init()
}

/** 
 * 添加规则
*/
const addAlarmRules = ((row: any) => {
  editDialogRef.value.openDialog(row)
  init()
})

/**
* 页条变化
* @param val
*/
const onSizeChange = (val: number) => {
  Data.pageInput.pageSize = val
  init()
}

/**
 * 页数 变化
 * @param val
 */
const onCurrentChange = (val: number) => {
  Data.pageInput.currentPage = val
  init()
}

/** 数据转换 */
const pushMethodChange = (() => {
  // 推送方式
  Data.tableModel.forEach((item: any) => {
    const pushList = item['pushMethod'].split(',')
    for (var i = 0; i < pushList.length; i++) {
      if (pushList[i] == 'wx') {
        pushList[i] = "微信"
      } else if (pushList[i] == 'email') {
        pushList[i] = "电子邮箱"
      }
    }
    item['pushMethod'] = pushList.toString()

    // 是否互斥
    if (item['isExclusive'] == true) {
      item['isExclusive'] = "是"
    } else {
      item['isExclusive'] = "否"
    }
  })
})

// 操作
const toDelete = (async (id?: number) => {
  await new alarmRulesApi().deliteData({ 'id': id }).then(() => {
    eventBus.emit('refreshView')
  })

})

const toOpen = (async (row: any) => {
  row.isActive = !row.isActive
  const data = { ...row } as any

  if (data.isExclusive == '是') {
    data.isExclusive = true
    console.log(1)
  } else {
    data.isExclusive = false
  }
  if (data.pushMethod == '') {
    return
  } else {
    if (data.pushMethod == '微信') {
      data.pushMethod = 'wx'
    } else if (data.pushMethod == '电子邮箱') {
      data.pushMethod = 'email'
    } else {
      data.pushMethod = 'wx,email'
    }
  }


  await new alarmRulesApi().addForm(data).then(() => {
    eventBus.emit('refreshView')
  })
})

// 挂载前
onBeforeMount(() => {
  eventBus.off('refreshView')
})

// 挂载时
onMounted(async () => {
  // 初始化分页大小
  Data.pageInput.pageSize = pageState.pageInput.pageSize;
  await init()
  eventBus.off('refreshView')
  eventBus.on('refreshView', async () => {
    await init()
  })
})



</script>

<style scoped lang="scss">
.el-input,
.el-select {
  width: 240px;
}

/* 输入框标签固定四个字符宽度 */
::v-deep .el-form-item__label {
  // 字体大小14，4个字符，12px右间距
  width: 14*4px+12px;
  justify-content: start;
}

/* 数据表头 设置灰色样式 */
::v-deep .el-table th.el-table__cell {
  background-color: #F6F6F6;
}
</style>