<template>
  <div class="cage-container">
    <!-- <van-tabs v-model:active="activeStatus" @change="changeType">
      <van-tab title="我的笼位" :name="MyCageType.MINE_CAGE"></van-tab>
      <van-tab title="历史笼位" :name="MyCageType.MY_CAGE_HISTORY"></van-tab>
    </van-tabs> -->
    <div class="search-wrap">
      <el-form :model="state.queryParams">
        <el-form-item prop="approveStatus">
          <el-select
            v-model="state.queryParams.approveStatus"
            style="width: 100%"
            placeholder="审批状态"
            clearable
            @change="search"
          >
            <el-option
              v-for="item in ApproveStatusList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="dateRange">
          <el-input
            v-model="dateRangeText"
            placeholder="请选择申请时间范围"
            readonly
            style="width: 100%"
            @click="showCalendar = true"
          >
            <template #suffix>
              <el-icon
                v-if="dateRangeText"
                style="cursor: pointer; margin-right: 8px"
                @click.stop="clearDateRange"
              >
                <Close />
              </el-icon>
              <el-icon
                style="cursor: pointer"
                @click.stop="showCalendar = true"
              >
                <Calendar />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>

    <div class="list-container">
      <van-list v-model:loading="state.loading" :finished="state.finished" finished-text="没有更多了" @load="onLoad">
        <van-cell v-for="item in state.pageList" :key="item" @click="handleCheckDetail(item)">
          <template #default>
            <div class="list">
              <header class="flex justify-between">
                <strong class="title">{{ `${item.userName}的笼位申请` }}</strong>
                <van-tag v-if="item.approveStatus == ApproveStatus.WAIT_SUBMIT" type="warning">待提交</van-tag>
                <van-tag v-else-if="item.approveStatus == ApproveStatus.APPROVING" type="primary">审核中</van-tag>
                <van-tag v-else-if="item.approveStatus == ApproveStatus.PASS" type="success">通过</van-tag>
                <van-tag v-else-if="item.approveStatus == ApproveStatus.REVOKE" type="success">撤销</van-tag>
                <van-tag v-else-if="item.approveStatus == ApproveStatus.REFUSE" type="danger">拒绝</van-tag>
              </header>
              <p class="inst-title">
                <span>课题名称</span>
                <span class="title ml8">{{ item.projectGroupName }}</span>
              </p>
              <p class="inst-title">
                <span>申请人</span>
                <span class="title ml8">
                  {{ item.userName }}
                </span>
              </p>
              <p class="inst-title">
                <span>申请时间</span>
                <span class="title ml8">
                  {{ formatToChineseDate(item.createdTime) }}
                </span>
              </p>
              <p class="inst-title">
                <span>开始时间</span>
                <span class="title ml8">
                  {{ formatToChineseDate(item.startDate) }}
                </span>
              </p>
              <p class="inst-title">
                <span>申请笼位(个)</span>
                <span class="title ml8">
                  {{ item.number }}
                </span>
              </p>
              <p class="inst-title">
                <span>退还笼位(个)</span>
                <span class="title ml8">
                  {{ item.returnNumber }}
                </span>
              </p>
              <p class="inst-title">
                <span>申请状态</span>
                <span class="title ml8">
                  {{ formatApproveStatus(Number(item.approveStatus)) }}
                </span>
              </p>
              <p class="inst-title">
                <span>动物类别</span>
                <span class="title ml8">
                  {{animalTypeList.find((type) => type.id === item.categoryId)?.name}}
                </span>
              </p>
              <p class="inst-title">
                <span>品种品系</span>
                <span class="title ml8">
                  {{ item.variety }}
                </span>
              </p>
              <p class="inst-title">
                <span>级别</span>
                <span class="title ml8">
                  {{LeavelList.find((leaveItem) => leaveItem.id === item.level)?.name || ''}}
                </span>
              </p>
              <footer class="flex justify-between mt16">
                <span class="title">
                  <el-button v-if="
                    item.approveStatus === ApproveStatus.PASS.toString() &&
                    item.returnStatus !== ReturnStatus.COMPLETE.toString() &&
                    userInfos.id === item.userId
                  " style="height: 25px" type="primary" @click.stop="handleRefundable(item)">退还</el-button>
                </span>
                <span class="time">{{ formatDate(new Date(item.createdTime), 'YYYY-mm-dd') }}</span>
              </footer>
            </div>
          </template>
        </van-cell>
      </van-list>
    </div>

    <DetailModal
      :showDialog="showDetailDialog"
      :isReturnCageList="false"
      ref="detailModalRef"
      @close="() => (showDetailDialog = false)"
    />
    <ReturnCageDialog
      ref="returnCageDialogRef"
      :currentRefundableItemNumber="currentRefundableItemNumber"
      :getTableData="handleRefresh"
    />
    <van-popup
      v-model:show="showCalendar"
      position="bottom"
      :style="{ height: '80vh' }"
      round
    >
      <van-calendar
        v-model:show="showCalendar"
        type="range"
        :min-date="new Date(1900, 0, 1)"
        @confirm="onDateRangeConfirm"
      />
    </van-popup>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, defineAsyncComponent, ComponentPublicInstance, computed } from 'vue'
import to from 'await-to-js'
import dayjs from 'dayjs'
import { Calendar, Close } from '@element-plus/icons-vue'

import { formatDate, formatToChineseDate } from '/@/utils/formatTime'
import { ApproveStatus, ReturnStatus, LeavelList, ApproveStatusList, MyCageType } from '/@/constants/pageConstants'
import { useUserInfos } from '/@/hooks/useUserInfos'
import { usePlatAnimalCageApplicationApi } from '/@/api/platform/animal'

interface ReturnCageDialogInstance extends ComponentPublicInstance {
  handleOpenRefundableDialog: (id: number) => void
}

interface DetailModalInstance extends ComponentPublicInstance {
  initForm: (id: number) => void
}

const DetailModal = defineAsyncComponent(() => import('/@/view/animal/application/components/Detail.vue'))
const ReturnCageDialog = defineAsyncComponent(() => import('/@/view/animal/application/components/ReturnCageDialog.vue'))

const { userInfos } = useUserInfos()
const platAnimalCageApplicationApi = usePlatAnimalCageApplicationApi()

const returnCageDialogRef = ref<ReturnCageDialogInstance>()
const detailModalRef = ref<DetailModalInstance>()

const showDetailDialog = ref<boolean>(false)
const activeStatus = ref<MyCageType>(MyCageType.MINE_CAGE)
const currentRefundableItemNumber = ref<number>(0)
const animalTypeList = ref([])
const dateTime = ref<any>([])
const showCalendar = ref(false)
const selectedDateRange = ref<[Date, Date] | null>(null)

const dateRangeText = computed(() => {
  if (selectedDateRange.value && selectedDateRange.value.length === 2) {
    const start = dayjs(selectedDateRange.value[0]).format('YYYY-MM-DD')
    const end = dayjs(selectedDateRange.value[1]).format('YYYY-MM-DD')
    return `${start} 至 ${end}`
  }
  return ''
})

const state = reactive({
  pageList: [] as any[],
  loading: false,
  finished: false,
  queryParams: {
    pageNum: 1,
    pageSize: 25,
    isMyself: 1,
    approveStatus: '',
    startDate: '',
    endDate: ''
  }
})

const getDicts = () => {
  Promise.all([platAnimalCageApplicationApi.getAnimalTypeList({})]).then(([animalType]) => {
    animalTypeList.value = animalType.data
  })
}
const changeType = () => {
  state.queryParams.pageNum = 1
  state.pageList = []
  onLoad()
}

const formatApproveStatus = (status: number) => {
  return ApproveStatusList.find((item) => item.id === status)?.name || ''
}

const handleRefundable = (row: any) => {
  currentRefundableItemNumber.value = row.number
  returnCageDialogRef.value.handleOpenRefundableDialog(row.id)
}

const handleRefresh = () => {
  resetQueryParams()
  onLoad()
}

const resetQueryParams = () => {
  state.pageList = []
  state.loading = false
  state.finished = false
  state.queryParams = {
    pageNum: 1,
    pageSize: 25,
    isMyself: 1,
    approveStatus: '',
    startDate: '',
    endDate: ''
  }
}

const setListPayload = () => {
  const payload: any = {
    ...state.queryParams
  }

  if (dateTime.value && dateTime.value.length === 2 && dateTime.value[0]) {
    payload.startDate = dayjs(dateTime.value[0]).format('YYYY-MM-DD')
  }

  if (dateTime.value && dateTime.value.length === 2 && dateTime.value[1]) {
    payload.endDate = dayjs(dateTime.value[1]).format('YYYY-MM-DD')
  }

  Object.entries(payload).forEach(([key, value]) => {
    if (value === '' || value === null) {
      delete payload[key as keyof typeof payload]
    }
  })

  return payload
}

const onLoad = async (isSearch?: boolean) => {
  state.loading = true
  const basePayload = setListPayload()
  const payload = {
    ...basePayload,
    pageNum: isSearch ? 1 : state.queryParams.pageNum
  }
  const apiRequest =
    activeStatus.value === MyCageType.MINE_CAGE
      ? platAnimalCageApplicationApi.getList(payload)
      : platAnimalCageApplicationApi.getMyCageHistoryList(payload)

  const [err, res]: ToResponse = await to(apiRequest)
  if (err) return
  const list = res?.data?.list || []
  state.loading = false

  if (!isSearch) {
    for (const item of list) {
      state.pageList.push(item)
    }
    state.queryParams.pageNum++
    if (list.length < state.queryParams.pageSize) {
      state.finished = true
    }
  } else {
    state.pageList = list
    state.queryParams.pageNum = 2
    state.finished = list.length < state.queryParams.pageSize
  }
}

const handleCheckDetail = (row: any) => {
  detailModalRef.value.initForm(row.id)
  showDetailDialog.value = true
}

const onDateRangeConfirm = (values: Date[]) => {
  if (values && values.length === 2) {
    selectedDateRange.value = [values[0], values[1]]
    dateTime.value = [
      dayjs(values[0]).format('YYYY-MM-DD'),
      dayjs(values[1]).format('YYYY-MM-DD')
    ]
    showCalendar.value = false
    search()
  }
}

const clearDateRange = () => {
  selectedDateRange.value = null
  dateTime.value = []
  state.queryParams.startDate = ''
  state.queryParams.endDate = ''
  search()
}

const search = () => {
  state.pageList = []
  state.queryParams.pageNum = 1
  state.finished = false
  onLoad(true)
}

onMounted(() => {
  onLoad()
  getDicts()
})
</script>

<style lang="scss" scoped>
.cage-container {
  position: relative;
  display: flex;
  flex-direction: column;

  .search-wrap {
    background: #fff;
    margin-bottom: 10px;
    padding: 15px;
  }

  .list-container {
    overflow-y: auto;
    padding: 10px;
    border-radius: 4px;
    flex: 1;
  }

  .van-list {
    .van-cell {
      background-color: #fff;

      +.van-cell {
        margin-top: 10px;
      }

      header,
      footer {
        color: #333;
      }

      .title {
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        text-align: left;
      }

      .inst-title {
        color: #333;
        text-align: left;
        flex: 1;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin-top: 4px;

        span:first-child {
          color: rgb(120, 120, 120);
        }
      }

      .time {
        color: #f69a4d;
      }
    }
  }
}
</style>
