<!-- 委托方满意度调查表列表 -->
<script name="QuestionnaireList" lang="ts" setup>
import { ElMessage } from 'element-plus'
import type { DateModelType } from 'element-plus'
import dayjs from 'dayjs'
import type{ ICustomerQuestionnaireInfo, IListQuery } from './customer-questionnaire'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getQuestionnaireList } from '@/api/resource/questionnaire'

const { proxy } = getCurrentInstance() as any
const router = useRouter()

// 查询条件
const searchQuery = ref<IListQuery>({
  customerName: '', // 填写单位
  writerName: '',
  writeTimeStart: '',
  writeTimeEnd: '',
  sendTimeStart: '',
  sendTimeEnd: '',
  offset: 1,
  limit: 20,
})
const dateRangeSend = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据 - 发送时间
const dateRangeWrite = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据 - 填写时间
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading

// 表头
const columns = ref<TableColumn[]>([
  { text: '调查表编号', value: 'questionnaireNo', align: 'center', width: '175' },
  { text: '填写单位', value: 'customerName', align: 'center' },
  { text: '填写人', value: 'writerName', align: 'center' },
  { text: '填写时间', value: 'writeTime', align: 'center', width: '180' },
  { text: '发送人', value: 'senderName', align: 'center' },
  { text: '发送时间', value: 'sendTime', align: 'center', width: '180' },
  { text: '填写状态', value: 'writeStatus', align: 'center', width: '120' },
])
const questionnaireList = ref<Array<ICustomerQuestionnaireInfo>>([]) // 表格数据

const reset = () => {
  searchQuery.value.customerName = ''
  searchQuery.value.writerName = ''
  searchQuery.value.writeTimeStart = ''
  searchQuery.value.writeTimeEnd = ''
  searchQuery.value.sendTimeStart = ''
  searchQuery.value.sendTimeEnd = ''
  searchQuery.value.offset = 1
  searchQuery.value.limit = 20
  dateRangeSend.value = ['', '']
  dateRangeWrite.value = ['', '']
}

const searchList = () => {
  fetchData(true)
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getQuestionnaireList(searchQuery.value).then((response) => {
    if (response.code === 200) {
      questionnaireList.value = response.data.rows

      total.value = parseInt(response.data.total)
    }
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.value.limit = val.size
  }
  if (val && val.page) {
    searchQuery.value.offset = val.page
  }
  fetchData(true)
}

// 批量发送
const batchAddQuestionnarie = () => {

}

// 添加（单个发送）
const addQuestionnarie = () => {
  router.push({
    query: {
      type: 'create',
    },
    path: 'questionnaire/detail',
  })
}

// 查看详情
const detail = (row: ICustomerQuestionnaireInfo) => {
  // 将行数据存入缓存 用来在路由之间传递数据
  sessionStorage.setItem('questionnaireInfo', JSON.stringify(row))

  router.push({
    query: {
      type: 'detail',
      id: row.id,
    },
    path: 'questionnaire/detail',
  })
}

const urging = (row: ICustomerQuestionnaireInfo) => {
  ElMessage.success(`满意度调查表 ${row.questionnaireNo} 填写消息已发送`)
}

watch(dateRangeSend, (val) => {
  if (val) {
    searchQuery.value.sendTimeStart = dayjs(val[0]).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(val[0]).format('YYYY-MM-DD')
    searchQuery.value.sendTimeEnd = dayjs(val[1]).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(val[1]).format('YYYY-MM-DD')
  }
  else {
    searchQuery.value.sendTimeStart = ''
    searchQuery.value.sendTimeEnd = ''
  }
})

watch(dateRangeWrite, (val) => {
  if (val) {
    searchQuery.value.writeTimeStart = dayjs(val[0]).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(val[0]).format('YYYY-MM-DD')
    searchQuery.value.writeTimeEnd = dayjs(val[1]).format('YYYY-MM-DD') === 'Invalid Date' ? '' : dayjs(val[1]).format('YYYY-MM-DD')
  }
  else {
    searchQuery.value.writeTimeStart = ''
    searchQuery.value.writeTimeEnd = ''
  }
})

onMounted(async () => {
  searchList()
})
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="searchList" @clear="reset">
      <search-item>
        <el-input v-model="searchQuery.customerName" placeholder="填写单位" clearable />
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.writerName" placeholder="填写人" clearable />
      </search-item>
      <search-item>
        <el-date-picker v-model="dateRangeSend" type="daterange" start-placeholder="发送时间（开始）" end-placeholder="发送时间（结束）" />
      </search-item>
      <search-item>
        <el-date-picker v-model="dateRangeWrite" type="daterange" start-placeholder="填写时间（开始）" end-placeholder="填写时间（结束）" />
      </search-item>
    </search-area>

    <!-- 表格数据展示 -->
    <table-container>
      <!-- 表头区域 -->
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/resource/customer/questionnaire/add')" icon="icon-batch" title="批量发送" @click="batchAddQuestionnarie" />
        <icon-button v-if="proxy.hasPerm('/resource/customer/questionnaire/add')" icon="icon-add" title="新建" @click="addQuestionnarie" />
      </template>

      <!-- 表格区域 -->
      <normal-table
        :data="questionnaireList" :total="total" :columns="columns"
        :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
        :list-loading="loadingTable"
        @change="changePage"
      >
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (searchQuery.offset - 1) * searchQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #columns>
          <el-table-column fixed="right" label="操作" align="center" width="130">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="detail(row)">
                详情
              </el-button>
              <el-button size="small" type="primary" link @click="urging(row)">
                催办
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>
