<template>
  <div class="workflow-page">
    <!-- 顶部按钮区域 -->
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="100px"
      >
        <el-form-item label="标题" prop="stepTitle">
          <el-input
            v-model="queryParams.stepTitle"
            placeholder="请输入隔离点名称"
            clearable
            class="!w-240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" />
            重置
          </el-button>
          <el-button type="primary" @click="addRow">
            <el-icon>
              <Plus />
            </el-icon>
            添加
          </el-button>
          <el-button type="danger" plain :disabled="!hasSelection" @click="deleteSelected()">
            <Icon icon="ep:delete" class="mr-5px" />
            删除
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 表格区域 -->
    <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="100" align="center">
          <template #default="{ row }">
            <el-checkbox v-model="row.isPreset" @change="saveRowData(row)" />
          </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
              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
              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
              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
              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
              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 v-model="row.enableCancelJob" @change="saveRowData(row)" />
          </template>
        </el-table-column>

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

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

        <el-table-column label="添加共锁人" width="120" align="center">
          <template #default="{ row }">
            <el-checkbox v-model="row.enableAddColocker" @change="saveRowData(row)" />
          </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="步骤号"
              @change="saveRowData(row)"
            />
          </template>
        </el-table-column>

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

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

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

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

        <el-table-column label="解锁" width="80" align="center">
          <template #default="{ row }">
            <el-checkbox 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)" />
          </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'
import {
  getWorkflowStepTemplatePage,
  insertWorkflowStepTemplate,
  updateWorkflowStepTemplate,
  deleteWorkflowStepTemplateList
} from '@/api/custonWorkflow/stepTemplate'
import { getRolePage } from '@/api/system/role'
import { getRoleUser } from '@/api/system/user'
import * as UserApi from '@/api/system/user'

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  stepTitle: undefined
})
const route = useRoute()
const router = useRouter()
// 响应式数据
const tableData = ref([])
const selectedRows = ref([])
const tableRef = ref()

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

  // 跳转到详情页面
  router.push({
    name: 'StepTemplateDetail',
    query: {
      id: row.id,
    }
  })
}

// 生成新的表格行
const createNewRow = () => {

  // 新序号 = 最大序号 + 1
  const stepNumber = tableData.value.length + 1
  return {
    stepCode: `step_${stepNumber}`,
    isPreset: undefined,
    stepName: `步骤${stepNumber}`,
    stepIcon: 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
  }
}

// 添加新行
const addRow = () => {
  const newRow = createNewRow()

  // 先插入表格
  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 deleteWorkflowStepTemplateList(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].id = i + 1
              await saveRowData(tableData.value[i])
            }

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

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

    if (!row.id) {
      const res = await insertWorkflowStepTemplate(row)
      if (res) {
        // 写回 id，保持响应式引用不变
        row.id = res
        ElMessage.success('新增步骤成功')
      }
    } else {
      await updateWorkflowStepTemplate(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 handleQuery = () => {
  queryParams.pageNo = 1
  initTableData()
}
/** 重置按钮操作 */
const queryFormRef = ref()
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
// 初始化如果添加过步骤需要回显出来
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 = []
  }
}
// 确认角色清空操作
const handleRoleClear = (row) => {
  row.confirmRoleCode = ''
  row.confirmUser = ''
}

// 组件挂载时初始化
onMounted(() => {
  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>
