<template>
  <div>
    <div class="btn-container">
      <el-button type="primary" @click="openDialog">功能选择</el-button>
    </div>
    <el-table :data="selectList" height="260">
      <el-table-column
        label="功能名称"
        align="center"
        prop="funcKey"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <div>{{ formatFuncName(row.funcKey) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="iconUrl" label="图片" >
        <template #default="{ row }">
          <el-image 
            v-if="row.iconUrl"
            style="height: 32px"
            :src="row.iconUrl"
            @click="showViewer(row.iconUrl)">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          align="center"
          min-width="200"
        >
          <template #default="{row}">
            <el-button link type="primary" @click="unSelectRow(row)">删除</el-button>
          </template>
        </el-table-column>
    </el-table>

    <el-dialog title="选择功能" v-model="open" width="700px">
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        label-width="68px"
        @submit.prevent
      >
        <el-form-item label="功能名称" prop="funcKey">
          <el-input
            v-model="queryParams.funcKey"
            placeholder="请输入功能名称"
            clearable
            @keyup.enter="getList"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getList"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="tableRef"
        :data="tableList"
        :height="400"
        :tree-props="{ checkStrictly: true }"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          v-show="false"
        />
        <el-table-column
          label="功能名称"
          align="center"
          prop="funcKey"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <div>{{ formatFuncName(row.funcKey) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="iconUrl" label="图片" >
          <template #default="{ row }">
            <el-image 
              v-if="row.iconUrl"
              style="height: 32px"
              :src="row.iconUrl"
              @click="showViewer(row.iconUrl)">
            </el-image>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 手动控制的预览组件，append-to-body 使其挂载到 body 末尾 -->
    <ElImageViewer
      v-if="isViewerOpen"
      :url-list="[currentImage]"
      @close="closeViewer"
      append-to-body
    />
  </div>
</template>
<script setup>
import { onMounted } from "vue";
import { ElImageViewer } from 'element-plus'
import { getFunction } from '@/api/is/func/index'
import { useDict } from '@/utils/dict'

const props = defineProps({
  selectNode: {
    type: Object,
    default: () => {}
  },
  selectIds: {
    type: Array,
    default: () => []
  },
  funcIds: {
    type: String,
    default: ''
  }
});

const emits = defineEmits(["updateSelectRows"]);

const selectList = ref([]);
const tableList = ref([]);

const open = ref(false);
const openDialog = () => {
  open.value = true;
  setTimeout(() => {
    toggleRowSelection();
  }, 100);
};

const toggleRowSelection = () => {
  if (selectList.value.length > 0) {
    tableList.value.forEach((row) => {
      selectList.value.forEach((item) => {
        if (item.id === row.id) {
          tableRef.value.toggleRowSelection(row, true);
        }
      });
    });
  }
};

const queryParams = ref({
  pageNum: 1,
  pageSize: 100000,
  funcKey: ''
})

const getList = async () => {
  const res = await getFunction({
    ...queryParams.value,
    vehicleConfigId: props.selectNode.id
  })
  if (res.code === 200) {
    tableList.value = res.rows
  }
};

const getSelectList = async (funcIds) => {
  const res = await getFunction({
    funcIds,
    vehicleConfigId: props.selectNode.id
  })
  if (res.code === 200) {
    selectList.value = res.rows
  }
}

const resetForm = () => {
  queryParams.value.funcKey = ''
  getList()
}

const tableRef = ref();
const submitForm = () => {
  const rows = tableRef.value.getSelectionRows();
  selectList.value = rows;
  emits("updateSelectRows", rows);
  resetForm()
  open.value = false;
};

const cancel = () => {
  open.value = false;
  resetForm()
};

const unSelectRow = (row) => {
  if (tableRef.value) {
    tableRef.value.toggleRowSelection(row, false);
    const rows = tableRef.value.getSelectionRows();
    selectList.value = rows;
    emits("updateSelectRows", rows);
  } else {
    selectList.value = selectList.value.filter(item => {
      item.id !== row.id
    })
    emits("updateSelectRows", selectList.value)
  }
}

const { ti_function_config } = useDict("ti_function_config");
const formatFuncName = (funcKey) => {
  const dict = ti_function_config.value.find(item => item.value === funcKey)
  return dict?.label || ''
}

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

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

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

onMounted(() => {
  getList();
  if (props.funcIds) {
    getSelectList(props.funcIds);
  }
});

</script>
<style lang="scss" scoped>
.btn-container {
  text-align: right;
  margin-bottom: 12px;
}
</style>
