<template>
  <div>
    <el-form :model="queryParams" inline class="query-form" ref="queryForm" @submit.prevent="getList">
      <el-form-item label="部署名称" prop="deploymentName">
        <el-input v-model="queryParams.deploymentName" placeholder="请输入部署名称" clearable></el-input>
      </el-form-item>
      <!--    <el-form-item label="状态" prop="enable">-->
      <!--      <el-select v-model="queryParams.enable" placeholder="请选择状态" clearable filterable>-->
      <!--        <el-option-->
      <!--            v-for="dict in cacheStore.getDict('regular_enable')"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--        />-->
      <!--      </el-select>-->
      <!--    </el-form-item>-->
      <el-form-item>
        <el-button color="#DED0B2" @click="getList" :icon="Refresh">搜索</el-button>
        <el-button color="#DED0B2"  @click="handleAdd" :icon="Plus">新增</el-button>
        <el-button @click="handleReset" :icon="Refresh" >重置</el-button>
<!--        <el-button type="primary"  @click="handleExport" :icon="Download" plain>导出-->
<!--        </el-button>-->
      </el-form-item>
    </el-form>
    <div class="table">
      <el-table
          :data="list"
          row-key="id"
          :lazy="true"
          stripe
          ref="singleTable"
          v-loading="loading"
          @select="handleSelect"
          v-tabh
      >
        <el-table-column type="selection" width="30"/>
        <el-table-column label="序号" type="index" width="60" align="center"/>
        <el-table-column prop="deploymentName" label="部署名称" align="center"/>
        <el-table-column prop="version" label="版本" align="center">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注说明" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" align="center"/>
        <el-table-column prop="state" label="状态" align="center">
          <template #default="scope">
            <point-tag dict-type="normal_disable" :value="scope.row.state"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" size="mini"
                       @click="handleEdit(scope.row.deploymentId)" link>编辑
            </el-button>
            <!--            <el-button type="primary" size="mini"-->
            <!--                       @click="viewHistoricalVersion(scope.row)" link>历史-->
            <!--            </el-button>-->
            <!--            <popover-delete :name="scope.row.version" :type="'版本'"-->
            <!--                            @delete="handleDelete(scope.row.deploymentId)"/>-->
          </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="历史" width="800px">
      <div class="table">
        <el-table
            :data="historyVersionList"
            row-key="id"
            :lazy="true"
            ref="singleTable"
            v-loading="loading"
            v-tabh
        >
          <el-table-column prop="deploymentName" label="部署名称" align="center"/>
          <el-table-column prop="version" label="版本" align="center">
            <template #default="scope">
              <el-tag type="success">{{ scope.row.version }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态" align="center">
            <template #default="scope">
              <point-tag dict-type="normal_disable" :value="scope.row.state"/>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注说明" align="center"/>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="mini"
                         :style="scope.row.state=== '1' ?'color: red':''"
                         @click="suspendOrActivateHistoryView(scope.row)" link>
                {{ scope.row.state === "1" ? "停用" : "启用" }}
              </el-button>
              <popover-delete :name="scope.row.version" :type="'版本'"
                              @delete="handleDeleteHistoryVersion(scope.row.deploymentId)"/>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  activateProcessDefinition,
  getProcessDefinitionList,
  suspendProcessDefinition,
  getHistoryVersion,
  deleteHistoryVersion
} from "@/api/workflow/process-definition.js";
import {Search, Refresh, Delete, Plus, Edit, Download, Document} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {useCacheStore} from '@/stores/cache.js'
import PointTag from "@/components/PointTag.vue";
import Paging from "@/components/pagination/index.vue";

const dictStore = useCacheStore()
dictStore.setCacheKey(['normal_disable'])
const router = useRouter()

//查询参数
const queryParams = reactive({
  deploymentName: '',
  // startTime: null,
  // endTime: null,
  // state: undefined,
})

//页面信息
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
})
const loading = ref(true)
const list = ref([])
const queryForm = ref()
const total = ref()
const selectDefinition = ref(null)
const historyVersionList = ref([])
const singleTable = ref()
const isVisited = ref(false)
onActivated(()=>{
  getList()
})
//重置搜索
const handleReset = () => {
  queryForm.value.resetFields()
  getList()
}

//获取数据
const getList = async () => {
  let params = {
    ...queryParams,
    ...pageInfo
  }
  loading.value = true
  getProcessDefinitionList(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 handleAdd = () => {
  router.push({
    path: '/workflow/process/add',
  })
}

const handleEdit = (deploymentId) => {
  router.push({
    path: `/workflow/process/edit/${deploymentId}`,
  })
}
//查看历史版本
const viewHistoricalVersion = (row) => {
  selectDefinition.value = row
  loading.value = true
  getHistoryVersion(row.processDefinitionKey).then(res => {
    loading.value = false;
    res.data.forEach(row => {
      row.logo = JSON.parse(row.logo);
    });
    historyVersionList.value = res.data;
  }).catch(err => {
    ElMessage.error(err.response.data);
  });
  isVisited.value = true;
}

//启用,挂起历史版本
const suspendOrActivateHistoryView = (row) => {
  let tip = row.state === "1" ? " 您正在停用 [ " + row.deploymentName + " ] 流程，是否继续？" : " 您正在激活 [ " + row.deploymentName + " ] 流程，是否继续?";
  ElMessageBox.confirm(tip, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    // let processDefinitionId = row.processDefinitionId;
    if (row.state === "1") {
      //停用
      suspendProcessDefinition(row.processDefinitionId).then(res => {
        if (res.code === 1000) {
          viewHistoricalVersion(selectDefinition.value)
          ElMessage.success(res.msg);
        } else {
          ElMessage.error(res.msg);
        }
      });
    } else {
      //启用
      activateProcessDefinition(row.processDefinitionId).then(res => {
        if (res.code === 1000) {
          viewHistoricalVersion(selectDefinition.value)
          ElMessage.success(res.msg);
        } else {
          ElMessage.error(res.msg);
        }
      });
    }
  });
}

//删除工作流历史版本
const handleDeleteHistoryVersion = (deploymentId) => {
  deleteHistoryVersion(deploymentId).then(res => {
    viewHistoricalVersion(selectDefinition.value)
  })
}

//勾选table数据行的 Checkbox
const handleSelect = async (selection, row) => {
  if (selection.length !== 0) {
    disabled.value = false
    id.value = row.id
    if (selection.length > 1) {
      const del_row = selection.shift();
      singleTable.value.toggleRowSelection(del_row, false);
    }
  } else {
    disabled.value = true
  }
}

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

//点击页码进行分页功能
const handleCurrentChange = async (val) => {
  pageInfo.pageNum = val
  await getList()
}

getList()
</script>
