<template>
  <el-dialog
    :title="formType === 'create' ? '新增工序路线与工位设置' : '编辑工序路线与工位设置'"
    v-model="visible"
    width="800px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" v-loading="formLoading">
      <!-- 基本信息 -->
      <el-form-item label="路线编码" prop="code">
        <el-input v-model="form.code" placeholder="请输入工序路线编码" />
      </el-form-item>
      <el-form-item label="路线名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入工序路线名称" />
      </el-form-item>
      <el-form-item label="路线描述" prop="description">
        <el-input v-model="form.description" placeholder="请输入工序路线描述" type="textarea" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" placeholder="请输入备注" />
      </el-form-item>

      <!-- 工序列表 -->
      <el-divider>工序列表</el-divider>
      <div class="mb-10px">
        <el-button type="primary" @click="handleAddOperation">
          <Icon icon="ep:plus" class="mr-5px" />添加工序
        </el-button>
      </div>

      <el-table :data="form.operations" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="工序" min-width="150" align="center">
          <template #default="{ row }">
            <el-select
              v-model="row.operationId"
              placeholder="请选择工序"
              @change="handleOperationChange($event, row)"
              style="width: 100%"
            >
              <el-option
                v-for="item in operationOptions"
                :key="item.id"
                :label="`${item.name} (${item.code})`"
                :value="item.id"
              >
                <span>{{ item.name }}</span>
                <span class="text-gray-400 ml-10px">({{ item.code }})</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="实际工时(分钟)" min-width="100" align="center">
          <template #default="{ row }">
            <el-input
              v-model.number="row.requiredTime"
              placeholder="输入分钟数"
              style="width: 100px"
              @blur="validateRequiredTime(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="150" align="center">
          <template #default="{ row }">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ $index }">
            <el-button
              link
              type="primary"
              :disabled="$index === 0"
              @click="moveOperation($index, 'up')"
            >
              <Icon icon="ep:arrow-up" />
            </el-button>
            <el-button
              link
              type="primary"
              :disabled="$index === form.operations.length - 1"
              @click="moveOperation($index, 'down')"
            >
              <Icon icon="ep:arrow-down" />
            </el-button>
            <el-button link type="danger" @click="removeOperation($index)">
              <Icon icon="ep:delete" />
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  YVHcreateProcessRoute,
  YVHupdateProcessRoute,
  YVHgetProcessRoute
} from '@/api/mes/production/process-route'
import { YVHgetProcessOperationList } from '@/api/mes/production/process-operation'
import { Icon } from '@/components/Icon'

// 生成工序路线编码
const generateRouteCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000)
    .toString()
    .padStart(3, '0')
  return `RT${year}${month}${day}${random}`
}

const emits = defineEmits(['success'])

const visible = ref(false)
const loading = ref(false)
const formLoading = ref(false) // 表单加载状态
const formType = ref<'create' | 'update'>('create')
const operationOptions = ref<any[]>([])

const form = reactive<any>({
  operations: []
})

const formRef = ref()

const rules = {
  code: [{ required: true, message: '请输入工序路线编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入工序路线名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  operations: [{ required: true, message: '请添加至少一个工序', trigger: 'change' }]
}

// 获取工序选项
const getOperationOptions = async () => {
  try {
    const res = await YVHgetProcessOperationList()
    operationOptions.value = res
    return res
  } catch (error) {
    console.error('获取工序列表失败:', error)
    ElMessage.error('获取工序列表失败')
    return []
  }
}

const open = async (type: 'create' | 'update', id?: number) => {
  formType.value = type
  visible.value = true
  formLoading.value = true // 开始加载，禁用表单

  try {
    // 重置表单
    Object.assign(form, {
      code: type === 'create' ? generateRouteCode() : '',
      name: '',
      description: '',
      status: 1,
      remark: '',
      operations: []
    })

    // 获取工序选项
    await getOperationOptions()

    if (type === 'update' && id) {
      const res = await YVHgetProcessRoute(id)
      Object.assign(form, res)
    } else if (type === 'create' && operationOptions.value.length > 0) {
      // 创建时默认添加一个工序
      handleAddOperation()
    }
  } catch (error) {
    console.error('初始化表单失败:', error)
    ElMessage.error('加载数据失败，请重试')
    visible.value = false
  } finally {
    formLoading.value = false // 加载完成，启用表单
  }
}

const handleAddOperation = () => {
  // 找到一个尚未添加的工序
  const usedOperationIds = form.operations.map((op: any) => op.operationId)
  const availableOperation = operationOptions.value.find((op) => !usedOperationIds.includes(op.id))

  const newOperation = {
    operationId: availableOperation?.id,
    operationCode: availableOperation?.code || '',
    operationName: availableOperation?.name || '',
    sequence: form.operations.length + 1,
    requiredTime: availableOperation?.standardTime || 30,
    remark: ''
  }

  form.operations.push(newOperation)

  // 如果选择了工序，自动填充相关信息
  if (availableOperation) {
    handleOperationChange(availableOperation.id, newOperation)
  }
}

const handleOperationChange = (operationId: number, row: any) => {
  const operation = operationOptions.value.find((item) => item.id === operationId)
  if (operation) {
    row.operationCode = operation.code
    row.operationName = operation.name
    // 如果requiredTime为0或未设置，则使用标准工时
    if (!row.requiredTime) {
      row.requiredTime = operation.standardTime || 30
    }
  }
}

const moveOperation = (index: number, direction: 'up' | 'down') => {
  const operations = form.operations
  if (direction === 'up' && index > 0) {
    ;[operations[index], operations[index - 1]] = [operations[index - 1], operations[index]]
  } else if (direction === 'down' && index < operations.length - 1) {
    ;[operations[index], operations[index + 1]] = [operations[index + 1], operations[index]]
  }
  // 更新序号
  operations.forEach((item: any, idx: number) => {
    item.sequence = idx + 1
  })
}

const removeOperation = (index: number) => {
  form.operations.splice(index, 1)
  // 更新序号
  form.operations.forEach((item: any, idx: number) => {
    item.sequence = idx + 1
  })
}

const submitForm = () => {
  if (form.operations.length === 0) {
    ElMessage.warning('请至少添加一个工序')
    return
  }

  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      if (formType.value === 'create') {
        await YVHcreateProcessRoute(form)
        ElMessage.success('新增成功')
      } else {
        await YVHupdateProcessRoute(form)
        ElMessage.success('修改成功')
      }
      visible.value = false
      emits('success')
    } finally {
      loading.value = false
    }
  })
}

const handleClose = () => {
  formRef.value?.resetFields()
}

// 对外暴露 open 方法
defineExpose({ open })

// 在script部分添加验证函数
const validateRequiredTime = (row: any) => {
  // 确保输入的是有效的非负整数
  if (isNaN(row.requiredTime) || row.requiredTime < 0) {
    row.requiredTime = 30 // 默认值
  } else {
    // 确保是整数
    row.requiredTime = Math.floor(Number(row.requiredTime))
  }
}
</script>

<style scoped>
.el-divider {
  margin: 16px 0;
}
</style>
