<template>
  <!-- 搜索 -->
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <el-form-item label="餐厅名称" prop="restaurantName">
        <TgInput @keyup.enter="handleQuery" v-model="queryParams.restaurantName" class="!w-240px" placeholder="请输入餐厅名称"/>
      </el-form-item>
      <el-form-item label="点餐月份" prop="month">
        <TgDatePicker type="month" v-model="queryParams.month" class="!w-240px" />
      </el-form-item>
      <el-form-item label="楼栋">
        <el-select
          v-model="queryParams.buildId"
          placeholder="选择楼栋"
          style="width: 180px"
          @change="handleBuildChange"
        >
          <el-option
            v-for="(item, index) in buildList"
            :key="index"
            :label="item.buildName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="楼层">
        <el-select v-model="queryParams.floorId" placeholder="选择楼层" style="width: 180px">
          <el-option
            v-for="(item, index) in floorList"
            :key="index"
            :label="item.floorName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="长者姓名" prop="elderId">
        <SelectElder v-model="queryParams.elderId" 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-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <TabBarBtn @add="openForm()" @export="handleExport" @import="handleInput" />
    <Table2
      v-loading="loading"
      :data="list"
      :columns="DishedStatisticColumns"
      :queryParams="queryParams"
      :opWidth="240"
      @edit="(arg) => openForm(arg)"
      @detail="(arg) => openForm(arg, true)"
      @del="handleDelete"
    >
    <template #pre="{scope}">
      <el-button v-if="scope.status == 0" link type="info" @click="handleCancel(scope)">取消</el-button>
    </template>
    <template #next="{scope}">
      <el-button @click="handleExportItem(scope)" link type="warning">导出</el-button>
    </template>
  </Table2>

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

  <Form ref="formRef" @success="getList" />

  <Import
    ref="importRef"
    @success="getList"
    :config="{
      title: '导入',
      downloadUrl: 'restaurant/dishesOrderStatistics/downloadExcel',
      excelTempName: '机构养老-【导入点餐统计】模板',
      importUrl: '/restaurant/dishesOrderStatistics/importDishesOrderStatisticsExcel',
      failExportUrl: ''
    }"
  />


</template>
<script lang="ts" setup>
import { getDishesOrderStatisticsPage, delDishesOrderStatistics, cancelDishesOrderStatistics, exportDishesOrderStatisticsExcel, exportDishesOrderItemExcel } from "@/api/system/foods";
import { DishedStatisticColumns } from '../column'
import Form from './Form.vue'
import download from '@/utils/download'
import Import from "@/components/ImportFile/index.vue";
import {ref} from "vue";
import { getBuildList } from '@/api/system/badManage'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

defineOptions({ name: 'OrderStatistics' })
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  restaurantName: undefined,
  month: undefined,
  elderId: undefined,
   buildId: '',
  floorId: '',
})
const queryFormRef = ref() // 搜索的表单
const floorList = ref([])
const buildList = ref([])

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getDishesOrderStatisticsPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

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

/** 添加/修改操作 */
const formRef = ref()
const openForm = (row: any = {}, detail: boolean = false) => {
  formRef.value.open(row.id, detail)
}

const handleBuildChange = (buildId: any) => {
  const selectedBuild = buildList.value.find((item: any) => item.id === buildId)
  if (selectedBuild) {
    floorList.value = selectedBuild.floorList || []
  }
}

const handleExport = async () => {
  const data = await exportDishesOrderStatisticsExcel(queryParams)
  download.excel(data, `点餐统计${Date.now()}.xls`)
}

const importRef = ref() //导入
//导入
const handleInput = () => {
  importRef.value.open()

}

const handleExportItem = async (item) => {
  const data = await exportDishesOrderItemExcel(item.id)
  download.excel(data, `点餐统计详情${Date.now()}.xls`)
}

const handleCancel = async (row) => {
  try{
      // 删除的二次确认
    await message.delConfirm('确定要取消吗？')
    await cancelDishesOrderStatistics(row.id)
    message.success(t('common.updateSuccess'))
    // 刷新列表
    await getList()
  }catch{}
}

/** 删除按钮操作 */
const handleDelete = async (id) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await delDishesOrderStatistics([id])
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(async() => {
  getList()
  try {
    buildList.value = await getBuildList({ tenantIds: userStore.orgTenantId[0] })
  } catch (e) {}
})
</script>
