<script setup name="ProjectManageList">
import { getCurrentInstance, reactive, ref, toRefs, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import useAppStore from '@/store/modules/app'
import { changeRoute } from '@/utils/switchRoute'

import QueryForm from './QueryForm.vue'
import StrategyAddDialog from './modules/StrategyAddDialog.vue' // 统一对话框组件

import {
  getTableList,
  queryAll,
  remove,
  disableOrEnable
} from '@/api/desensitizationStrategy'

const appStore = useAppStore()
const router = useRouter()
const emit = defineEmits(['page'])
const { proxy } = getCurrentInstance()

const strategyDialogRef = ref()

onMounted(() => {
  handleQuery()
  queryAll().then(res => {
    if (res.flag) {
      roleList.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }).catch(err => {
    ElMessage.error(err.msg)
  })
})

function onReset(formQuery) {
  formQuery.resetFields()
  handleQuery()
}

const roleList = ref([])

function onQuery() {
  handleQuery()
}

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

const data = reactive({
  queryParams: {
    pageno: 1,
    pagesize: 8,
    remarks: '',
    state: '',
    strategyName: ''
  }
})

// 表格数据
const { queryParams } = toRefs(data)
const total = ref(0)
const loading = ref(false)
const projectId = ref(sessionStorage.getItem('projectId'))

// 查询列表
function getList() {
  loading.value = true
  getTableList({
    pageno: queryParams.value.pageno,
    pagesize: queryParams.value.pagesize,
    projectid: projectId.value,
    remarks: queryParams.value.remarks,
    roleGroup: '',
    state: queryParams.value.state,
    strategyName: queryParams.value.strategyName
  }).then(res => {
    if (res.flag) {
      tableData.value = res.data.list
      total.value = res.data.total
    }
    loading.value = false
  })
}

function pageProjectManage() {
  changeRoute()
  router.push({
    path: '/project/Project'
  })
}


const strategyAddDialogRef = ref()
/**
 * 新增策略
 */
function handleAdd() {

  dialog.value.title = '添加策略'

  dialog.value.type = 'addtactics'

  strategyAddDialogRef.value.openDialog('addtactics')
}

const tableData = ref([])
const dialog = ref({
  title: '',
  type: ''
})
/**
 * 查看策略详情
 */
const showDetail = (row) => {

  
  dialog.value.title = '详情'

  dialog.value.type = 'info'

  strategyAddDialogRef.value.openDialog('detail', row)
}

/**
 * 编辑策略
 */
const editStrategy = (row) => {


  dialog.value.title = '编辑策略'

  dialog.value.type = 'edit'

  strategyAddDialogRef.value.openDialog('edit', row)
}

/**
 * 删除策略
 */
const deleteStrategy = (row) => {
  ElMessageBox.confirm(
    `确定删除【${row.strategyName}】策略吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    remove({
      projectid: sessionStorage.getItem('projectId'),
      strategyId: row.strategyId
    }).then(res => {
      if (res.flag) {
        ElMessage.success('删除成功')
        handleQuery() // 刷新列表
      } else {
        ElMessage.error(res.msg)
      }
    }).catch(err => {
      ElMessage.error('删除失败')
    })
  }).catch(() => {
    // 用户取消删除
  })
}

/**
 * 启用/禁用策略
 */
const toggleStatus = (row) => {

  const newStatus = row.state === '1' ? '0' : '1'
  const action = newStatus === '1' ? '启用' : '禁用'
  
  ElMessageBox.confirm(
    `确定要${action}【${row.strategyName}】策略吗？`,
    `${action}确认`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {


    disableOrEnable({
      projectid: sessionStorage.getItem('projectId'),
      state:row.state === '1' ? '0' : '1',
      strategyId:row.strategyId

    }).then(res => { 
      if(res.flag){
        ElMessage({
          type: 'success',
          message: `${action}成功`
        })
       handleQuery()
      }
    })


  }).catch(() => {
    // 用户取消操作
  })
}
</script>

<template>
  <div class="app-container scroller">
    <PageTitle :back="true" @back="pageProjectManage">
      <template #title>
        返回项目管理
      </template>
      <template #buttons>
        <el-button
          icon="Plus"
          type="primary"
          @click="handleAdd"
        > 
          新增策略
        </el-button>
      </template>
    </PageTitle>
    
    <div class="app-container__body">
      <div>
        <query-form
          ref="QueryFormRef"
          v-model="queryParams"
          @query="onQuery"
          @reset="onReset"/>
        
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          v-loading="loading"
        >
          <el-table-column prop="strategyName" label="策略名称" min-width="120" fiexd/>
          <el-table-column prop="remarks" label="备注" min-width="120" show-overflow-tooltip />
          <el-table-column prop="createtime" label="创建时间" min-width="180" />
          <el-table-column prop="createuser" label="创建人" width="120" />
          <el-table-column prop="statezh" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.state === '1' ? 'success' : 'info'">
                {{ row.state === '1' ? '已启用' : '未启用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" align="center" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="showDetail(row)">详情</el-button>
              <el-divider direction="vertical" />
              <el-button link type="primary" size="small" @click="editStrategy(row)">编辑策略</el-button>
              <el-divider direction="vertical" />
              <el-button link type="danger" size="small" @click="deleteStrategy(row)">删除</el-button>
              <el-divider direction="vertical" />
              <el-button link type="success" size="small" @click="toggleStatus(row)">
                {{ row.state === '1' ? '禁用' : '启用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
          
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageno"
          v-model:limit="queryParams.pagesize"
          @pagination="getList"
        />
      </div>
    </div>

    <!-- 统一策略对话框组件 -->
    <StrategyAddDialog :title="dialog.title" ref="strategyAddDialogRef" @refresh="handleQuery" />
  </div>
</template>

<style lang="scss" scoped>
.table-item {
  margin-top: var(--container-pd);
  margin-bottom: 20px;
}

.item-content {
  margin: 8px 0;
  .label {
    width: 80px;
    color: #888;
  }
}

.flex-container { 
  display: flex;
}

.align-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.flex1 {
  flex: 1;
}
.flex-wrap {
  flex-direction: wrap;
}
</style>