<template>
  <div class="workflow-page">
    <!-- 顶部按钮区域 -->
    <div class="button-group">
      <el-button
        type="primary"
        @click="addRow"
        :disabled="DisableCheckView || !props.enableStepTable||props.isPreset"
      >
        <el-icon>
          <Plus />
        </el-icon>
        添加
      </el-button>
      <el-button
        type="success"
        @click="addFromTemplate"
        :disabled="DisableCheckView || !props.enableStepTable||props.isPreset"
      >
        <el-icon>
          <DocumentAdd />
        </el-icon>
        从模板添加
      </el-button>
<!--      这里修改的时候 如果是预置的工作流禁止修改-->
      <el-button
        type="danger"
        @click="deleteSelected"
        :disabled="isDeleteDisabled||props.isPreset"
      >
        <el-icon>
          <Delete />
        </el-icon>
        删除
      </el-button>
    </div>
    <TemplateAddDialog
      v-model:visible="templateDialogVisible"
      @select-template="handleTemplateSelect"
    />
    <!-- 表格区域 -->
    <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="80" align="center">
          <template #default="{ row }">
            {{ row.stepIndex }}
          </template>
        </el-table-column>

        <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">
          <template #default="{ row }">

            <el-input
              :disabled="DisableCheckView"
              v-model="row.stepTitle"
              placeholder="标题"
              size="small"
              @blur="saveRowData(row)"
            />
          </template>
        </el-table-column>

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

        <el-table-column label="确认方式" width="130">
          <template #default="{ row }">
            <el-select
              :disabled="DisableCheckView"
              v-model="row.confirmType"
              placeholder="请选择确认方式"
              @change="saveRowData(row)"
              filterable
              clearable
            >
              <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="确认角色" width="130">
          <template #default="{ row }">
            <el-select
              :disabled="DisableCheckView"
              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="确认人员" width="130">
          <template #default="{ row }">
            <el-select
              :disabled="DisableCheckView"
              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="步骤操作说明" width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewStepDetail(row)">查看</el-button>
          </template>
        </el-table-column>

        <el-table-column label="取消作业" width="100" align="center">
          <template #default="{ row }">
            <el-checkbox
              :disabled="DisableCheckView||props.isPreset"
              v-model="row.enableCancelJob"
              @change="saveRowData(row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="设置锁定人" width="120" align="center">
          <template #default="{ row }">
            <el-checkbox
              :disabled="DisableCheckView||props.isPreset"
              v-model="row.enableSetLocker"
              @change="saveRowData(row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="设置共锁人" width="120" align="center">
          <template #default="{ row }">
            <el-checkbox
              :disabled="DisableCheckView||props.isPreset"
              v-model="row.enableSetColocker"
              @change="saveRowData(row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="添加共锁人" width="120" align="center">
          <template #default="{ row }">
            <el-checkbox
              :disabled="DisableCheckView||props.isPreset"
              v-model="row.enableAddColocker"
              @change="saveRowData(row)"
            />
          </template>
        </el-table-column>

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

        <el-table-column label="减少共锁人" width="120" align="center">
          <template #default="{ row }">
            <el-checkbox
              :disabled="DisableCheckView||props.isPreset"
              v-model="row.enableReduceColocker"
              @change="saveRowData(row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="上锁" width="80" align="center">
          <template #default="{ row }">
            <el-checkbox
              :disabled="DisableCheckView||props.isPreset"
              v-model="row.enableLock"
              @change="saveRowData(row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="共锁" width="80" align="center">
          <template #default="{ row }">
            <el-checkbox
              :disabled="DisableCheckView||props.isPreset"
              v-model="row.enableColock"
              @change="saveRowData(row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="解除共锁" width="100" align="center">
          <template #default="{ row }">
            <el-checkbox
              :disabled="DisableCheckView||props.isPreset"
              v-model="row.enableReleaseColock"
              @change="saveRowData(row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="解锁" width="80" align="center">
          <template #default="{ row }">
            <el-checkbox
              :disabled="DisableCheckView||props.isPreset"
              v-model="row.enableUnlock"
              @change="saveRowData(row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="结束作业" width="100" align="center">
          <template #default="{ row }">
            <el-checkbox v-model="row.enableEndJob" @change="saveRowData(row)" :disabled="DisableCheckView||props.isPreset"/>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { Plus, DocumentAdd, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Sortable from 'sortablejs'

import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { getIsSystemAttributeByKey } from '@/api/basic/configuration/index'
import {
  getWorkflowStepPage,
  insertWorkflowStep,
  updateWorkflowStep,
  deleteWorkflowStepList
} from '@/api/custonWorkflow/step'
import { getRolePage } from '@/api/system/role'
import { getRoleUser } from '@/api/system/user'
import * as UserApi from '@/api/system/user'
import TemplateAddDialog from './TemplateAdd.vue'

const route = useRoute()
const router = useRouter()
// 响应式数据
const tableData = ref([])
const selectedRows = ref([])
const tableRef = ref()
const templateDialogVisible = ref(false)
const props = defineProps({
  enableStepTable: {
    type: Boolean,
    required: true
  },
  modeId: {
    type: [String, Number],
    default: null
  },
  isPreset:{
    type: Boolean,
    required: true
  }
})
// 使用 computed 来处理复杂的禁用逻辑
const isDeleteDisabled = computed(() => {
  // 没有选中数据
  if (!hasSelection.value) {
    return true
  }

  // 处于查看模式
  if (DisableCheckView.value) {
    return true
  }

  // 是预设模式
  if (props.isPreset) {
    return true
  }

  // 步骤表格被禁用
  if (!props.enableStepTable) {
    return true
  }

  return false
})
// 计算属性
const hasSelection = computed(() => selectedRows.value.length > 0)
// 表格图标切换
const selectIcon = (row, iconUrl) => {
  row.stepIcon = iconUrl
  saveRowData(row) // 你已有的接口保存方法
}
// 查看步骤详情
const viewStepDetail = (row) => {
  // 临时存储步骤数据
  localStorage.setItem('tempStepData', JSON.stringify(row))

  // 跳转到详情页面
  router.push({
    name: 'WorkflowTableStepDetail',
    query: {
      stepId: row.id,
      modeId: route.query.id
    }
  })
}
// 生成新的表格行
const createNewRow = () => {
  return {
    modeId: route.query.id||props.modeId,
    stepTemplateId: undefined,
    stepIndex: 0,
    stepName: undefined,
    stepTitle: undefined,
    stepTitleShort: undefined,
    stepDescription: undefined,
    confirmType: undefined,
    confirmRoleCode: undefined,
    confirmUser: undefined,
    enableCancelJob: undefined,
    enableSetLocker: undefined,
    enableSetColocker: undefined,
    enableAddColocker: undefined,
    gotoStepAfterAddingColocker: undefined,
    enableReduceColocker: undefined,
    enableLock: undefined,
    enableColock: undefined,
    enableReleaseColock: undefined,
    enableUnlock: undefined,
    enableEndJob: undefined,
    id: undefined,
    stepIcon: undefined
  }
}
// 从模板添加
const addFromTemplate = () => {
  templateDialogVisible.value = true
}
// 接收模板选择结果
const handleTemplateSelect = async (templateData) => {
  console.log(templateData, '子组件传递的数据')

  try {
    // 遍历数组中的每个模板对象
    for (const template of templateData) {
      console.log('处理模板:', template)

      // 计算新的 stepIndex
      const newStepIndex = tableData.value.length + 1

      // 创建新行，只映射需要的字段
      const newRow = {
        ...createNewRow(),
        stepTitle: template.stepTitle,
        stepTitleShort: template.stepTitleShort,
        stepDescription: template.stepDescription,
        stepIcon: template.stepIcon,
        confirmType: template.confirmType,
        confirmRoleCode: template.confirmRoleCode,
        confirmUser: template.confirmUser,
        enableCancelJob: template.enableCancelJob,
        enableSetLocker: template.enableSetLocker,
        enableSetColocker: template.enableSetColocker,
        enableAddColocker: template.enableAddColocker,
        gotoStepAfterAddingColocker: template.gotoStepAfterAddingColocker,
        enableReduceColocker: template.enableReduceColocker,
        enableLock: template.enableLock,
        enableColock: template.enableColock,
        enableReleaseColock: template.enableReleaseColock,
        enableUnlock: template.enableUnlock,
        enableEndJob: template.enableEndJob,
        stepIndex: newStepIndex,
        modeId: route.query.id || props.modeId
      }
      console.log('创建的新行数据:', newRow)
      // 插入表格
      tableData.value.push(newRow)
      // 保存到后端
      await saveRowData(newRow)
    }
    ElMessage.success(`成功添加 ${templateData.length} 个模板`)
  } catch (error) {
    console.error('添加模板失败:', error)
    ElMessage.error('添加模板失败')
  }
}
// 添加新行
const addRow = () => {
  const newRow = createNewRow()

  // 计算 stepIndex（推荐使用最大值 + 1）
  const maxStepIndex =
    tableData.value.length > 0 ? Math.max(...tableData.value.map((r) => r.stepIndex || 0)) : 0
  newRow.stepIndex = maxStepIndex + 1

  // 先插入表格
  tableData.value.push(newRow)

  // 然后保存（传的就是表格里的对象引用）
  saveRowData(newRow)
}

// 删除选中行
const deleteSelected = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的行')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 行数据吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 获取选中行中已有 id 的（过滤未保存的行）
    const selectedWithId = selectedRows.value.filter((row) => row.id)
    const selectedIds = selectedWithId.map((row) => row.id)

    // 删除已有 id 的记录
    if (selectedIds.length > 0) {
      await deleteWorkflowStepList(selectedIds)
    }

    // 无论是否调用接口，前端都要同步移除这些行
    tableData.value = tableData.value.filter((row) => !selectedRows.value.includes(row))
    selectedRows.value = []

    ElMessage.success('删除成功')
  } catch (error) {
    console.error('删除失败', error)
    ElMessage.error('删除失败，请稍后重试')
  }
}

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 行拖拽
const initRowDrop = () => {
  nextTick(() => {
    const tbody = document.querySelector('.el-table__body-wrapper tbody')
    if (tbody) {
      Sortable.create(tbody, {
        animation: 150,
        handle: 'tr',
        ghostClass: 'sortable-ghost',
        chosenClass: 'sortable-chosen',
        dragClass: 'sortable-drag',
        onEnd: async ({ newIndex, oldIndex }) => {
          if (newIndex !== undefined && oldIndex !== undefined && newIndex !== oldIndex) {
            const movedRow = tableData.value.splice(oldIndex, 1)[0]
            tableData.value.splice(newIndex, 0, movedRow)

            for (let i = 0; i < tableData.value.length; i++) {
              tableData.value[i].stepIndex = i + 1
              await saveRowData(tableData.value[i])
            }

            ElMessage.success('拖拽排序完成')
          }
        }
      })
    }
  })
}

// 自动保存单行数据
const saveRowData = async (row) => {
  try {
    if (!row) return

    if (!row.id) {
      const res = await insertWorkflowStep(row)
      if (res) {
        // 写回 id，保持响应式引用不变
        row.id = res
        createNewRow()
        ElMessage.success('新增步骤成功')
      }
    } else {
      await updateWorkflowStep(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 {

    if (props.modeId || route.query.id) {
      const data = await getWorkflowStepPage({
        pageNo: 1,
        pageSize: -1,
        modeId: route.query.id || props.modeId
      })
      if (Array.isArray(data.list)) {
        // 按 stepIndex 从小到大排序
        tableData.value = data.list.sort((a, b) => {
          const aIndex = a.stepIndex || 0
          const bIndex = b.stepIndex || 0
          return aIndex - bIndex
        })

        console.log(
          '初始化数据完成，已按 stepIndex 排序:',
          tableData.value.map((row) => row.stepIndex)
        )
      } else {
        tableData.value = []
      }
    }
  } catch (error) {
    console.error('初始化表格数据失败:', error)
    ElMessage.error('加载步骤数据失败')
    tableData.value = []
  }
}
// 确认角色清空操作
const handleRoleClear = (row) => {
  row.confirmRoleCode = ''
  row.confirmUser = ''
}
const DisableCheckView = ref()
// 组件挂载时初始化
onMounted(() => {
  if (route.query.type == 'view') {
    DisableCheckView.value = true
  } else {
    DisableCheckView.value = false
  }
  initRowDrop() //行拖拽数据更新
  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>
