<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="标题" prop="instructionsTitle">
        <el-input
          v-model="queryParams.instructionsTitle"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="物资类型" prop="materialsTypeId">
        <el-tree-select
          v-model="queryParams.materialsTypeId"
          :data="materialstypeOptions"
          :props="{ label: 'materialsTypeName', value: 'id' }"
          placeholder="请选择物资类型"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="请选择类型" class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.FILE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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="['iscs:instructions:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['iscs:instructions:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="说明编号" align="center" prop="id" width="200" />
      <el-table-column label="排序" align="center" prop="orderNum" width="100" />
      <el-table-column label="标题" align="center" prop="instructionsTitle" />
      <el-table-column label="物资类型" align="center" prop="materialsTypeName" />
      <el-table-column label="类型" align="center" prop="fileType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.FILE_TYPE" :value="scope.row.fileType" />
        </template>
      </el-table-column>
      <el-table-column label="文件" align="center" prop="fileUrl">
        <template #default="scope">
          <el-button link type="primary" @click="handlePreview(scope.row)">查看</el-button>
        </template>
      </el-table-column>
<!--      <el-table-column label="详情" align="center">-->
<!--        <template #default="scope">-->
<!--          <el-button link type="primary" @click="handleDetail(scope.row)">查看</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="添加时间" align="center" prop="createTime" :formatter="dateFormatter" />
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['iscs:instructions:update']"
          >
            修改
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['iscs:instructions:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-model:total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <InstructionsForm ref="formRef" @success="getList" />
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'
import * as InstructionsApi from '@/api/material/instructions/index'
import * as TypeApi from '@/api/material/type'
import InstructionsForm from './InstructionsForm.vue'

defineOptions({ name: 'Instructions' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const materialstypeOptions = ref([]) // 物资类型选项
const multiple = ref(true) // 非多个禁用
const ids = ref<number[]>([]) // 选中数组

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  instructionsTitle: undefined,
  materialsTypeId: undefined,
  fileType: undefined
})

const queryFormRef = ref() // 搜索的表单

/** 查询物资说明列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InstructionsApi.listInstructions(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取物资类型树形结构 */
const getMaterialTypes = async () => {
  const data = await TypeApi.listType({
    pageNo: 1,
    pageSize: -1
  })
  materialstypeOptions.value = handleTree(
    data.list,
    'id',
    'parentId',
    'children'
  )
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

/** 新增/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id?: number) => {
  const instructionsId = id || ids.value
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InstructionsApi.delInstructions(instructionsId)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 查看文件 */
const handlePreview = (row: any) => {
  if (row.fileUrl) {
    window.open(row.fileUrl, '_blank')
  }
}

/** 查看详情 */
const handleDetail = (row: any) => {
  router.push(`/mes/material/instructions/instructionsDetail?instructionsId=${row.instructionsId}`)
}

/** 初始化 **/
onMounted(async () => {
  await Promise.all([
    getList(),
    getMaterialTypes()
  ])
})
</script>
