<template>
  <div>
    <el-form :model="queryParams" inline class="query-form" ref="queryForm">
      <el-form-item label="监听器类型" prop="listenerType">
        <el-select v-model="queryParams.listenerType" placeholder="请选择监听器类型"  filterable clearable>
          <el-option
              v-for="item in cacheStore.getDict('process_listen_type')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="监听器名称" prop="listenerName">
        <el-input v-model="queryParams.listenerName" placeholder="请输入监听器名称"></el-input>
      </el-form-item>
      <el-form-item label="监听器数据类型" prop="listenerValueType">
        <el-select v-model="queryParams.listenerValueType" placeholder="请选择监听器数据类型"  filterable clearable>
          <el-option
              v-for="item in cacheStore.getDict('process_data_type')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch()" :icon="Search">搜索</el-button>
        <el-button type="primary" @click="handleReset" :icon="Refresh" plain>重置</el-button>
      </el-form-item>
    </el-form>
    <div class="query-btn">
      <el-button type="primary" v-perm="['code:listener:add']" @click="handleAdd" :icon="Plus" >新增</el-button>
      <el-button type="danger" v-perm="['code:listener:del']" @click="handleMoreDelete(listenId,listenNameList)" :icon="Delete" plain
                 :disabled="disabled">删除
      </el-button>
<!--      <el-button type="warning" v-perm="['code:listener:export']" @click="handleExport" :icon="Download" plain>导出-->
<!--      </el-button>-->
    </div>
    <div class="table">
      <el-table
          :data="list"
          row-key="id"
          :lazy="true"
          ref="singleTable"
          v-loading="loading"
          @select="handleSelect"
          v-tabh
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column label="序号" type="index" width="60" align="center"/>
        <el-table-column prop="listenerType" label="监听器类型" align="center">
          <template #default="scope">
            <tag dict-type="process_listen_type" :value="scope.row.listenerType"/>
          </template>
        </el-table-column>
        <el-table-column prop="eventType" label="监听类型" align="center"/>
        <el-table-column prop="listenerName" label="监听器名称" align="center"/>
        <el-table-column prop="listenerValue" label="监听器值" align="center"/>
        <el-table-column prop="listenerValueType" label="监听器数据类型" align="center">
          <template #default="scope">
            <tag dict-type="process_data_type" :value="scope.row.listenerValueType"/>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="mini" v-perm="['code:listener:edit']"
                       @click="handleEdit(scope.row.id)"  link>编辑
            </el-button>
            <popover-delete :name="scope.row.dsName" :type="'系统内置监听器'" :perm="['code:listener:del']"
                            @delete="handleDelete(scope.row.id)"/>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <paging :current-page="pageInfo.pageNum" :page-size="pageInfo.pageSize" :page-sizes="[10, 20, 30, 40,50]"
            :total="total" @changeSize="handleSizeChange" @goPage="handleCurrentChange"/>
    <el-dialog v-model="isVisited" :title="title" width="900px">
      <el-form :model="form" ref="formInstance" :rules="formRules" label-width="100px" class="dialog-form">
        <el-row>
          <el-col :span="11">
            <el-form-item label="监听器名称" prop="listenerName" class="listen">
              <el-input placeholder="请设置监听器名称" v-model="form.listenerName"/>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="2">
            <el-form-item label="监听器类型" prop="eventType" class="listen">
              <el-select placeholder="请选择监听器类型" @change="form.eventType = []"
                         v-model="form.listenerType"  filterable clearable>
                <el-option :value="'1'" label="任务监听"/>
                <el-option :value="'2'" label="执行监听"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="事件类型" prop="listenerType" class="listen">
              <el-select multiple placeholder="请选择事件类型" v-model="form.eventType"  filterable clearable>
                <el-option value="create" label="create"/>
                <el-option v-if="form.listenerType === '2'" value="end" label="end"/>
                <el-option v-if="form.listenerType === '2'" value="take" label="take"/>
                <el-option v-if="form.listenerType === '1'" value="assignment" label="assignment"/>
                <el-option v-if="form.listenerType === '1'" value="complete" label="complete"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="2">
            <el-form-item label="值类型" prop="listenerValueType" class="listen">
              <el-radio-group style="margin: 0 5px;" @change="listenerValueTypeChange"
                              v-model="form.listenerValueType">
                <el-radio-button :label="'0'">Java类</el-radio-button>
                <el-radio-button :label="'1'">表达式</el-radio-button>
                <el-radio-button :label="'2'">代理表达式</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="值" prop="listenerValue" class="listen">
              <el-input :placeholder="listenerValuePlaceholder" v-model="form.listenerValue"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
      <span>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit(formInstance)">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getProcessListenerList,
  getProcessListenerDetails,
  addProcessListener,
  editProcessListener,
  delProcessListener
} from "@/api/workflow/process-listen.js";
import {Search, Refresh, Delete, Plus, Edit, Download} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {downLoadExcel} from "@/utils/downloadZip";
import Tag from '@/components/Tag.vue'
import {useCacheStore} from '@/stores/cache.js'

import Paging from "@/components/pagination/index.vue";

const cacheStore = useCacheStore()
//查询参数
const queryParams = reactive({
  listenerType: '',
  listenerName: '',
  listenerValueType: '',
})
//页面信息
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
})
const disabled = ref(true)
const list = ref([])
const queryForm = ref([])
const listenId = ref([])
const listenNameList = ref([])
const loading = ref(true)
const total = ref()
const title = ref('')
const isVisited = ref(false)
const form = ref()
const formInstance = ref()
const listenerValuePlaceholder = ref('请输入类路径')
const formRules = ref({
  listenerType: [
    {required: true, message: "监听器类型 1 : 任务监听 2: 执行监听不能为空", trigger: "change"},
  ],
  eventType: [
    {required: true, message: "监听类型 create assignment complete end take不能为空", trigger: "change"},
  ],
  listenerName: [
    {required: true, message: "监听器名称不能为空", trigger: "blur"},
  ],
  listenerValue: [
    {required: true, message: "监听器值不能为空", trigger: "blur"},
  ],
})
//搜索功能
const handleSearch = () => {
  getList()
}
//重置搜索
const handleReset = () => {
  queryForm.value.resetFields()
  getList()
}
//获取数据
const getList = async () => {
  let params = {
    ...queryParams,
    ...pageInfo
  }
  loading.value = true
  getProcessListenerList(params).then(res => {
    if (res.code === 1000) {
      list.value = res.data.rows
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg)
    }
    loading.value = false
  }).catch(err => {
    loading.value = false;
  })
}

const listenerValueTypeChange = () => {
  if (form.value.listenerValueType === '0') {
    listenerValuePlaceholder.value = '请输入类路径'
  } else {
    listenerValuePlaceholder.value = '请输入表达式'
  }
}
//重置from表单
const restFrom = () => {
  form.value = {
    listenerType: '1',
    listenerName: '',
    listenerValue: '',
    eventType: [],
    listenerValueType: '0',
  }
}
//取消
const handleCancel = () => {
  restFrom()
  isVisited.value = false
}
//提交
const handleSubmit = async (instance) => {
  if (!instance) return
  instance.validate(async (valid) => {
    if (!valid) return
    if (title.value === '新增系统内置监听器') {
      addProcessListener(form.value).then(res => {
        if (res.code === 1000) {
          ElMessage.success(res.msg)
          getList()
          isVisited.value = false
        } else {
          ElMessage.error(res.msg)
        }
      })
    } else {
      editProcessListener(form.value).then(res => {
        if (res.code === 1000) {
          ElMessage.success(res.msg)
          getList()
          isVisited.value = false
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}
//添加
const handleAdd = async () => {
  restFrom()
  title.value = "新增系统内置监听器"
  isVisited.value = true
  nextTick(()=>{
    // 清空校验
    formInstance.value.clearValidate()
  })
}
//修改
const handleEdit = async (id) => {
  restFrom()
  getProcessListenerDetails(id).then(res => {
    if (res.code === 1000) {
      form.value = res.data
      title.value = "编辑系统内置监听器"
      isVisited.value = true
      nextTick(()=>{
        // 清空校验
        formInstance.value.clearValidate()
      })
    } else {
      ElMessage.error(res.msg)
    }
  })
}
//导出excel
const handleExport = () => {
  downLoadExcel('/workflow/process/listener/export', {...queryParams})
}

//勾选table数据行的 Checkbox
const handleSelect = async (selection) => {
  if (selection.length !== 0) {
    disabled.value = false
    listenId.value = selection.map(item => item.id).join()
    listenNameList.value = selection.map(item => item.listenerName).join()
  } else {
    disabled.value = true
  }
}

//切换每页显示条数
const handleSizeChange = async (val) => {
  pageInfo.pageSize = val
  await getList()
}

//点击页码进行分页功能
const handleCurrentChange = async (val) => {
  pageInfo.pageNum = val
  await getList()
}
const handleMoreDelete=(listenId,listenNameList)=>{
  ElMessageBox.confirm(`确认删除名称为${listenNameList}的系统内置监听器吗?`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleDelete(listenId)
  })
}
//删除
const handleDelete = async (id) => {
    delProcessListener(id).then(res => {
      if (res.code === 1000) {
        ElMessage.success(res.msg)
        getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
}
getList()
</script>
