<template>
    <div class="hc-layout-box">
        <HcNewCard>
            <template #header>
                <HcTooltip keys="gauge-station-add">
                    <el-button hc-btn type="primary" @click="AddRowClick">
                        <HcIcon name="add-box" />
                        <span>新增</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="gauge-station-import">
                    <el-button hc-btn @click="importModalClick">
                        <HcIcon name="upload-cloud" />
                        <span>导入</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="gauge-station-export">
                    <el-button :loading="downloadLoading" hc-btn @click="exportModalClick">
                        <HcIcon name="download" />
                        <span>导出</span>
                    </el-button>
                </HcTooltip>
                <div class="w-60 ml-6">
                    <el-input v-model="searchForm.name" clearable placeholder="请输入测站点或关键字进行搜索" @keyup="keyUpEvent" />
                </div>
                <div class="ml-2">
                    <el-button type="primary" @click="searchClick">
                        <HcIcon name="search-2" />
                        <span>搜索</span>
                    </el-button>
                </div>
            </template>
            <template #extra>
                <HcNewSwitch :datas="tabsTypeData" size="default" :keys="tabsTypeKey" @change="tabsTypeChange" />
            </template>
            <HcTable v-if="tabsTypeKey === '0'" :column="levelTableColumn" :datas="levelTable" :loading="tableLoading" is-new :index-style="{ width: 60 }">
                <template #action="{ row }">
                    <HcTooltip keys="gauge-station-edit">
                        <el-button size="small" text type="primary" @click="handleLevelEdit(row)">编辑</el-button>
                    </HcTooltip>
                    <HcTooltip keys="gauge-station-del">
                        <el-button size="small" text type="danger" @click="handleLevelDelete(row)">删除</el-button>
                    </HcTooltip>
                </template>
            </HcTable>
            <HcTable v-if="tabsTypeKey === '1'" :column="traverseTableColumn" :datas="traverseTable" :loading="tableLoading" is-new :index-style="{ width: 60 }">
                <template #action="{ row }">
                    <HcTooltip keys="gauge-station-edit">
                        <el-button size="small" text type="primary" @click="handleTraverseEdit(row)">编辑</el-button>
                    </HcTooltip>
                    <HcTooltip keys="gauge-station-del">
                        <el-button size="small" text type="danger" @click="handleTraverseDelete(row)">删除</el-button>
                    </HcTooltip>
                </template>
            </HcTable>
            <template #action>
                <HcPages :pages="searchForm" @change="pageChange" />
            </template>
        </HcNewCard>

        <!-- 新增/编辑 弹框 -->
        <hc-new-dialog v-model="showRowModal" :title="`${formRowValue?.id ? '编辑' : '新增'}${tabsTypeKey === '1' ? '导线点' : '水准点'}`" widths="47rem">
            <el-form ref="formRowRef" :model="formRowValue" :rules="rulesRow" label-width="auto" size="large">
                <el-form-item label="点名称" prop="name">
                    <el-input v-model="formRowValue.name" placeholder="请输入点名称" />
                </el-form-item>
                <el-form-item v-if="tabsTypeKey === '1'" label="X坐标(m)" prop="x">
                    <el-input v-model="formRowValue.x" placeholder="请输入X坐标(m)" />
                </el-form-item>
                <el-form-item v-if="tabsTypeKey === '1'" label="Y坐标(m)" prop="y">
                    <el-input v-model="formRowValue.y" placeholder="请输入Y坐标(m)" />
                </el-form-item>
                <el-form-item label="高程(m)" prop="h">
                    <el-input v-model="formRowValue.h" placeholder="请输入高程(m)" />
                </el-form-item>
                <el-form-item label="等级">
                    <el-select v-model="formRowValue.level" block>
                        <el-option v-for="(item, index) in personData" :key="index" :label="item.label" :value="item.value" placeholder="请选择等级" />
                    </el-select>
                </el-form-item>
                <el-form-item label="里程" prop="milestone">
                    <el-input v-model="formRowValue.milestone" placeholder="请输入对应的设计里程" />
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="formRowValue.remark" :autosize="{ minRows: 3, maxRows: 5 }" placeholder="请输入文字说明" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="showRowModal = false">取消</el-button>
                    <el-button :loading="saveFormLoading" hc-btn type="primary" @click="saveFormClick">提交</el-button>
                </div>
            </template>
        </hc-new-dialog>
        <!-- 导入 弹框 -->
        <hc-new-dialog v-model="showImportModal" :title="`导入${tabsTypeKey === '1' ? '导线点' : '水准点'}`" widths="47rem">
            <div class="hc-import-modal-box">
                <div class="tip-box">
                    <span>请先下载导入模板(</span>
                    <a
                        v-if="tabsTypeKey === '1'"
                        class="text-link"
                        href="https://bladex-chongqing-info.oss-cn-hangzhou.aliyuncs.com//upload/20230821/d9ac14618c04b91b03c5746a24867e54.xlsx"
                        target="_blank"
                    >导线点导入模板</a>
                    <a
                        v-if="tabsTypeKey === '0'"
                        class="text-link"
                        href="https://bladex-chongqing-info.oss-cn-hangzhou.aliyuncs.com//upload/20230821/cdc62c130027dafa575dfb478cedba61.xlsx"
                        target="_blank"
                    >水准点导入模板</a>
                    <span> )，按模板样式编辑测站点后，再点击"选择文件"按钮选择编辑好的文件，并点击底部的"确认导入"按钮即可导入成功!</span>
                </div>
                <div class="upload-box">
                    <el-upload
                        ref="uploadRef" v-model:file-list="fileList" :accept="accept" :action="action"
                        :auto-upload="false" :data="addition" :headers="getTokenHeader()" :limit="1"
                        :on-error="handleUploadError" :on-exceed="handleUploadExceed"
                        :on-progress="handleUploadProgress" :on-success="handleUploadFinish"
                    >
                        <template #trigger>
                            <el-button :loading="importLoading" type="primary">选择文件</el-button>
                        </template>
                    </el-upload>
                </div>
                <div class="text-orange">导入模板格式示例：</div>
                <div v-if="tabsTypeKey === '1'" class="demo-img-box">
                    <img alt="" src="../../assets/view/152221@2x.png">
                </div>
                <div v-if="tabsTypeKey === '0'" class="demo-img-box">
                    <img alt="" src="../../assets/view/152211@2x.png">
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="showImportModal = false">取消</el-button>
                    <el-button
                        :disabled="fileList.length <= 0" :loading="importLoading" hc-btn type="primary"
                        @click="handleImportClick"
                    >
                        确认导入
                    </el-button>
                </div>
            </template>
        </hc-new-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '~src/store'
import stationApi from '~api/gauge/station'
import { getTokenHeader } from '~src/api/request/header'
import { genFileId } from 'element-plus'
import { downloadBlob, formValidate, getArrValue } from 'js-fast-way'
import { delMessageV2 } from '~com/message/index.js'

//初始变量
const router = useRouter()
const useRoutes = useRoute()
const useAppState = useAppStore()

//路由参数
const routerQuery = useRoutes?.query
const typeName = routerQuery?.type || '0'

//全局变量
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)

//类型tab数据和相关处理
const tabsTypeKey = ref(typeName)
const tabsTypeData = ref([
    { key: '0', name: '水准点' },
    { key: '1', name: '导线点' },
])
const tabsTypeChange = (item) => {
    tabsTypeKey.value = item?.key
    searchForm.value.type = item?.key
    searchForm.value.current = 1
    getTableData()
    //路由跳转
    router.push({
        path: useRoutes.path,
        query: {
            type: item?.key,
        },
    })
}
//渲染完成
onMounted(() => {
    searchForm.value.type = typeName
    getTableData()
})

//搜索表单
const searchForm = ref({
    projectId: projectId.value, contractId: contractId.value, name: null, type: '0',
    current: 1, size: 20, total: 0,
})

//回车搜索
const keyUpEvent = (e) => {
    if (e.key === 'Enter') {
        searchForm.value.current = 1
        getTableData()
    }
}

//重新搜索数据
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

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

//导线点
const traverseTableColumn = ref([
    { key: 'name', name: '测站点名称' },
    { key: 'x', name: 'X坐标(m)' },
    { key: 'y', name: 'Y坐标(m)' },
    { key: 'h', name: '高程(m)' },
    { key: 'level', name: '等级' },
    { key: 'milestone', name: '里程' },
    { key: 'remark', name: '备注' },
    { key: 'action', name: '操作', width: '130' },
])
const traverseTable = ref([])

//水准点
const levelTableColumn = ref([
    { key: 'name', name: '测站点名称' },
    { key: 'h', name: '高程(m)' },
    { key: 'level', name: '等级' },
    { key: 'milestone', name: '里程' },
    { key: 'remark', name: '备注' },
    { key: 'action', name: '操作', width: '130' },
])
const levelTable = ref([])

//获取数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await stationApi.queryListData({
        projectId: projectId.value,
        contractId: contractId.value,
        ...searchForm.value,
    })
    //处理数据
    tableLoading.value = false
    if (!error && code === 200) {
        let records = getArrValue(data['records'])
        if (tabsTypeKey.value === '0') {
            levelTable.value = records
        } else if (tabsTypeKey.value === '1') {
            traverseTable.value = records
        }
        searchForm.value.total = data.total || 0
    } else {
        levelTable.value = []
        traverseTable.value = []
        searchForm.value.total = 0
    }
}

//等级
const personData = ref([
    { label: '一级', value: '一级' }, { label: '二级', value: '二级' },
    { label: '三级', value: '三级' }, { label: '四级', value: '四级' },
])

//新增 / 编辑 配置
const showRowModal = ref(false)
const formRowRef = ref(null)
const formRowValue = ref({ name: '', x: '', y: '', h: '', level: null, remark: null })
const rulesRow = {
    name: {
        required: true,
        trigger: 'blur',
        message: '请输入测站点名称',
    },
    x: {
        required: true,
        trigger: 'blur',
        message: '请输入X坐标(m)',
    },
    y: {
        required: true,
        trigger: 'blur',
        message: '请输入Y坐标(m)',
    },
    h: {
        required: true,
        trigger: 'blur',
        message: '请输入高程(m)',
    },
}

//新增
const AddRowClick = () => {
    const type = tabsTypeKey.value
    const obj = {
        projectId: projectId.value,
        contractId: contractId.value,
        type: tabsTypeKey.value,
        name: '', h: '', level: null, remark: null,
    }
    if (type === '0') {
        formRowValue.value = obj
    } else if (type === '1') {
        formRowValue.value = { ...obj, x: '', y: '' }
    }
    saveFormLoading.value = false
    showRowModal.value = true
}

//新增/编辑 保存
const saveFormLoading = ref(false)
const saveFormClick = async () => {
    const validate = await formValidate(formRowRef.value)
    if (validate) {
        const form = formRowValue.value
        if (form.id) {
            saveFormLoading.value = true
            const { error, code } = await stationApi.updateSave(form, false)
            //判断状态
            saveFormLoading.value = false
            if (!error && code === 200) {
                showRowModal.value = false
                window?.$message?.success('保存成功')
                getTableData()
            } else {
                window?.$message?.error('保存失败')
            }
        } else {
            saveFormLoading.value = true
            const { error, code } = await stationApi.addSave(form, false)
            //判断状态
            saveFormLoading.value = false
            if (!error && code === 200) {
                showRowModal.value = false
                window?.$message?.success('新增成功')
                getTableData()
            } else {
                window?.$message?.error('新增失败')
            }
        }
    }
}

//导入配置
const showImportModal = ref(false)
const importLoading = ref(false)

//上传配置
const uploadRef = ref(null)
const addition = ref({})
const fileList = ref([])
const action = '/api/blade-business/dap/import'
const accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'

//导入
const importModalClick = () => {
    addition.value = {
        projectId: projectId.value,
        contractId: contractId.value,
        type: tabsTypeKey.value,
    }
    importLoading.value = false
    showImportModal.value = true
}

//上传一个文件时，重置
const handleUploadExceed = (files) => {
    uploadRef.value?.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadRef.value?.handleStart(file)
}

//确认导入
const handleImportClick = () => {
    uploadRef.value?.submit()
}
//上传中
const handleUploadProgress = () => {
    importLoading.value = true
}
//上传完成
const handleUploadFinish = () => {
    importLoading.value = false
    showImportModal.value = false
    window?.$message?.success('导入成功')
    uploadRef.value?.clearFiles()
    getTableData()
}
//上传失败
const handleUploadError = () => {
    importLoading.value = false
    window?.$message?.error('导入失败')
}

//导出
const exportModalClick = () => {
    window?.$messageBox?.alert('将导出当前所有数据？', '导出数据', {
        showCancelButton: true,
        confirmButtonText: '确定导出',
        cancelButtonText: '取消',
        callback: (action) => {
            if (action === 'confirm') {
                getExportExcel()
            }
        },
    })
}
//确定导出
const downloadLoading = ref(false)
const getExportExcel = async () => {
    //批量下载
    downloadLoading.value = true
    const { error, disposition, res } = await stationApi.getExportExcel({
        projectId: projectId.value,
        contractId: contractId.value,
        type: tabsTypeKey.value,
        search: searchForm.value['name'] || '',
    })
    //处理数据
    downloadLoading.value = false
    if (!error) {
        if (disposition) {
            downloadBlob(res, disposition)
        } else {
            window.$message?.error('数据异常')
        }
    }
}

//水准点
const handleLevelEdit = (row) => {
    formRowValue.value = {
        ...row,
        projectId: projectId.value,
        contractId: contractId.value,
        type: tabsTypeKey.value,
    }
    saveFormLoading.value = false
    showRowModal.value = true
}
const handleLevelDelete = (row) => {
    delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                delData(row.id)
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
    })
}

//导线点
const handleTraverseEdit = (row) => {
    formRowValue.value = {
        ...row,
        projectId: projectId.value,
        contractId: contractId.value,
        type: tabsTypeKey.value,
    }
    saveFormLoading.value = false
    showRowModal.value = true
}
const handleTraverseDelete = (row) => {
    delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                delData(row.id)
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
    })
}

//删除请求
const delData = async (id) => {
    const { error, code } = await stationApi.delData({ ids: id }, false)
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        getTableData()
    } else {
        window?.$message?.error('删除失败')
    }
}
</script>

<style lang="scss" scoped>
@import '../../styles/gauge/station.scss';
</style>
