<template>
  <div class="workflow-page">
    <!-- 表格区域 -->
    <div class="table-container">
      <el-table ref="tableRef" :data="tableData" border stripe row-key="id">
        <el-table-column label="序号" width="80" align="center">
          <template #default="{ row }">
            {{ row.stepIndex }}
          </template>
        </el-table-column>

        <el-table-column label="图标" 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="标题">
          <template #default="{ row }">
            <el-input v-model="row.stepTitle" placeholder="标题" size="small"  @blur="saveRowData(row)"/>
          </template>
        </el-table-column>

        <el-table-column label="标题缩写">
          <template #default="{ row }">
            <el-input v-model="row.stepTitleShort" placeholder="标题缩写" size="small"  @blur="saveRowData(row)"/>
          </template>
        </el-table-column>

        <el-table-column label="确认方式">
          <template #default="{ row }">
            <el-select v-model="row.confirmType" placeholder="请选择确认方式" filterable clearable @change="saveRowData(row)">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SYS_STEP_CONFIRMTYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="确认角色">
          <template #default="{ row }">
            <el-select
              v-model="row.confirmRoleCode"
              placeholder="请选择确认角色"
              @change="saveRowData(row)"
              filterable
              clearable
              @clear="handleRoleClear(row)"
            >
              <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="确认人员">
          <template #default="{ row }">
            <el-select
              v-model="row.confirmUser"
              placeholder="请选择确认人员"
              @change="saveRowData(row)"
              filterable
              clearable
            >
              <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="步骤功能" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="StepFunction(row)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="步骤操作说明" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewStepDetail(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <!-- 步骤功能弹框 -->
    <StepFunctionDialog v-model:visible="stepFunctionVisible" :step-data="currentStepData" />
  </div>

</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { getIsSystemAttributeByKey } from '@/api/basic/configuration/index'
import {
  getJobTicketStepPage,
  insertJobTicketStep,
  updateJobTicketStep
} from '@/api/job/jobStep'
import { getRolePage } from '@/api/system/role'
import { getRoleUser } from '@/api/system/user'
import * as UserApi from '@/api/system/user'
import StepFunctionDialog from './StepFunction.vue'
import { getWorkflowStepPage } from '@/api/custonWorkflow/step'

const route = useRoute()
const router = useRouter()
// 响应式数据
const tableData = ref([])

const tableRef = ref()
const stepFunctionVisible = ref(false)
// 当前选中的步骤数据
const currentStepData = ref<any>({})
const props = defineProps({
  sopId: {
    type: [String, Number],
    default: null
  },
  modeId: {
    type: [String, Number],
    default: null
  }
})

// 表格图标切换
const selectIcon = (row, iconUrl) => {
  row.stepIcon = iconUrl
  saveRowData(row) // 你已有的接口保存方法
}
// 查看步骤详情
const viewStepDetail = (row) => {
  // 临时存储步骤数据
  localStorage.setItem('jobTableDetail', JSON.stringify(row))
  // 跳转到详情页面
  router.push({
    name: 'jobTableStepDetail',
    query: {
      stepId: row.id,
      ticketId: route.query.ticketId
    }
  })
}
//查看步骤功能
const StepFunction = (row) => {
  currentStepData.value = row
  stepFunctionVisible.value = true
}

// 自动保存单行数据
const saveRowData = async (row) => {
  try {
    if (!row) return
    await updateJobTicketStep(row)
    // 为了给确认人员传递查询条件
    if (row.confirmRoleCode) {
      await InitUser(row)
    }
    // ElMessage.success('更新步骤成功')
  } catch (error) {
    console.error('保存步骤失败', error)
    ElMessage.error('保存失败，请稍后重试')
  }
}

// 角色获取
const RoleOptions = ref()
const InitRole = async () => {
  const data = await getRolePage({ pageNo: 1, pageSize: 10 })
  RoleOptions.value = data.list
}
// 人员获取
const UserOptions = ref()
const InitUser = async (row) => {
  console.log(row, 'row')
  try {
    const data = await getRoleUser(row.confirmRoleCode)
    UserOptions.value = data.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 {
    // 1. 首先检查是否已经有SOP步骤数据
    const existingData = await getJobTicketStepPage({
      pageNo: 1,
      pageSize: -1,
      ticketId: route.query.ticketId || props.ticketId
    })

    // 2. 如果已经有数据，直接回显
    if (existingData && existingData.list && existingData.list.length > 0) {
      console.log('发现已存在的Ticket步骤数据，直接回显')
      tableData.value = existingData.list.sort((a, b) => {
        const aIndex = a.stepIndex || 0
        const bIndex = b.stepIndex || 0
        return aIndex - bIndex
      })
      // 初始化更新Sop步骤接口
      if (!existingData.list || existingData.list.length === 0) {
        // 如果没有现有数据，才调用新增接口
        await insertJobTicketStep(existingData.list)
        console.log('初始化Ticket步骤成功')
      } else {
        console.log('Ticket步骤已存在，跳过初始化')
      }
      console.log(
        '初始化数据完成，已按 stepIndex 排序:',
        tableData.value.map((row) => row.stepIndex)
      )
      return // 直接返回，不需要后续操作
    }

    // 3. 如果没有数据，且有modeId，则从工作流导入步骤
    if (props.modeId) {
      console.log('没有现有数据，开始从工作流导入步骤')
      const workflowData = await getWorkflowStepPage({
        pageNo: 1,
        pageSize: -1,
        modeId: props.modeId
      })

      if (workflowData && workflowData.list && workflowData.list.length > 0) {
        console.log('获取到工作流步骤数据:', workflowData.list.length, '个步骤')

        // 为每个步骤添加sopId
        const jobStepData = workflowData.list.map((item) => ({
          ...item,
          ticketId: route.query.ticketId || props.ticketId,
          stepId: item.id
        }))

        // 导入步骤数据
        await insertJobTicketStep(jobStepData)
        console.log('步骤数据导入成功')

        // 导入成功后，重新获取数据并回显
        const newData = await getJobTicketStepPage({
          pageNo: 1,
          pageSize: -1,
          ticketId: route.query.ticketId || props.ticketId
        })

        if (newData && newData.list && newData.list.length > 0) {
          tableData.value = newData.list.sort((a, b) => {
            const aIndex = a.stepIndex || 0
            const bIndex = b.stepIndex || 0
            return aIndex - bIndex
          })
          console.log('导入后数据回显完成:', tableData.value.length, '个步骤')
          ElMessage.success(`成功导入 ${newData.list.length} 个步骤`)
        }
      } else {
        console.log('工作流中没有步骤数据')
        tableData.value = []
      }
    } else {
      // 4. 没有modeId也没有现有数据，初始化为空
      console.log('没有modeId和现有数据，初始化为空表格')
      tableData.value = []
    }
  } catch (error) {
    console.error('初始化表格数据失败:', error)
    ElMessage.error('加载步骤数据失败')
    tableData.value = []
  }
}
// 确认角色清空操作
const handleRoleClear = (row) => {
  row.confirmRoleCode = ''
  row.confirmUser = ''
}

// 组件挂载时初始化
onMounted(() => {
  loadIconOptions() //获取步骤图标信息
  InitRole() //初始化角色数据
  initTableData() //初始化步骤表格里的数据
})
// 监听 confirmRoleCode 的变化
watch(
  () => tableData.value,
  async (newTableData) => {
    if (newTableData) {
      const data = await UserApi.getUserPage({ pageNo: 1, pageSize: -1 })
      console.log(data, 'user')
      UserOptions.value = data.list.map((row) => {
        return {
          label: row.nickname,
          value: row.id
        }
      })
    }
  },
  { immediate: true, deep: true }
)
</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>
