<template>
  <!-- 手机端布局 -->
  <div v-if="isMobile" class="mobile-requisition-list">
    <!-- 顶部操作栏 -->
    <div class="mobile-header">
      <div class="mobile-header__search">
        <el-input
          v-model="queryParams.code"
          placeholder="搜索领料单号"
          clearable
          @keyup.enter="handleQuery"
          :prefix-icon="Search"
        />
      </div>
      <div class="mobile-header__actions">
        <el-button :icon="Filter" circle @click="filterVisible = true" />
        <el-button type="primary" :icon="Plus" circle @click="openForm('create')" v-hasPermi="['mes:material-requisition:create']" />
      </div>
    </div>

    <!-- 快捷筛选 -->
    <div class="mobile-header__quick-filter">
      <div
        class="quick-filter-item"
        :class="{ active: quickFilterStatus === undefined }"
        @click="handleQuickFilter(undefined)"
      >全部</div>
      <div
        class="quick-filter-item"
        :class="{ active: quickFilterStatus === 1 }"
        @click="handleQuickFilter(1)"
      >待审核</div>
      <div
        class="quick-filter-item"
        :class="{ active: quickFilterStatus === 2 }"
        @click="handleQuickFilter(2)"
      >已审核</div>
      <div
        class="quick-filter-item"
        :class="{ active: quickFilterStatus === 3 }"
        @click="handleQuickFilter(3)"
      >已领料</div>
    </div>

    <!-- 卡片列表 -->
    <div class="mobile-list" v-loading="loading">
      <div v-if="list.length === 0 && !loading" class="mobile-empty">
        <el-empty description="暂无领料记录" />
      </div>
      <div
        v-for="row in list"
        :key="row.id"
        class="mobile-card"
        @click="handleCardClick(row)"
      >
        <div class="mobile-card__header">
          <span class="mobile-card__no">{{ row.code }}</span>
          <el-tag :type="getStatusType(row.status)" size="small">{{ getStatusText(row.status) }}</el-tag>
        </div>
        <div class="mobile-card__body">
          <div class="mobile-card__row">
            <span class="mobile-card__label">批次信息</span>
            <span class="mobile-card__value">{{ row.orderCode || '-' }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">领料时间</span>
            <span class="mobile-card__value">{{ formatDate(row.requisitionTime) }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">申请人</span>
            <span class="mobile-card__value">{{ row.applicantName || '-' }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">审批人</span>
            <span class="mobile-card__value">{{ row.approverName || '-' }}</span>
          </div>
        </div>
        <div class="mobile-card__footer" @click.stop>
          <el-button size="small" @click="handleView(row.id)">详情</el-button>
          <el-button size="small" type="primary" @click="openForm('update', row.id)" v-if="row.status === 1">编辑</el-button>
          <el-button size="small" type="success" @click="handleApprove(row.id)" v-if="row.status === 1">审核</el-button>
          <el-button size="small" type="success" @click="handleComplete(row.id)" v-if="row.status === 2">确认领料</el-button>
          <el-button size="small" type="warning" @click="handleReverse(row.id)" v-if="row.status === 2">反审核</el-button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="mobile-pagination" v-if="total > 0">
      <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" :page-sizes="[10, 20]" layout="total, prev, pager, next" :pager-count="5" @pagination="getList" />
    </div>

    <!-- 筛选抽屉 -->
    <el-drawer v-model="filterVisible" title="筛选条件" direction="btt" size="50%">
      <el-form :model="queryParams" ref="queryFormRef" label-position="top">
        <el-form-item label="工单编号" prop="orderCode">
          <el-input v-model="queryParams.orderCode" placeholder="请输入工单编号" clearable style="width:100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width:100%">
            <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="结束" style="width:100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleFilterConfirm">确认筛选</el-button>
      </template>
    </el-drawer>
  </div>

  <!-- PC端布局 -->
  <template v-else>
    <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-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>
  </template>

  <!-- 表单弹窗：添加/修改 -->
  <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 { Search, Filter, Plus } from '@element-plus/icons-vue'
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'
import { useWindowSize } from '@vueuse/core'

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

// 手机端筛选相关
const filterVisible = ref(false)
const quickFilterStatus = ref<number | undefined>(undefined)

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
  quickFilterStatus.value = undefined
  handleQuery()
}

/** 快捷筛选 */
const handleQuickFilter = (status: number | undefined) => {
  quickFilterStatus.value = status
  queryParams.status = status
  queryParams.pageNo = 1
  getList()
}

/** 筛选确认 */
const handleFilterConfirm = () => {
  filterVisible.value = false
  handleQuery()
}

/** 卡片点击 */
const handleCardClick = (row: any) => {
  if (row.status === 1) {
    openForm('update', row.id)
  } else {
    handleView(row.id)
  }
}

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>

<style lang="scss" scoped>
.mobile-requisition-list {
  padding: 12px;
  background: #f5f5f5;
  min-height: 100vh;
}

.mobile-header {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 12px;
  &__search { flex: 1; }
  &__actions { display: flex; gap: 4px; flex-shrink: 0; }
}

.mobile-header__quick-filter {
  display: flex;
  gap: 12px;
  margin: 8px 0;
  justify-content: flex-start;

  .quick-filter-item {
    padding: 4px 12px;
    font-size: 14px;
    border-radius: 20px;
    cursor: pointer;
    color: #909399;
    background: transparent;
    transition: all 0.2s;

    &.active {
      color: #fff;
      background: #409eff;
    }
  }
}

.mobile-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.mobile-empty { padding: 40px 0; }

.mobile-card {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  &__no { font-weight: 600; font-size: 15px; color: #303133; }
  &__body { font-size: 13px; }
  &__row { display: flex; justify-content: space-between; padding: 3px 0; }
  &__label { color: #909399; flex-shrink: 0; margin-right: 12px; }
  &__value {
    color: #606266;
    text-align: right;
    &--ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 200px; }
  }
  &__footer { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; padding-top: 10px; border-top: 1px solid #f0f0f0; }
}

.mobile-pagination {
  margin-top: 12px;
  display: flex;
  justify-content: center;
  :deep(.el-pagination) { flex-wrap: wrap; justify-content: center; }
}
</style>
