<template>
    <hc-card class="hc-project-collect-admin-list" w-to="1660">
        <template #headerToSearch>
            <hc-date-year v-model="searchForm.startYear" v-model:end="searchForm.endYear" />
            <div class="relative ml-3 w-[300px]">
                <hc-search-input v-model="searchForm.searchValue" text="搜索" color="#151921" @search="searchClick">
                    <!-- <template #prepend>
                        <el-select v-model="searchForm.year" placeholder="年份" clearable style="width: 80px">
                            <el-option label="2023" value="2023" />
                            <el-option label="2024" value="2024" />
                        </el-select>
                    </template> -->
                </hc-search-input>
            </div>
        </template>
        <template #extraToHeader>
            <div class="w-[120px]">
                <el-select v-model="searchForm.planYear" filterable clearable block placeholder="选择年份" @change="searchClick">
                    <el-option v-for="item in yearOptions" :key="item.value" :label="item.value" :value="item.key" />
                </el-select>
            </div>
            <div class="ml-2 w-[120px]">
                <el-select v-model="searchForm.projectStage" filterable clearable block placeholder="项目阶段" @change="searchClick">
                    <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
            <div class="ml-2 w-[100px]">
                <el-select v-model="searchForm.projectType" filterable clearable block placeholder="项目类型" @change="searchClick">
                    <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
        </template>
        <template #extra>
            <el-button type="success" class="ml-6" @click="reportsClick">生成报告</el-button>
            <el-button v-del-com:[delTableItem] type="danger" class="ml-2" :disabled="tableCheckKeys.length <= 0">批量删除</el-button>
            <el-button type="warning" class="ml-2" @click="importClick">导入</el-button>
            <!-- el-button v-yes-com:[deriveTableItem] type="primary" class="ml-2" :disabled="tableCheckKeys.length <= 0">批量导出</el-button -->
        </template>
        <HcTableList ref="tableRef" is-admin :datas="tableData" :plan-year="searchForm.planYear" @tap="rowNameClick" @check="tableCheck" @change="searchClick" />
        <template #action>
            <div>建设规模：共计 {{ buildTotal }} 公里</div>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>

        <!-- 生成报告 -->
        <hc-dialog v-model="isReportsShow" widths="24rem" title="生成报告" @close="reportsModalClose">
            <el-form ref="reportsFormRef" :model="reportsForm" :rules="reportsFormRules" label-position="top" label-width="auto">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="选择年份：" prop="year">
                            <el-select v-model="reportsForm.year" placeholder="选择年份">
                                <el-option v-for="item in projectYear" :key="item" :label="item" :value="item" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="选择季度：" prop="quarter">
                            <el-select v-model="reportsForm.quarter" placeholder="选择季度">
                                <el-option label="一季度" :value="1" />
                                <el-option label="二季度" :value="2" />
                                <el-option label="三季度" :value="3" />
                                <el-option label="四季度" :value="4" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="reportsModalClose">取消</el-button>
                    <el-button :loading="reportsLoding" type="primary" @click="saveReportsClick">确定</el-button>
                </div>
            </template>
        </hc-dialog>

        <!-- 导入 -->
        <hc-dialog v-model="isImportShow" widths="24rem" title="项目数据导入" :footer="false" @close="modalImportClose">
            <hc-form-upload
                v-model="importFile" class="hc-form-drop-upload"
                :options="{ num: 1, type: 'list', drop: true }"
                :upload="{ options: uploadOptions }" @success="uploadSuccess"
            />
            <div class="hc-flex mt-5">
                <span class="mr-2">模板下载:</span>
                <el-button color="#20C98B" size="small" class="text-white" :loading="downloadTemplateLoading" @click="downloadTemplate">点击下载</el-button>
            </div>
        </hc-dialog>
    </hc-card>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import HcTableList from '../modules/project-list.vue'
import { arrToId, formValidate, getArrValue, isNullES, newDownBlob } from 'js-fast-way'
import { getDictionaryData } from '~src/utils/tools'
import mainApi from '~api/project/project'
import { useClick } from 'hc-vue3-ui'

//事件
const emit = defineEmits(['edit'])
//渲染完成
onMounted(async () => {
    await getYearStation()
    await getProStation()
    await getProType()
    getTableData().then()
})
const tableRef = ref(null)
const buildTotal = ref(0)
//表格数据
const tableData = ref([])
const tableLoading = ref(false)
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const { error, code, data } = await mainApi.page(searchForm.value)
    //处理数据
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data.total || 0
        buildTotal.value = data?.buildTotal || 0
    } else {
        tableData.value = []
        searchForm.value.total = 0
        buildTotal.value = 0
    }
}

//项目阶段
const yearOptions = ref([])
const getYearStation = async () => {
    const { error, code, data } = await mainApi.getAllYear()
    //处理数据
    if (!error && code === 200) {
        yearOptions.value = getArrValue(data)
        const currentYear = new Date().getFullYear().toString()
        const hasCurrentYear = yearOptions.value.some(option => option.key == currentYear)
        searchForm.value.planYear = hasCurrentYear ? currentYear : yearOptions.value[0].key
  
    } else {
        yearOptions.value = []
       
    }

}
//项目阶段
const stateOptions = ref([])
const getProStation = async () => {
    stateOptions.value = await getDictionaryData('projectStage', true)

}
//项目类型
const typeOptions = ref([])
const getProType = async () => {
    typeOptions.value = await getDictionaryData('projectType', true)
  }

  
//搜索条件
const searchForm = ref({
    startYear: '', endYear: '', searchValue: '', planYear: '', projectStage:'', projectType:'',
    current: 1, size: 20, total: 0,
})
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

//分页
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格被选择
const tableCheckKeys = ref([])
const tableCheck = (row) => {
    tableCheckKeys.value = row
}

//项目名称被点击
const rowNameClick = (row) => {
    emit('edit', row)
}

//批量删除
const delTableItem = async (_, resolve) => {
    const ids = arrToId(tableCheckKeys.value)
    const { error, code, msg } = await mainApi.del(ids)
    if (!error && code === 200) {
        window.$message.success('删除成功')
        resolve()
        searchClick()
    } else {
        window.$message.error(msg ?? '删除失败')
        resolve()
    }
}

//批量导出
const deriveTableItem = async (_, resolve) => {
    /*const ids = arrToId(tableCheckKeys.value)
    const { error, val } = await mainApi.exportWorkfocus(ids)
    if (error) {
        window.$message?.error('数据异常')
        resolve()
        return
    }
    await newDownBlob(val)*/
    window.$message?.error('暂未开放')
    resolve()
}

//生成报告弹窗
const isReportsShow = ref(false)
const projectYear = ref([])
const reportsClick = async () => {
    isReportsShow.value = true
    //获取年份
    const { data } = await mainApi.getProjectYear()
    projectYear.value = getArrValue(data)
    //计算当前时间
    const today = new Date()
    const month = today.getMonth() // 0-11
    const quarter = Math.floor(month / 3) + 1
    reportsForm.value = {
        year: today.getFullYear(),
        quarter: quarter,
    }
}

//生成报告表单
const reportsFormRef = ref(null)
const reportsForm = ref({})
const reportsFormRules = {
    year: {
        required: true,
        trigger: 'blur',
        message: '请选择年份',
    },
    quarter: {
        required: true,
        trigger: 'blur',
        message: '请选择季度',
    },
}

//确认生成报告
const reportsLoding = ref(false)
const saveReportsClick = async () => {
    const isForm = await formValidate(reportsFormRef.value)
    if (!isForm) return false
    reportsLoding.value = true
    const { error, val } = await mainApi.buildReport(reportsForm.value)
    if (error) {
        reportsLoding.value = false
        window.$message?.error('数据异常')
        return
    }
    await newDownBlob(val)
    reportsLoding.value = false
    isReportsShow.value = false
}

//关闭弹窗
const reportsModalClose = () => {
    isReportsShow.value = false
}

//项目数据导入
const isImportShow = ref(false)
const importFile = ref([])
const uploadOptions = {
    url: '/api/blade-attach/project/import-project',
    size: 120,
    accept: '.xls,.xlsx',
    accept_tip: '请选择Excel文件',
}
const importClick = () => {
    isImportShow.value = true
}

//关闭项目数据导入弹窗
const modalImportClose = () => {
    isImportShow.value = false
}

//下载模板
const downloadTemplateLoading = ref(false)
const downloadTemplate = async () => {
    await useClick() //这里要使用 await 来等待
    downloadTemplateLoading.value = true
    const { error, data, msg } = await mainApi.exportTemplate()
    downloadTemplateLoading.value = false
    if (error && isNullES(data)) {
        window.$message?.error(msg ?? '数据异常')
        return
    }
    await window.electron.ipcRenderer.invoke('download-file', data)
    downloadTemplateLoading.value = false
}

//上传完成
const uploadSuccess = ({ res }) => {
    modalImportClose()
    window?.$message.success(res.msg)
    getTableData()
}
</script>

<style lang="scss">
.hc-project-collect-admin-list {
    .hc-card-action {
        display: flex;
        align-items: center;
    }
}
</style>
