<template>
  <div class="function-table">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" class="search-form">
      <el-form-item label="功能名称">
        <el-input
          v-model="searchForm.funcKey"
          placeholder="请输入功能名称"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="描述">
        <el-input
          v-model="searchForm.remark"
          placeholder="请输入描述"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getDataList()">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格操作栏 -->
    <div class="table-actions">
      <div class="title">选中左侧的车机版本后，才显示数据</div>
      <el-button type="primary" @click="handleAddFunction">
        <el-icon><Plus /></el-icon>
        新增功能
      </el-button>
    </div>

    <!-- 功能表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="ID" />
      <el-table-column prop="funcKey" label="功能名称"/>
      <el-table-column prop="iconUrl" label="图片" >
        <template #default="{ row }">
          <el-image 
            v-if="row.iconUrl"
            style="height: 32px"
            :src="getImgUrl(row.iconUrl)"
            @click="showViewer(row.iconUrl)">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="描述" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建日期" ></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleUpdateFunction(row)">
            编辑
          </el-button>
          <el-button link type="primary" @click="handleDeleteFunction(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 手动控制的预览组件，append-to-body 使其挂载到 body 末尾 -->
    <ElImageViewer
      v-if="isViewerOpen"
      :url-list="[getImgUrl(currentImage)]"
      @close="closeViewer"
      append-to-body
    />

    <!-- 功能编辑对话框 -->
    <FunctionDialog
      v-model:visible="functionDialogVisible"
      :title="functionDialogTitle"
      :form-data="functionFormData"
      @confirm="handleFunctionConfirm"
    />
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox, ElImageViewer  } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import FunctionDialog from './FunctionDialog.vue'
import { addFunction, getFunction, updateFunction, deleteFunction } from '@/api/is/func/index'

const props = defineProps({
  selectNode: {
    type: Object,
    default: () => {}
  }
})

// 表格数据
const tableData = ref([])

const total = ref(0)
// 搜索表单
const searchForm = reactive({
  funcKey: '',
  remark: '',
  pageNum: 1,
  pageSize: 10,
})

// 对话框相关
const functionDialogVisible = ref(false)
const functionDialogTitle = ref('')

// 表单数据
const functionFormData = reactive({
  funcKey: '',
  remark: '',
  id: null,
  iconUrl: null
})

// 重置搜索
function handleReset() {
  searchForm.funcKey = ''
  searchForm.remark = ''
  searchForm.pageSize = 10
  searchForm.pageNum = 1
  getDataList()
}

const isAdd = ref(true)

// 新增功能
function handleAddFunction() {
  if (props.selectNode?.type !== 'version') {
    ElMessage.warning('请先选择车机版本')
    return
  }
  isAdd.value = true
  functionDialogTitle.value = '新增功能'
  functionFormData.funcKey = ''
  functionFormData.remark = ''
  functionFormData.iconUrl = null
  functionFormData.id = null
  functionDialogVisible.value = true
}

// 确认功能操作
async function handleFunctionConfirm(valid, data) {
  if (valid) {
    const newFunction = {
      ...data,
      vehicleConfigId: props.selectNode.id
    }
    let res
    if (isAdd.value) {
      res = await addFunction(newFunction)
    } else {
      res = await updateFunction(newFunction)
    }
    if (res.code === 200) {
      functionDialogVisible.value = false
      getDataList()
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg)
    }
  }
}

// 删除功能
function handleDeleteFunction(row) {
  ElMessageBox.confirm(
    `确定要删除功能"${row.funcKey}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await deleteFunction(row.id)
    if (res.code === 200) {
      getDataList()
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg)
    }
  }).catch(() => {
    // 用户取消删除
  })
}

const getDataList = async () => {
  if (props.selectNode?.type !== 'version') {
    ElMessage.warning('请先选择车机版本')
    return
  }
  const res = await getFunction({
    ...searchForm,
    vehicleConfigId: props.selectNode.id
  })
  if (res.code === 200) {
    tableData.value = res.rows
    total.value = res.total
  }
}

const getImgUrl = (url) => {
  return import.meta.env.VITE_API_URL + url
}

const isViewerOpen = ref(false);
const currentImage = ref('');

const showViewer = (url) => {
  currentImage.value = url;
  isViewerOpen.value = true;
};

const closeViewer = () => {
  isViewerOpen.value = false;
};

const handleUpdateFunction = (row) => {
  functionDialogTitle.value = '编辑功能'
  isAdd.value = false
  functionFormData.funcKey = row.funcKey
  functionFormData.remark = row.remark
  functionFormData.id = row.id
  functionFormData.iconUrl = row.iconUrl || null
  functionDialogVisible.value = true
}

watch(() => props.selectNode,
  (newVal) => {
    if (newVal && newVal.type === 'version') {
      getDataList()
    } else {
      tableData.value = []
    }
  }
)
</script>

<style lang="scss" scoped>
.function-table {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.table-actions {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: end;

  .title {
    font-size: 14px;
    color: #999;
  }
}
</style>