<template>
  <Dialog  v-model="visibleRef" title="模板步骤" width="1300">
    <div class="workflow-page">
      <!-- 表格区域 -->
      <div class="table-container">
        <el-table
          ref="tableRef"
          :data="tableData"
          @selection-change="handleSelectionChange"
          border
          stripe
          row-key="id"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="图标" width="120" align="center">
            <template #default="{ row }">
              <el-popover placement="bottom" trigger="click" width="230">
                <!-- 图标选择面板 -->
                <div style="display: flex; flex-wrap: wrap; gap: 8px">
                  <div
                    v-for="icon in iconOptions"
                    :key="icon.value"
                    @click="() => selectIcon(row, icon.value)"
                    :style="{
                      border: row.stepIcon === icon.value ? '2px solid #409EFF' : '1px solid #ccc',
                      borderRadius: '4px',
                      padding: '2px',
                      cursor: 'pointer'
                    }"
                  >
                    <img
                      :src="icon.value"
                      :alt="icon.name"
                      style="width: 28px; height: 28px; object-fit: contain"
                    />
                  </div>
                </div>

                <!-- 触发元素：当前图标或按钮 -->
                <template #reference>
                  <div style="cursor: pointer; display: inline-block">
                    <img
                      v-if="row.stepIcon"
                      :src="row.stepIcon"
                      style="width: 32px; height: 32px; border-radius: 4px; border: 1px solid #ccc"
                    />
                    <el-button v-else type="primary" size="small">选择图标</el-button>
                  </div>
                </template>
              </el-popover>
            </template>
          </el-table-column>

          <el-table-column label="标题" width="180" prop="stepTitle" />

          <el-table-column label="标题缩写" width="120" prop="stepTitleShort" />

          <el-table-column label="确认方式" width="130">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SYS_STEP_CONFIRMTYPE" :value="scope.row.confirmType" />
            </template>
          </el-table-column>

          <el-table-column label="确认角色" width="150">
            <template #default="{ row }">
              <el-select v-model="row.confirmRoleCode" placeholder="" disabled>
                <el-option
                  v-for="dict in RoleOptions"
                  :key="dict.code"
                  :label="dict.name"
                  :value="dict.code"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="确认人员" width="130">
            <template #default="{ row }">
              <el-select v-model="row.confirmUser" placeholder="" disabled>
                <el-option
                  v-for="dict in UserOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="步骤操作说明" width="120" align="center">
            <el-button type="primary" link> 查看</el-button>
          </el-table-column>

          <el-table-column label="取消作业" width="100" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.enableCancelJob" />
            </template>
          </el-table-column>

          <el-table-column label="设置锁定人" width="120" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.enableSetLocker" />
            </template>
          </el-table-column>

          <el-table-column label="设置共锁人" width="120" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.enableSetColocker" />
            </template>
          </el-table-column>

          <el-table-column label="添加共锁人" width="120" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.enableAddColocker" />
            </template>
          </el-table-column>

          <el-table-column label="添加共锁人后跳转步骤" width="180">
            <template #default="{ row }">
              <el-input-number
                v-model="row.gotoStepAfterAddingColocker"
                :min="1"
                size="small"
                placeholder="步骤号"
              />
            </template>
          </el-table-column>

          <el-table-column label="减少共锁人" width="120" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.enableReduceColocker" />
            </template>
          </el-table-column>

          <el-table-column label="上锁" width="80" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.enableLock" />
            </template>
          </el-table-column>

          <el-table-column label="共锁" width="80" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.enableColock" />
            </template>
          </el-table-column>

          <el-table-column label="解除共锁" width="100" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.enableReleaseColock" />
            </template>
          </el-table-column>

          <el-table-column label="解锁" width="80" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.enableUnlock" />
            </template>
          </el-table-column>

          <el-table-column label="结束作业" width="100" align="center">
            <template #default="{ row }">
              <el-checkbox v-model="row.enableEndJob" />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { DICT_TYPE } from '@/utils/dict'
import { getIsSystemAttributeByKey } from '@/api/basic/configuration'
import { getWorkflowStepTemplatePage } from '@/api/custonWorkflow/stepTemplate'
import { getRolePage } from '@/api/system/role'
import * as UserApi from '@/api/system/user'
defineOptions({ name: 'TemplateAddDialog' })

// 响应式数据
const tableData = ref([])

const tableRef = ref()
const props = defineProps({
  visible: Boolean
})
const emit = defineEmits(['update:visible', 'select-template'])
const visibleRef = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})
// 控制选中项
const selectedRows = ref([])
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}
// 点击确定时回传数据
const handleConfirm = () => {
  emit('select-template', selectedRows.value)
  emit('update:visible', false)
}

const handleClose = () => {
  emit('update:visible', false)
}
// 表格图标切换
const selectIcon = (row, iconUrl) => {
  row.stepIcon = iconUrl
}

// 角色获取
const RoleOptions = ref()
const InitRole = async () => {
  const data = await getRolePage({ pageNo: 1, pageSize: 10 })
  RoleOptions.value = data.list
}
// 人员获取
const UserOptions = ref()
const InitUser = async () => {

  try {
    const data=await UserApi.getUserPage({ pageNo: 1, pageSize: -1 })
    UserOptions.value = data.list.map((row) => {
      return {
        label: row.nickname,
        value: row.id
      }
    })
  } catch (error) {
    console.error('获取角色数据失败:', error)
  }
}
// 在您的组件中添加
const iconOptions = ref([])

// 获取图标选项
const loadIconOptions = async () => {
  const icons = await getIcons()
  if (icons && icons.length > 0) {
    iconOptions.value = icons
    console.log('图标选项已加载:', iconOptions.value)
  }
}
// 获取步骤基础图标
const getIcons = async () => {
  try {
    const sysAttrKey1 = 'icon.step.all'
    const iconRes = await getIsSystemAttributeByKey(sysAttrKey1)
    console.log(iconRes, '获取到的图标配置')

    if (iconRes && iconRes.sysAttrValue) {
      // 将逗号分隔的字符串转换为数组
      const iconKeys = iconRes.sysAttrValue.split(',')
      console.log('图标键值列表:', iconKeys)

      // 批量获取每个图标的具体值
      const iconValues = await getIconValues(iconKeys)
      console.log('所有图标值:', iconValues)

      return iconValues
    }
  } catch (error) {
    console.error('获取图标失败:', error)
  }
}

// 批量获取图标值
const getIconValues = async (iconKeys) => {
  const iconValues = []

  // 方法1：串行请求（推荐，避免并发过多）
  for (const key of iconKeys) {
    try {
      const iconData = await getIsSystemAttributeByKey(key.trim())
      if (iconData && iconData.sysAttrValue) {
        iconValues.push({
          id: iconData.id,
          key: key.trim(),
          value: iconData.sysAttrValue,
          name: iconData.sysAttrName || key.trim()
        })
      }
    } catch (error) {
      console.error(`获取图标 ${key} 失败:`, error)
    }
  }

  return iconValues
}

// 初始化如果添加过步骤需要回显出来
const initTableData = async () => {
  try {
    const data = await getWorkflowStepTemplatePage({
      pageNo: 1,
      pageSize: -1
    })

    if (Array.isArray(data.list)) {
      // 按 stepIndex 从小到大排序
      tableData.value = data.list
    } else {
      tableData.value = []
    }
  } catch (error) {
    tableData.value = []
  }
}

// 组件挂载时初始化
onMounted(() => {
  loadIconOptions() //获取步骤图标信息
  InitRole() //初始化角色数据
  initTableData() //初始化步骤表格里的数据
  InitUser()
})

</script>

<style scoped lang="scss">
.workflow-page {
  padding: 20px;

  .button-group {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;

    .el-button {
      display: flex;
      align-items: center;
      gap: 5px;
    }
  }

  .table-container {
    .el-table {
      .el-input,
      .el-select,
      .el-input-number {
        width: 100%;
      }

      .el-textarea {
        .el-textarea__inner {
          resize: vertical;
        }
      }
    }
  }
}
</style>
