<template>
  <el-dialog :title="formTitle" v-model="dialogVisible" width="60%" append-to-body destroy-on-close>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="编号" prop="code">
            <el-input v-model="formData.code" placeholder="自动生成" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="批次号" prop="batchNo">
            <el-input v-model="formData.batchNo" placeholder="请选择工单批次号" readonly>
              <template #append>
                <el-button @click="openBatchSelector" type="primary" :icon="Search">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品" prop="productId">
            <el-select
              v-model="formData.productId"
              placeholder="请选择产品"
              clearable
              @change="handleProductChange"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工序路线" prop="processRouteId">
            <el-select
              v-model="formData.processRouteId"
              placeholder="请选择工序路线"
              clearable
              @change="handleProcessRouteChange"
            >
              <el-option
                v-for="item in processRouteList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工序" prop="processId">
            <el-select
              v-model="formData.processId"
              placeholder="请选择工序"
              clearable
              @change="handleProcessChange"
            >
              <el-option
                v-for="item in processList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="加工前重量" prop="beforeWeight">
            <el-input-number
              v-model="formData.beforeWeight"
              :precision="2"
              :step="0.1"
              @change="handleWeightChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="加工后重量" prop="afterWeight">
            <el-input-number
              v-model="formData.afterWeight"
              :precision="2"
              :step="0.1"
              @change="handleWeightChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="颜色" prop="color">
            <el-input v-model="formData.color" placeholder="请输入颜色" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="损耗率" prop="lossRate">
            <el-input v-model="formData.lossRate" disabled>
              <template #append>%</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="粗细度" prop="thickness">
            <el-input v-model="formData.thickness" placeholder="请输入粗细度" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数量" prop="quantity">
            <el-input-number v-model="formData.quantity" :precision="0" :step="1" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否合格" prop="qualified">
            <el-switch v-model="formData.qualified"  />
            <el-tooltip
              effect="dark"
              content="系统根据季节和损耗率自动判断是否合格"
              placement="top"
            >
              <el-icon class="el-icon--right"><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配料比例" prop="ratio">
            <el-input v-model="formData.ratio" placeholder="请输入配料比例" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              placeholder="选择开始时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker v-model="formData.endTime" type="datetime" placeholder="选择结束时间" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="data1">
            <el-input v-model="formData.data1" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="说明" prop="data2">
            <el-input v-model="formData.data2" placeholder="请输入说明" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="扩展" prop="data3">
            <el-input v-model="formData.data3" placeholder="请输入扩展" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>

<!-- 批次选择弹窗 -->
<el-dialog
  title="选择工单"
  v-model="batchSelectorVisible"
  width="70%"
  append-to-body
  destroy-on-close
>
  <el-table
    v-loading="workOrdersLoading"
    :data="workOrdersList"
    border
    style="width: 100%"
    @row-click="handleWorkOrderSelect"
    highlight-current-row
  >
    <el-table-column prop="code" label="工单编号" width="180" />
    <el-table-column prop="name" label="工单名称" width="220" />
    <el-table-column prop="productName" label="产品" width="150" />
    <el-table-column prop="routeName" label="工艺路线" width="150" />
    <el-table-column prop="status" label="状态" width="100">
      <template #default="scope">
        <el-tag v-if="scope.row.status === 3" type="warning">生产中</el-tag>
        <el-tag v-else-if="scope.row.status === 4" type="success">已完成</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="planQuantity" label="计划数量" width="100" />
    <el-table-column prop="producedQuantity" label="已生产" width="100" />
    <el-table-column prop="qualifiedQuantity" label="合格数量" width="100" />
  </el-table>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="batchSelectorVisible = false">取消</el-button>
    </div>
  </template>
</el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  createProcessQuality,
  updateProcessQuality,
  getProcessQuality,
  getProcessRouteList
} from '@/api/mes/quality/process-quality'
import { YVHgetProcessOperationPage } from '@/api/mes/production/process-operation'
import { ProductApi } from '@/api/erp/product/product'
import { formatDate } from '@/utils/formatTime'
import { QuestionFilled } from '@element-plus/icons-vue'
import { Search } from '@element-plus/icons-vue'

// 引入工单API接口
import { YVHgetWorkOrderPage, YVHgetWorkOrder } from '@/api/mes/production/workorder'

interface Product {
  id: number
  name: string
}

interface Process {
  id: number
  name: string
}

interface ProcessRoute {
  id: number
  name: string
  code: string
}

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const formTitle = ref('')
const formType = ref<'create' | 'update'>('create')
const loading = ref(false)
const formRef = ref()
const productList = ref<Product[]>([])
const processList = ref<Process[]>([])
const processRouteList = ref<ProcessRoute[]>([])

const batchSelectorVisible = ref(false)
const workOrdersList = ref([])
const workOrdersLoading = ref(false)

const formData = reactive({
  id: undefined as number | undefined,
  code: '',
  batchNo: '',
  productId: undefined as number | undefined,
  productName: '',
  processRouteId: undefined as number | undefined,
  processRouteName: '',
  processId: undefined as number | undefined,
  processName: '',
  beforeWeight: undefined as number | undefined,
  afterWeight: undefined as number | undefined,
  color: '',
  lossRate: undefined as string | undefined,
  thickness: '',
  quantity: undefined as number | undefined,
  qualified: false,
  ratio: '',
  startTime: undefined as Date | undefined,
  endTime: undefined as Date | undefined,
  data1: '',
  data2: '',
  data3: ''
})

const formRules = {
  // code: [{ required: true, message: '请输入编号', trigger: 'blur' }],
  batchNo: [{ required: true, message: '请输入批次号', trigger: 'blur' }],
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
  processId: [{ required: true, message: '请选择工序', trigger: 'change' }]
}

// 打开表单
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  formType.value = type as 'create' | 'update'
  formTitle.value = type === 'create' ? '新增工序质检' : '编辑工序质检'
  resetForm()

  // 加载产品列表
  const productRes = await ProductApi.getProductSimpleList()
  productList.value = productRes

  // 加载工序路线列表
  const routeRes = await getProcessRouteList()
  processRouteList.value = routeRes

  // 加载工序列表
  const processRes = await YVHgetProcessOperationPage({ pageNo: 1, pageSize: 100 })
  processList.value = processRes.list

  // 修改时加载详情
  if (type === 'update' && id) {
    loading.value = true
    try {
      const res = await getProcessQuality(id)
      // Convert date strings/timestamps to Date objects before assigning
      if (res.startTime) {
        res.startTime = new Date(res.startTime)
      }
      if (res.endTime) {
        res.endTime = new Date(res.endTime)
      }
      Object.assign(formData, res)
    } finally {
      loading.value = false
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      console.log(formRef)
      try {
        loading.value = true

        // 创建提交数据的副本并处理日期 - 使用时间戳而不是格式化字符串
        const submitData = {
          ...formData,
          startTime: formData.startTime ? (formData.startTime instanceof Date ? formData.startTime.getTime() : formData.startTime) : undefined,
          endTime: formData.endTime ? (formData.endTime instanceof Date ? formData.endTime.getTime() : formData.endTime) : undefined
        }

        if (formType.value === 'create') {
          await createProcessQuality(submitData)
          ElMessage.success('新增成功')
        } else {
          await updateProcessQuality(submitData)
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        emit('success')
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  formData.id = undefined
  formData.code = ''
  formData.batchNo = ''
  formData.productId = undefined
  formData.productName = ''
  formData.processRouteId = undefined
  formData.processRouteName = ''
  formData.processId = undefined
  formData.processName = ''
  formData.beforeWeight = undefined
  formData.afterWeight = undefined
  formData.color = ''
  formData.lossRate = undefined
  formData.thickness = ''
  formData.quantity = undefined
  formData.qualified = false
  formData.ratio = ''
  
  // 设置默认开始时间为当前时间
  const now = new Date()
  formData.startTime = now
  
  // 设置默认结束时间为开始时间后一天
  const tomorrow = new Date(now)
  tomorrow.setDate(tomorrow.getDate() + 1)
  formData.endTime = tomorrow
  
  formData.data1 = ''
  formData.data2 = ''
  formData.data3 = ''
}

// 产品选择变更
const handleProductChange = (val: number) => {
  const product = productList.value.find((item) => item.id === val)
  if (product) {
    formData.productName = product.name
  }
}

// 工序路线选择变更
const handleProcessRouteChange = (val: number) => {
  const route = processRouteList.value.find((item) => item.id === val)
  if (route) {
    formData.processRouteName = route.name
  }
}

// 工序选择变更
const handleProcessChange = (val: number) => {
  const process = processList.value.find((item) => item.id === val)
  if (process) {
    formData.processName = process.name
  }
}

// 重量变更时计算损耗率
const handleWeightChange = () => {
  if (formData.beforeWeight && formData.afterWeight && formData.beforeWeight > 0) {
    formData.lossRate = (
      ((formData.beforeWeight - formData.afterWeight) / formData.beforeWeight) *
      100
    ).toFixed(2)
  }
}

// 打开批次选择器
const openBatchSelector = async () => {
  batchSelectorVisible.value = true
  workOrdersLoading.value = true
  try {
    // 查询状态为3(生产中)和4(已完成)的工单
    const res = await YVHgetWorkOrderPage({
      pageNo: 1,
      pageSize: 100,
      status: [3, 4]
    })
    workOrdersList.value = res.list || []
  } catch (error) {
    console.error('Failed to fetch work orders:', error)
    ElMessage.error('获取工单列表失败')
  } finally {
    workOrdersLoading.value = false
  }
}

// 选择工单
const handleWorkOrderSelect = async (row: any) => {
  try {
    // 获取工单详细信息
    const workOrder = await YVHgetWorkOrder(row.id)
    
    // 填充批次号
    formData.batchNo = workOrder.code
    
    // 填充产品信息
    formData.productId = workOrder.productId
    formData.productName = workOrder.productName
    
    // 填充工艺路线信息
    formData.processRouteId = workOrder.routeId
    formData.processRouteName = workOrder.routeName
    
    // 如果有工序信息，更新工序选择下拉框
    if (workOrder.operations && workOrder.operations.length > 0) {
      // 更新工序列表，只显示已完成的工序
      processList.value = workOrder.operations
        .filter(op => op.status === 2) // 已完成的工序
        .map(op => ({
          id: op.operationId,
          name: op.operationName
        }))
      
      // 如果只有一个工序，自动选择
      if (processList.value.length === 1) {
        formData.processId = processList.value[0].id
        formData.processName = processList.value[0].name
      }
    }
    
    // 关闭批次选择器
    batchSelectorVisible.value = false
    
    // 显示成功消息
    ElMessage.success('工单信息已加载')
  } catch (error) {
    console.error('获取工单详情失败:', error)
    ElMessage.error('获取工单详情失败')
  }
}

defineExpose({ open })
</script>

<style scoped>
.dialog-footer {
  text-align: right;
  padding-top: 20px;
}
</style>
