<template>
  <doc-alert title="【MES】生产领料管理" url="https://doc.iocoder.cn/mes/material-requisition/" />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="领料单号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入领料单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="工单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入工单编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option label="待审核" :value="1" />
          <el-option label="已审核" :value="2" />
          <el-option label="已领料" :value="3" />
          <el-option label="已取消" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-240px"
        />
      </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"
          plain
          @click="openForm('create')"
          v-hasPermi="['mes:material-requisition:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <!-- <el-button
          type="danger"
          plain
          @click="handleDelete(selectionList.map((item) => item.id))"
          v-hasPermi="['mes:material-requisition:delete']"
          :disabled="selectionList.length === 0"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 删除
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column label="领料单号" align="center" prop="code" min-width="120" />
      <el-table-column label="批次信息" align="center" prop="orderCode" min-width="120" />
      <el-table-column label="领料时间" align="center" prop="requisitionTime" min-width="150" sortable>
        <template #default="scope">
          {{ formatDate(scope.row.requisitionTime) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" min-width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applicantName" min-width="100" />
      <el-table-column label="审批人" align="center" prop="approverName" min-width="100" />
      <el-table-column label="备注" align="center" prop="remark" min-width="120" />
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="150" sortable>
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" min-width="160">
        <template #default="scope">
          <el-tooltip content="查看" placement="top">
            <el-button
              link
              type="primary"
              @click="handleView(scope.row.id)"
              v-hasPermi="['mes:material-requisition:query']"
            >
              <Icon icon="ep:view" />
            </el-button>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button
              v-if="scope.row.status === 1"
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['mes:material-requisition:update']"
            >
              <Icon icon="ep:edit" />
            </el-button>
          </el-tooltip>
          <el-tooltip content="审核" placement="top">
            <el-button
              v-if="scope.row.status === 1"
              link
              type="success"
              @click="handleApprove(scope.row.id)"
              v-hasPermi="['mes:material-requisition:approve']"
            >
              <Icon icon="ep:check" />
            </el-button>
          </el-tooltip>
          <el-tooltip content="确认领料" placement="top">
            <el-button
              v-if="scope.row.status === 2"
              link
              type="success"
              @click="handleComplete(scope.row.id)"
              v-hasPermi="['mes:material-requisition:complete']"
            >
              <Icon icon="ep:finished" />
            </el-button>
          </el-tooltip>
          <el-tooltip content="反审核" placement="top">
            <el-button
              v-if="scope.row.status === 2"
              link
              type="warning"
              @click="handleReverse(scope.row.id)"
              v-hasPermi="['mes:material-requisition:reverse']"
            >
              <Icon icon="ep:refresh-left" />
            </el-button>
          </el-tooltip>
          <!-- <el-tooltip content="删除" placement="top">
            <el-button
              v-if="[0, 4].includes(scope.row.status)"
              link
              type="danger"
              @click="handleDelete([scope.row.id])"
              v-hasPermi="['mes:material-requisition:delete']"
            >
              <Icon icon="ep:delete" />
            </el-button>
          </el-tooltip> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MaterialRequisitionForm ref="formRef" @success="getList" />
  <!-- 查看弹窗 -->
  <MaterialRequisitionView ref="viewRef" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/formatTime'
import {
  getMaterialRequisitionPage,
  approveMaterialRequisition,
  reverseMaterialRequisition
} from '@/api/mes/production/material-requisition'
import { Icon } from '@/components/Icon'
import MaterialRequisitionForm from './MaterialRequisitionForm.vue'
import MaterialRequisitionView from './MaterialRequisitionView.vue'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()
const currentUser = computed(() => userStore.user)

const loading = ref(true)
const list = ref<any[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  orderCode: undefined,
  status: undefined,
  createTime: undefined
})
const queryFormRef = ref()
const formRef = ref()
const viewRef = ref()
const selectionList = ref<any[]>([])

const getStatusType = (status: number) => {
  const types = {
    1: 'warning',
    2: 'success',
    3: 'success',
    4: 'danger'
  }
  return types[status]
}

const getStatusText = (status: number) => {
  const texts = {
    1: '待审核',
    2: '已审核',
    3: '已领料',
    4: '已取消'
  }
  return texts[status]
}

const getList = async () => {
  loading.value = true
  try {
    const res = await getMaterialRequisitionPage(queryParams)
    list.value = res.list
    total.value = res.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields?.()
  queryParams.code = undefined
  queryParams.orderCode = undefined
  queryParams.status = undefined
  queryParams.createTime = undefined
  handleQuery()
}

const openForm = (type: 'create' | 'update', id?: number) => {
  console.log('打开表单:', type, id)
  formRef.value.open(type, id)
}

const handleView = (id: number) => {
  console.log('查看详情:', id)
  viewRef.value.open(id)
}



const handleApprove = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要审核通过该领料单吗？', '提示', { type: 'warning' })
    await approveMaterialRequisition({
      id,
      approved: true,
      approverId: currentUser.value.id,
      approverName: currentUser.value.nickname,
      remark: ''
    })
    ElMessage.success('审核成功')
    getList()
  } catch {}
}

const handleComplete = async (id: number) => {
  console.log('确认领料:', id)
  formRef.value.openComplete(id)
}

const handleReverse = async (id: number) => {
  try {
    const { value: remark } = await ElMessageBox.prompt('请输入反审核原因', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: (value) => {
        if (!value) {
          return '反审核原因不能为空'
        }
        return true
      }
    })
    await reverseMaterialRequisition({
      id,
      reverserId: currentUser.value.id,
      reverserName: currentUser.value.nickname,
      remark
    })
    ElMessage.success('反审核成功')
    getList()
  } catch {}
}


const handleSelectionChange = (rows: any[]) => {
  selectionList.value = rows
}

/** 行点击操作 */
const handleRowClick = (row: any, _column: any, event: MouseEvent) => {
  // 检查是否点击了按钮、链接或其他交互元素
  const target = event.target as HTMLElement
  if (
    target.tagName === 'BUTTON' ||
    target.tagName === 'A' ||
    target.tagName === 'I' ||
    target.tagName === 'svg' ||
    target.closest('button') ||
    target.closest('a') ||
    target.closest('.el-button') ||
    target.closest('.el-checkbox')
  ) {
    return
  }

  // 待审核状态打开编辑页面，其他状态打开查看页面
  if (row.status === 1) {
    openForm('update', row.id)
  } else {
    handleView(row.id)
  }
}

onMounted(() => {
  getList()
})
</script>
