<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <TenantSelect v-model="queryParams.tenantIds" placeholder="请选择机构名称" prop="tenantIds" />
      <el-form-item label="长者姓名" prop="elderName">
        <el-input
          @keyup.enter="handleQuery"
          v-model="queryParams.elderName"
          placeholder="请输入长者姓名"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="床位号" prop="bedId">
        <SelectRoom v-model="queryParams.bedId" class="!w-240px" />
      </el-form-item>
      <el-form-item label="缴费状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" class="!w-240px">
          <el-option
            v-for="(dict, index) in getStrDictOptions(DICT_TYPE.SETTLEMENT_STATUS)"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!--      <el-form-item label="退住日期" prop="retreatDate">-->
      <!--        <el-date-picker-->
      <!--          v-model="queryParams.retreatDate"-->
      <!--          class="!w-240px"-->
      <!--          placeholder="请选择"-->
      <!--          end-placeholder="结束日期"-->
      <!--          start-placeholder="开始日期"-->
      <!--          type="date"-->
      <!--          value-format="YYYY-MM-DD"-->
      <!--        />-->
      <!--      </el-form-item>-->

      <!--      <el-form-item label="费用截止日期" prop="costDeadlineDate">-->
      <!--        <el-date-picker-->
      <!--          v-model="queryParams.costDeadlineDate"-->
      <!--          class="!w-240px"-->
      <!--          placeholder="请选择"-->
      <!--          end-placeholder="结束日期"-->
      <!--          start-placeholder="开始日期"-->
      <!--          type="date"-->
      <!--          value-format="YYYY-MM-DD"-->
      <!--        />-->
      <!--      </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>
    <el-button plain type="success" :loading="loading" @click="handleExport">
      <Icon class="mr-5px" icon="ep:download" />
      导出
    </el-button>

    <TabBarBtn />

    <Table2
      v-loading="loading"
      :data="list"
      :columns="levelSettleColumn"
      :queryParams="queryParams"
      :op-width="240"
      @print="handlePrint"
      @detail="(arg) => openForm(arg, true)"
      :showDetailCondition="showDetailCondition"
    >
      <template #pre="{ scope }">
        <!--        <el-button-->
        <!--          link-->
        <!--          type="success"-->
        <!--          @click="openRefundForm(scope)"-->
        <!--          v-hasPermi="['leave-settle:refund-settle']"-->
        <!--          v-show="scope.status == 1"-->
        <!--        >-->
        <!--          补充结算-->
        <!--        </el-button>-->
        <el-button
          link
          type="primary"
          @click="openForm(scope)"
          v-hasPermi="['leave-settle:settle']"
          v-show="scope.status == 0"
        >
          结算
        </el-button>
      </template>
    </Table2>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <RefundSettlement ref="refundFormRef" @success="getList" />
  <Print ref="printRef" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { getRefundSettlementOrderPage } from '@/api/elderly/fee/leave-settle'
import { levelSettleColumn } from '../column'
import RefundSettlement from './refund-settlement.vue'
import Print from './Print.vue'
import { useUserStore } from '@/store/modules/user'
import { exportWithCustomHeaders } from '@/utils/excel-export'
import { formatToDateTime } from '@/utils/dateUtil'
import { Message as message } from '@/layout/components/Message'
defineOptions({ name: 'LevelSettle' })
const userStore = useUserStore()
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  elderName: undefined,
  bedId: undefined,
  status: undefined,
  costDeadlineDate: undefined,
  retreatDate: undefined,
  refundAmount: undefined,
  tenantIds: userStore.orgTenantId
})
const queryFormRef = ref() // 搜索的表单
const router = useRouter()

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

/** 搜索按钮操作 */
const handleQuery = async () => {
  if (!queryFormRef.value) return
  const valid = await queryFormRef.value.validate()
  if (!valid) return
  queryParams.pageNo = 1
  getList()
}

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

/** 导出按钮操作 */
const handleExport = async () => {
  if (loading.value) return
  try {
    loading.value = true
    queryParams.pageNo = 1
    queryParams.pageSize = 99999
    const exportList = await getList()
    if (!exportList || exportList.length === 0) {
      message.error('暂无数据可以导出!')
      return
    }
    const statusOptions = getStrDictOptions(DICT_TYPE.SETTLEMENT_STATUS)
    const data = exportList.map((item) => ({
      ...item,
      statusLabel:
        statusOptions.find((dict) => String(dict.value) === String(item.status))?.label ||
        item.status,
      settlementTimeStr: item.settlementTime ? formatToDateTime(item.settlementTime) : '',
      createdTimeStr: item.createdTime ? formatToDateTime(item.createdTime) : ''
    }))
    const headers = [
      { key: 'tenantName', title: '所属机构', width: 40 },
      { key: 'elderName', title: '长者姓名', width: 40 },
      { key: 'bedName', title: '床位号', width: 40 },
      { key: 'statusLabel', title: '结算状态', width: 40 },
      { key: 'retreatDate', title: '退住日期', width: 40 },
      { key: 'costDeadlineDate', title: '费用截止日期', width: 40 },
      { key: 'refundableAmount', title: '应退金额', width: 40 },
      { key: 'receivableAmount', title: '应收金额', width: 40 },
      { key: 'refundAmount', title: '实缴金额', width: 40 },
      { key: 'settlementTimeStr', title: '结算时间', width: 40 },
      { key: 'settlementPersonName', title: '结算人', width: 40 },
      { key: 'orderNumber', title: '结算单号', width: 40 },
      { key: 'createdBy', title: '创建人', width: 40 },
      { key: 'createdTimeStr', title: '创建时间', width: 40 }
    ]
    await exportWithCustomHeaders(data, headers, `退住结算-${formatToDateTime()}.xlsx`, '退住结算')
  } catch (e) {
    message.error('导出失败!')
    console.log(e)
  } finally {
    queryParams.pageSize = 10
    loading.value = false
  }
}

/** 添加/修改操作 */
// const formRef = ref()
const openForm = (row: any = {}, isDetail: boolean = false) => {
  // formRef.value.open(row.id, row.elderId, isDetail)
  router.push({
    name: isDetail ? 'LevelSettleDetail' : 'LevelSettleForm', //详情和结算是同一个 form
    params: {
      id: row.id,
      elderId: row.elderId,
      tId: row.tenantId,
      isDetail: isDetail
    }
  })
}

// 补充结算
const refundFormRef = ref()
const openRefundForm = (row) => {
  refundFormRef.value.open(row.id)
}

const showDetailCondition = (row) => {
  return row.status == 1
}

const printRef = ref()
const handlePrint = (row) => {
  printRef.value.open(row.id, row.status == 1)
}
/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
