<template>
    <n-divider dashed title-placement="left">测站点</n-divider>
    <div class="hc-layout-box">
        <n-card class="hc-card-overflow-p-box" :segmented="{content: true}">
            <template #header>
                <div class="hc-card-header flex items-center">
                    <div class="w-60">
                        <n-input v-model:value="searchForm.name" type="text" placeholder="请输入测站点或关键字进行搜索" clearable/>
                    </div>
                    <n-button type="primary" class="px-5 ml-3" @click="searchChange">搜索</n-button>
                    <n-popover trigger="hover" :disabled="!bubbleVal || !btn_add?.textInfo" v-if="btn_add">
                        <template #trigger>
                            <n-button type="primary" strong secondary class="px-5 ml-10" @click="AddRowClick">新增</n-button>
                        </template>
                        <span>{{btn_add?.textInfo}}</span>
                    </n-popover>
                    <n-popover trigger="hover" :disabled="!bubbleVal || !btn_import?.textInfo" v-if="btn_import">
                        <template #trigger>
                            <n-button type="primary" strong secondary class="px-5 ml-3" @click="importModalClick">导入</n-button>
                        </template>
                        <span>{{btn_import?.textInfo}}</span>
                    </n-popover>
                    <n-popover trigger="hover" :disabled="!bubbleVal || !btn_export?.textInfo" v-if="btn_export">
                        <template #trigger>
                            <n-button type="primary" strong secondary class="px-5 ml-3" @click="exportModalClick">导出</n-button>
                        </template>
                        <span>{{btn_export?.textInfo}}</span>
                    </n-popover>
                </div>
            </template>
            <template #header-extra>
                <HcTabs :datas="tabsTypeData" :keys="tabsTypeKey" @change="tabsTypeChange"/>
            </template>
            <div v-if="tabsTypeKey==='1'">
                <n-data-table :columns="traverseColumns" :data="traverseTable" :pagination="false" :row-key="row => row.name" :single-line="false" striped/>
            </div>
            <div v-if="tabsTypeKey==='0'">
                <n-data-table :columns="levelColumns" :data="levelTable" :pagination="false" :row-key="row => row.name" :single-line="false" striped/>
            </div>
            <template #action>
                <HcPage :pages="searchForm" @change="pageChange"/>
            </template>
        </n-card>
    </div>
    <!--新增/编辑 弹框-->
    <n-modal v-model:show="showRowModal">
        <n-card class="w-750" :title="rowModalTitle()" :segmented="{content: true}">
            <n-form ref="formRowRef" :model="formRowValue" :rules="rulesRow" label-placement="left" label-width="auto" size="large">
                <n-form-item label="点名称" path="name">
                    <n-input class="flex-1" v-model:value="formRowValue.name" placeholder="请输入点名称"/>
                </n-form-item>
                <n-form-item label="X坐标(m)" path="x" v-if="tabsTypeKey === '1'">
                    <n-input class="flex-1" v-model:value="formRowValue.x" placeholder="请输入X坐标(m)"/>
                </n-form-item>
                <n-form-item label="Y坐标(m)" path="y" v-if="tabsTypeKey === '1'">
                    <n-input class="flex-1" v-model:value="formRowValue.y" placeholder="请输入Y坐标(m)"/>
                </n-form-item>
                <n-form-item label="高程(m)" path="h">
                    <n-input class="flex-1" v-model:value="formRowValue.h" placeholder="请输入高程(m)"/>
                </n-form-item>
                <n-form-item label="等级">
                    <n-select class="flex-1" v-model:value="formRowValue.level" :options="personData" placeholder="请选择等级"/>
                </n-form-item>
                <n-form-item label="备注">
                    <n-input v-model:value="formRowValue.remark" placeholder="请输入文字说明" type="textarea" :autosize="{minRows: 3,maxRows: 5}"/>
                </n-form-item>
            </n-form>
            <template #action>
                <div class="text-center">
                    <n-button class="px-5" @click="showRowModal = false">取消</n-button>
                    <n-button type="primary" class="px-5 ml-4" :loading="saveFormLoading" @click="saveFormClick">保存</n-button>
                </div>
            </template>
        </n-card>
    </n-modal>
    <!--导入 弹框-->
    <n-modal v-model:show="showImportModal">
        <n-card class="w-750" :title="'导入' + getModalTitle()" :segmented="{content: true}">
            <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">
                    <n-upload ref="uploadRef" :action="action" :headers="getTokenHeader()" :data="upData" :max="1" :accept="accept" :default-upload="false" multiple @change="handleUploadChange" @finish="uploadFinish">
                        <n-button type="primary" class="px-4">选择文件</n-button>
                    </n-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 #action>
                <div class="text-center">
                    <n-button class="px-4" @click="showImportModal = false">取消</n-button>
                    <n-button type="primary" :disabled="!fileListLength" :loading="importLoading" class="px-4 ml-4" @click="handleImportClick">确认导入</n-button>
                </div>
            </template>
        </n-card>
    </n-modal>
</template>

<script setup>
import {ref,watch,onMounted} from "vue";
import {useAppStore} from "~src/store/index";
import HcTabs from "~com/plugins/naive/HcTabs.vue"
import HcPage from "~com/plugins/naive/HcPage.vue"
import {renderTableEditDelButton} from "~src/plugins/renderele";
import {getTokenHeader} from '~src/api/request/header';
import station from '~api/gauge/station';
import {download} from "~src/utils/lib/tools";

//初始变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);

//按钮气泡开关
const bubbleVal = ref(useAppState.getBubble);

//监听
watch(() => [
    useAppState.getProjectId,
    useAppState.getContractId,
    useAppState.getBubble,
], ([UserProjectId,UserContractId,Bubble]) => {
    projectId.value = UserProjectId
    contractId.value = UserContractId
    //按钮气泡开关
    bubbleVal.value = Bubble
})

//获取气泡数据
const getButtonsVal = (value) => {
    return useAppState.getButtonsVal(value)
}

//气泡数据
const btn_add = ref(getButtonsVal('gauge-station-add'))
const btn_import = ref(getButtonsVal('gauge-station-import'))
const btn_export = ref(getButtonsVal('gauge-station-export'))
const btn_edit = ref(getButtonsVal('gauge-station-edit'))
const btn_del = ref(getButtonsVal('gauge-station-del'))

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

//结构类型tab数据和相关处理
const tabsTypeKey = ref('1')
const tabsTypeData = ref([
    {key:'0',  name: '水准点'},
    {key:'1', name: '导线点'}
]);
const tabsTypeChange = (value) => {
    tabsTypeKey.value = value;
    searchForm.value.type = value;
    searchForm.value.current = 1
    getTableData()
}

//渲染完成
onMounted(() => {
    getTableData()
})

//新增编辑
const showRowModal = ref(false)
const formRowRef = ref(null)
const formRowValue = ref({
    projectId: projectId.value,
    contractId: contractId.value,
    type: tabsTypeKey.value,
    name: '', x: '', y: '', h: '', level: null, remark: null
})
const personData = ref([
    {label: "一级", value: "一级"}, {label: "二级", value: "二级"},
    {label: "三级", value: "三级"}, {label: "四级", value: "四级"}
])
const rulesRow = {
    name: {
        required: true,
        trigger: ["blur", "input"],
        message: "请输入测站点名称"
    },
    x: {
        required: true,
        trigger: ["blur", "input"],
        message: "请输入X坐标(m)"
    },
    y: {
        required: true,
        trigger: ["blur", "input"],
        message: "请输入Y坐标(m)"
    },
    h: {
        required: true,
        trigger: ["blur", "input"],
        message: "请输入高程(m)"
    }
}

//卡片弹窗标题
const rowModalTitle = () => {
    let formType = '新增', tabType = '异常了';
    if (formRowValue.value.id) {
        formType = '编辑'
    }
    if (tabsTypeKey.value === '1') {
        tabType = '导线点'
    } else if (tabsTypeKey.value === '0') {
        tabType = '水准点'
    }
    return formType + tabType
}

//导线点的 表格表头
const createTraverseColumns = ({edit,del}) => {
    return [
        {title: '序号', key: 'num', width: 80, align: 'center',
            render(_, index) {
                return index + 1
            }
        },
        {title: '测站点名称', key: 'name'},
        {title: 'X坐标(m)', key: 'x'},
        {title: 'Y坐标(m)', key: 'y'},
        {title: '高程(m)', key: 'h'},
        {title: '等级', key: 'level'},
        {title: '备注', key: 'remark'},
        {title: "操作", key: "actions", width: 160, align: 'center',
            render(row) {
                return renderTableEditDelButton({
                    bubble: bubbleVal.value,
                    btn_edit: btn_edit.value,
                    btn_del: btn_del.value,
                    edit_event: edit,
                    del_event: del,
                    row:row
                })
            }
        }
    ];
};
const traverseColumns = createTraverseColumns({
    edit(row) {
        let form = JSON.parse(JSON.stringify(row));
        let mile = ['name', 'x', 'y', 'h', 'level', 'remark']
        mile.forEach((key) => {
            formRowValue.value[key] = form[key] + '';
        })
        formRowValue.value['id'] = form.id;
        formRowValue.value['projectId'] = projectId.value;
        formRowValue.value['contractId'] = contractId.value;
        showRowModal.value = true
    },
    del(row) {
        station.delData({
            ids: row.id
        }).then(({data}) => {
            if (data.code === 200) {
                window?.$message?.success('删除成功')
                getTableData()
            } else {
                window?.$message?.error('删除失败')
            }
        })
    },
})
const traverseTable = ref([]);

//水准点的 表格表头
const createLevelColumns = ({edit,del}) => {
    return [
        {title: '序号', key: 'num', width: 80, align: 'center',
            render(_, index) {
                return index + 1
            }
        },
        {title: '测站点名称', key: 'name'},
        {title: '高程(m)', key: 'h'},
        {title: '等级', key: 'level'},
        {title: '备注', key: 'remark'},
        {title: "操作", key: "actions", width: 160, align: 'center',
            render(row) {
                return renderTableEditDelButton({
                    bubble: bubbleVal.value,
                    btn_edit: btn_edit.value,
                    btn_del: btn_del.value,
                    edit_event: edit,
                    del_event: del,
                    row:row
                })
            }
        }
    ];
};
const levelColumns = createLevelColumns({
    edit(row) {
        let form = JSON.parse(JSON.stringify(row));
        let mile = ['name', 'h', 'level', 'remark'];
        mile.forEach((key) => {
            formRowValue.value[key] = form[key] + '';
        })
        formRowValue.value['id'] = form.id;
        formRowValue.value['projectId'] = projectId.value;
        formRowValue.value['contractId'] = contractId.value;
        showRowModal.value = true
    },
    del(row) {
        station.delData({
            ids: row.id
        }).then(({data}) => {
            if (data.code === 200) {
                window?.$message?.success('删除成功')
                getTableData()
            } else {
                window?.$message?.error('删除失败')
            }
        })
    },
})
//表格数据
const levelTable = ref([]);

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

//保存表单
const saveFormLoading = ref(false)
const saveFormClick = () => {
    const form = formRowValue.value
    if (!!form.id) {
        saveFormLoading.value = true
        station.updateSave(formRowValue.value).then(({data}) => {
            saveFormLoading.value = false
            if (data.code === 200) {
                getTableData()
                showRowModal.value = false
                window?.$message?.success('保存成功')
            } else {
                window?.$message?.error('保存失败')
            }
        }).catch(() => {
            saveFormLoading.value = false
        })
    } else {
        saveFormLoading.value = true
        station.addSave(formRowValue.value).then(({data}) => {
            saveFormLoading.value = false
            if (data.code === 200) {
                getTableData()
                showRowModal.value = false
                window?.$message?.success('新增成功')
            } else {
                window?.$message?.error('新增失败')
            }
        }).catch(() => {
            saveFormLoading.value = false
        })
    }
}

//导入弹窗
const showImportModal = ref(false)
const fileListLength = ref(0);
const uploadRef = ref(null);
const importLoading = ref(false)
const action = '/api/blade-business/dap/import';
const accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel';
const upData = ref({
    projectId: projectId.value,
    contractId: contractId.value,
    type: tabsTypeKey.value
})

const importModalClick  = () => {
    upData.value = {
        projectId: projectId.value,
        contractId: contractId.value,
        type: tabsTypeKey.value
    }
    showImportModal.value = true
}

const handleUploadChange = (options) => {
    fileListLength.value = options.fileList.length;
}
const handleImportClick = () => {
    importLoading.value = true
    uploadRef.value?.submit();
}
//上传完成
const uploadFinish = ({event}) => {
    importLoading.value = false
    let res = JSON.parse(event?.target?.response);
    if (res.code === 200) {
        window?.$message?.success('导入成功')
        showImportModal.value = false
        getTableData()
    } else {
        window?.$message?.error(res.msg||'导入失败')
    }
}

//卡片弹窗标题
const getModalTitle = () => {
    let tabType = '异常了';
    if (tabsTypeKey.value === '1') {
        tabType = '导线点'
    } else if (tabsTypeKey.value === '0') {
        tabType = '水准点'
    }
    return tabType
}

//导出弹窗
const exportModalClick  = () => {
    window?.$dialog?.warning({
        title: "导出数据",
        content: "将导出当前所有数据",
        positiveText: "确定导出",
        negativeText: "取消",
        onPositiveClick: () => {
            station.getExportExcel({
                projectId: projectId.value,
                contractId: contractId.value,
                type: tabsTypeKey.value,
                search: searchForm.value['name'] || ''
            }).then(res => {
                download(res)
            })
        }
    });
}

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

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

//获取数据
const getTableData = () => {
    station.queryListData(searchForm.value).then(({data}) => {
        let res = data['data'] || {}
        if (tabsTypeKey.value === '0') {
            levelTable.value = res['records'] || []
        } else if (tabsTypeKey.value === '1') {
            traverseTable.value = res['records'] || []
        }
        searchForm.value.total = res.total || 0
    })
}
</script>

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