<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
        <el-form-item label="姓名" prop="userName">
          <UserSelect v-model="queryParams.userId" placeholder="请输入姓名搜索" style="width: 200px" />
        </el-form-item>

        <el-form-item label="用工形式" prop="employmentType">
          <el-select v-model="queryParams.employmentType" placeholder="请选择用工形式" clearable style="width: 200px">
            <el-option v-for="dict in employment_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="部门" prop="deptName">
          <el-input v-model="queryParams.deptName" placeholder="请输入部门" clearable style="width: 200px" />
        </el-form-item>

        <el-form-item label="最近合同开始时间" prop="recentContractStartTime">
          <el-date-picker v-model="queryParams.recentContractStartTime" type="date" value-format="YYYY-MM-DD"
            placeholder="选择日期" style="width: 200px" />
        </el-form-item>

        <el-form-item label="最近合同结束时间" prop="recentContractEndTime">
          <el-date-picker v-model="queryParams.recentContractEndTime" type="date" value-format="YYYY-MM-DD"
            placeholder="选择日期" style="width: 200px" />
        </el-form-item>

        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable style="width: 200px" />
        </el-form-item>

        <el-form-item label="开始时间" prop="contractStartTime">
          <el-date-picker v-model="queryParams.contractStartTime" type="date" value-format="YYYY-MM-DD"
            placeholder="选择日期" style="width: 200px" />
        </el-form-item>

        <el-form-item label="结束时间" prop="contractEndTime">
          <el-date-picker v-model="queryParams.contractEndTime" type="date" value-format="YYYY-MM-DD"
            placeholder="选择日期" style="width: 200px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="operation-container">
      <el-button type="info" plain icon="Upload" @click="handleImport">导入</el-button>
      <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
    </div>

    <el-table v-loading="loading" :data="list" border fit highlight-current-row style="width: 100%; margin-top: 20px;"
      @expand-change="handleExpandChange">
      <el-table-column type="expand">
        <template #default="scope">
          <div class="detail-container">
            <div class="detail-title">合同明细</div>
            <el-table :data="scope.row.contractDetailList || []" border fit size="small"
              style="width: 100%; margin-top: 10px;">
              <el-table-column label="序号" type="index" width="60" align="center" />
              <el-table-column label="合同名称" prop="contractName" align="center" min-width="200"
                show-overflow-tooltip />
              <el-table-column label="开始时间" prop="startTime" align="center" min-width="130" />
              <el-table-column label="结束时间" prop="endTime" align="center" min-width="130" />
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="序号" type="index" width="60" align="center">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="userName" align="center" min-width="100" />
      <el-table-column label="用工形式" prop="employmentType" align="center" min-width="100">
        <template #default="scope">
          <dict-tag :options="employment_type" :value="scope.row.employmentType" />
        </template>
      </el-table-column>
      <el-table-column label="部门" prop="deptName" align="center" min-width="150" show-overflow-tooltip />
      <el-table-column label="最近合同开始时间" prop="recentContractStartTime" align="center" min-width="150" />
      <el-table-column label="最近合同结束时间" prop="recentContractEndTime" align="center" min-width="150" />
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ContractExpirationLedger">
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import UserSelect from '@/components/UserSelect/index.vue'
import {
  listContractExpirationLedger,
  exportContractExpirationLedger,
  getContractExpirationLedger
} from '@/api/ledgerManage/contractExpirationLedger'
import { getToken } from '@/utils/auth'

const { proxy } = getCurrentInstance()

const { employment_type } = proxy.useDict('employment_type')

const loading = ref(false)
const total = ref(0)
const list = ref([])
const queryFormRef = ref(null)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userId: '',
  employmentType: '',
  deptName: '',
  recentContractStartTime: '',
  recentContractEndTime: '',
  contractName: '',
  contractStartTime: '',
  contractEndTime: ''
})

const upload = reactive({
  open: false,
  title: '',
  isUploading: false,
  url: '',
  headers: {
    Authorization: 'Bearer ' + getToken()
  }
})

const getList = async () => {
  loading.value = true
  try {
    const res = await listContractExpirationLedger(queryParams)
    list.value = res.rows || []
    total.value = res.total || 0
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.userId = ''
  queryParams.employmentType = ''
  queryParams.deptName = ''
  queryParams.recentContractStartTime = ''
  queryParams.recentContractEndTime = ''
  queryParams.contractName = ''
  queryParams.contractStartTime = ''
  queryParams.contractEndTime = ''
  handleQuery()
}

const handleExpandChange = async (row, expandedRows) => {
  if (expandedRows.includes(row) && (!row.contractDetailList || row.contractDetailList.length === 0)) {
    try {
      const res = await getContractExpirationLedger(row.id)
      row.contractDetailList = res.data?.contractDetailList || res.data || []
    } catch (error) {
      row.contractDetailList = []
    }
  }
}

const handleExport = () => {
  proxy.download(
    'ledger/contract-expiration/export',
    queryParams,
    `contract_expiration_ledger_${new Date().getTime()}.xlsx`
  )
}

const handleImport = () => {
  upload.title = '合同到期台账导入'
  upload.url = import.meta.env.VITE_APP_BASE_API + '/ledger/contract-expiration/import'
  upload.open = true
}

const importTemplate = () => {
  proxy.download(
    'ledger/contract-expiration/importTemplate',
    {},
    `contract_expiration_template_${new Date().getTime()}.xlsx`
  )
}

const handleFileUploadProgress = () => {
  upload.isUploading = true
}

const handleFileSuccess = (response, file) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs.uploadRef.handleRemove(file)
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      '</div>',
    '导入结果',
    { dangerouslyUseHTMLString: true }
  )
  getList()
}

const submitFileForm = () => {
  proxy.$refs.uploadRef.submit()
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="less">
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 10px;
}

.operation-container {
  margin-top: 10px;
}

.detail-container {
  padding: 10px 30px;
}

.detail-title {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}
</style>
