<template>
  <div class="function-table">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" class="search-form">
      <el-form-item label="界面名称">
        <el-input
          v-model="searchForm.uiKey"
          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="handleAddUI">
        <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="uiKey" label="界面名称">
        <template #default="{ row }">
            <div>{{ formatUiName(row.uiKey) }}</div>
          </template>
      </el-table-column>
      <el-table-column prop="uiUrl" label="图片" >
        <template #default="{ row }">
          <el-image 
            v-if="row.uiUrl"
            style="height: 32px"
            :src="row.uiUrl"
            @click="showViewer(row.uiUrl)">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="funcIds" label="功能id数组" show-overflow-tooltip />
      <el-table-column prop="remark" label="描述" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建日期" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
        <el-button link type="primary" @click="handleUpdateUI(row)">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDeleteUI(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="[currentImage]"
      @close="closeViewer"
      append-to-body
    />

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

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox, ElImageViewer } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import FunctionDialog from './Dialog.vue'
import { addUi, getUiList, deleteUiList, updateUI } from '@/api/is/im/index'
import { useDict } from '@/utils/dict'

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

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

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

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

// 表单数据
const functionFormData = reactive({
  uiKey: '',
  remark: '',
  id: null,
  uiUrl: null,
  funcIds: null
})

// 重置搜索
function handleReset() {
  searchForm.uiKey = ''
  searchForm.remark = ''
  getDataList()
}

const isAdd = ref(true)
// 新增界面
function handleAddUI() {
  functionDialogTitle.value = '新增界面'
  functionFormData.uiKey = ''
  functionFormData.remark = ''
  functionFormData.id = null
  functionFormData.uiUrl = null
  functionFormData.funcIds = null
  isAdd.value = true
  functionDialogVisible.value = true
}

const handleUpdateUI = (row) => {
  functionDialogTitle.value = '编辑界面'
  functionFormData.uiKey = row.uiKey
  functionFormData.remark = row.remark
  functionFormData.id = row.id
  functionFormData.uiUrl = row.uiUrl || null
  functionFormData.funcIds = row.funcIds || null
  isAdd.value = false
  functionDialogVisible.value = true
}

// 确认界面操作
async function handleFunctionConfirm(valid, formData) {
  if (valid) {
    let res
    if (isAdd.value) {
      res = await addUi({
        ...formData,
        vehicleConfigId: props.selectNode.id
      })
      
    } else {
      res = await updateUI(formData)
    }
    if (res.code === 200) {
      getDataList()
      ElMessage.success(res.msg)
      functionDialogVisible.value = false
    } else {
      ElMessage.error(res.msg)
    }
  }
}

// 删除界面
function handleDeleteUI(row) {
  ElMessageBox.confirm(
    `确定要删除界面"${row.uiKey}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await deleteUiList(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 getUiList({
    ...searchForm,
    vehicleConfigId: props.selectNode.id
  })

  if (res.code === 200) {
    tableData.value = res.rows
    total.value = res.total
  }
}

const { ti_ui_config } = useDict("ti_ui_config");
const formatUiName = (uiKey) => {
  const dict = ti_ui_config.value.find(item => item.value === uiKey)
  return dict?.label || ''
}

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

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

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

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>