<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1200"       @close="cancel">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"

    >
      <el-form-item label="工艺流程" prop="techProc">
        <el-input v-model="techProcDisplay" placeholder="请输入工艺流程" />
      </el-form-item>
      <el-form-item label="状态" prop="enabledStatus">
        <el-select v-model="formData.enabledStatus" placeholder="请选择状态">
        <el-option
          v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_STATUS)"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" :rows="4" v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>

      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">工序信息</span>
        </template>
        <el-row>
          <el-col>
            <el-card class="hl-incard">
              <el-form ref="OrderYsDetailSubFormRef" :model="procList"   label-width="0"  >
                <el-table ref="procTable" :data="procList" class="hl-table"  @selection-change="handleProcSelectionChange" border>
                  <el-table-column type="selection" width="55"/>
                  <el-table-column prop="procCd" label="工序编码" align="center"/>
                  <el-table-column prop="procName" label="工序名称" align="center"/>
                  <el-table-column prop="remark" label="备注" align="center"/>
                  <el-table-column prop="creatorName" label="创建人" align="center"/>
                  <el-table-column prop="createTime" label="创建时间" align="center" :formatter="dateFormatter2"/>
                </el-table>


              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </el-card>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import * as TechProcApi from '@/api/biz/techproc'
import { dateFormatter2 } from '@/utils/formatTime'
import * as ProcApi from '@/api/biz/proc'
import { nextTick } from 'vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const procList = ref<ProcApi.ProcVO[]>([])
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false)
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined as number | undefined,
  techProc: undefined as string | undefined,
  enabledStatus: 0 as number,
  remark: undefined as string | undefined,
  procList: undefined as string[] | undefined,
})
const formRules = reactive({
  techProc: [{ required: true, message: '工艺流程不能为空', trigger: 'blur' }],
  enabledStatus: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const procTable = ref() // 工序表格 Ref
const selectedProcs = ref<ProcApi.ProcVO[]>([]) // 选中的工序行
const techProcDisplay = ref('') // 工序名称显示（按列表顺序）
const PROC_SEPARATOR = '-'
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  procList.value=await ProcApi.getProcList()

  if (id) {
    formLoading.value = true
    try {
      formData.value = await TechProcApi.getTechProc(id)
      // 编辑回显：工序名称显示
      techProcDisplay.value = convertCodeToName(formData.value.techProc)
      // 编辑回显：选中对应工序行
      setSelectedRows(formData.value.techProc)

    } finally {
      formLoading.value = false
    }
  }

}
defineExpose({ open }) // 提供 open、setSelectedRows 方法
const cancel = async () => {
  dialogVisible.value = false
  emit('success')
}
/** 工序编码转名称 */
const convertCodeToName = (codeStr: string | undefined) => {
  if (!codeStr) {
    return ''
  }
  const codes = codeStr.split(PROC_SEPARATOR)
  const names = codes.map(code => {
    const proc = procList.value.find(item => item.procCd === code)
    return proc ? proc.procName : code
  })
  return names.join(PROC_SEPARATOR)
}
/** 工序选择变化处理 - 按列表顺序排列 */
const handleProcSelectionChange = (rows: ProcApi.ProcVO[]) => {
  selectedProcs.value = rows
  // 获取选中的编码集合
  const selectedCodes = new Set(rows.map(item => item.procCd))
  // 按列表顺序过滤选中的工序
  const sortedSelected = procList.value.filter(item => selectedCodes.has(item.procCd))
  // 显示用：工序名称拼接（按列表顺序）
  techProcDisplay.value = sortedSelected.map(item => item.procName).join(PROC_SEPARATOR)
  // 存储用：工序编码拼接（按列表顺序）
  formData.value.techProc = sortedSelected.map(item => item.procCd).join(PROC_SEPARATOR)
  // 保存选中的工序编码列表（按列表顺序）
  formData.value.procList = sortedSelected.map(item => item.procCd)
}
/** 设置表格选中行 */
const setSelectedRows = (procCodes) => {
  if (!procCodes || !procTable.value || procList.value.length === 0) {
    return
  }
  let codes: string[] = []
  if (Array.isArray(procCodes)) {
    if (procCodes.length > 0 && typeof procCodes[0] === 'object') {
      codes = procCodes.map((item: any) => item.procCd || item.id || item)
    } else {
      codes = procCodes
    }
  } else if (typeof procCodes === 'string') {
    codes = procCodes.split(PROC_SEPARATOR)
  }
  procTable.value.clearSelection()
  if (codes.length > 0) {
    const codeSet = new Set(codes.map(c => String(c)))
    const rows = procList.value.filter(item => codeSet.has(String(item.procCd)))
    selectedProcs.value = rows
    nextTick(() => {
      rows.forEach(row => {
        procTable.value.toggleRowSelection(row, true)
      })
    })
  }
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TechProcApi.TechProcVO
    if (formType.value === 'create') {
      await TechProcApi.createTechProc(data)
      message.success(t('common.createSuccess'))
    } else {
      await TechProcApi.updateTechProc(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    techProc: undefined,
    enabledStatus: 0,
    remark: undefined,
    procList: undefined,
  }
  techProcDisplay.value = ''
  formRef.value?.resetFields()
}
</script>
