<template>
    <div class="hc-layout-box">
        <HcCard :scrollbar="false" actionSize="lg">
            <template #header>
                <HcTooltip keys="gauge-station-add">
                    <el-button type="primary" hc-btn @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 hc-btn :loading="downloadLoading" @click="exportModalClick">
                        <HcIcon name="download"/>
                        <span>导出</span>
                    </el-button>
                </HcTooltip>
                <div class="w-60 ml-6">
                    <el-input v-model="searchForm.name" size="large" placeholder="请输入测站点或关键字进行搜索" clearable @keyup="keyUpEvent"/>
                </div>
                <div class="ml-2">
                    <el-button type="primary" size="large" @click="searchClick">
                        <HcIcon name="search-2"/>
                        <span>搜索</span>
                    </el-button>
                </div>
            </template>
            <template #extra>
                <HcNewSwitch :datas="tabsTypeData" :keys="tabsTypeKey" @change="tabsTypeChange"/>
            </template>

            <HcTable :column="levelTableColumn" :datas="levelTable" :loading="tableLoading" v-if="tabsTypeKey === '0'">
                <template #action="{row}">
                    <HcTooltip keys="gauge-station-edit">
                        <el-button type="primary" size="small" text @click="handleLevelEdit(row)">编辑</el-button>
                    </HcTooltip>
                    <HcTooltip keys="gauge-station-del">
                        <el-button type="danger" size="small" text @click="handleLevelDelete(row)">删除</el-button>
                    </HcTooltip>
                </template>
            </HcTable>

            <HcTable :column="traverseTableColumn" :datas="traverseTable" :loading="tableLoading" v-if="tabsTypeKey === '1'">
                <template #action="{row}">
                    <HcTooltip keys="gauge-station-edit">
                        <el-button type="primary" size="small" text @click="handleTraverseEdit(row)">编辑</el-button>
                    </HcTooltip>
                    <HcTooltip keys="gauge-station-del">
                        <el-button type="danger" size="small" text @click="handleTraverseDelete(row)">删除</el-button>
                    </HcTooltip>
                </template>
            </HcTable>

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

<script setup>
import {ref,onMounted} from "vue";
import {useRouter, useRoute} from 'vue-router'
import {useAppStore} from "~src/store/index";
import stationApi from '~api/gauge/station';
import {getTokenHeader} from '~src/api/request/header';
import {getArrValue, downloadBlob, formValidate} from "vue-utils-plus"
import { genFileId } from 'element-plus'

//初始变量
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:'remark', name: '备注'},
    {key:'action', name: '操作', width: '130'}
])
const traverseTable = ref([])

//水准点
const levelTableColumn = ref([
    {key:'name', name: '测站点名称'},
    {key:'h', name: '高程(m)'},
    {key:'level', 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) => {
    window?.$messageBox?.alert('是否删除当前数据？', '删除提醒', {
        showCancelButton: true,
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        callback: (action) => {
            if (action === 'confirm') {
                delData(row.id)
            }
        }
    })
}

//导线点
const handleTraverseEdit = (row) => {
    formRowValue.value = {
        ...row,
        projectId: projectId.value,
        contractId: contractId.value,
        type: tabsTypeKey.value
    }
    saveFormLoading.value = false
    showRowModal.value = true
}
const handleTraverseDelete = (row) => {
    window?.$messageBox?.alert('是否删除当前数据？', '删除提醒', {
        showCancelButton: true,
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        callback: (action) => {
            if (action === 'confirm') {
                delData(row.id)
            }
        }
    })
}

//删除请求
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>
