<!-- 多井钻头 -->
<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="区块" prop="qk">
                <el-select v-model="searchForm.qk" placeholder="请选择区块" clearable filterable style="width: 150px;">
                    <el-option v-for="item in blockOptions" :key="item.qk" :label="item.qk" :value="item.qk"
                        v-if="item && item.qk" />
                </el-select>
            </el-form-item>
            <el-form-item label="钻头尺寸">
                <el-input v-model="searchForm.ztcc" placeholder="请输入钻头信息" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getList">搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
                <el-button type="success" @click="handleAdd">新增</el-button>
            </el-form-item>
        </el-form>


        <!-- 表格区域 -->
        <el-table :data="tableData" border stripe v-loading="loading" style="width: 100%; height: calc(100vh - 230px)">
            <el-table-column prop="qk" label="区块" align="center" min-width="70" show-overflow-tooltip></el-table-column>
            <el-table-column prop="famc" label="方案名称" align="center" min-width="100" show-overflow-tooltip sortable />
            <el-table-column prop="ztcc" label="钻头尺寸mm" align="center" min-width="160"
                show-overflow-tooltip></el-table-column>
            <el-table-column prop="dc" label="地层" align="center" min-width="120"
                show-overflow-tooltip></el-table-column>
            <el-table-column prop="yxzt" label="综合最优" align="center" min-width="155" show-overflow-tooltip sortable />
            <el-table-column prop="jczt" label="进尺最优" align="center" min-width="155" show-overflow-tooltip sortable />
            <el-table-column prop="jxzszt" label="转速最优" align="center" min-width="155" show-overflow-tooltip sortable />
            <el-table-column prop="bz" label="备注" align="center" min-width="180"
                show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="160" align="center" fixed="right">
                <template #default="scope">
                    <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
                    <el-button type="text" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination style="margin-top: 10px; text-align: right;" v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize" :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" background />

        <!-- 新增/编辑对话框 -->
        <el-dialog :title="dialogTitle" width="900px" :close-on-click-modal="false" :visible.sync="dialogVisible">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="140px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="方案名称" prop="famc">
                            <el-input v-model="formData.famc" placeholder="请输入方案名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="区块" prop="qk">
                            <el-select v-model="formData.qk" placeholder="请选择区块名称" clearable filterable
                                style="width: 100%;">
                                <el-option v-for="item in blockOptions" :key="item.qk" :label="item.qk" :value="item.qk"
                                    v-if="item && item.qk" style="width: 100%;" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="完井时间" prop="wjsjks" required>
                            <el-date-picker v-model="formData.wjsjks" type="date" placeholder="选择开始日期"
                                style="width: 50%;" />
                            <el-date-picker v-model="formData.wjsjjs" type="date" placeholder="选择结束日期"
                                style="width: 50%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="层位" prop="cw">
                            <el-input v-if="!showCascader" v-model="formData.cw" readonly style="width: 100%;">
                                <template slot="append">
                                    <el-button @click="openCascader">选择</el-button>
                                </template>
                            </el-input>
                            <!-- 使用v-if来条件渲染el-cascader -->
                            <el-cascader v-if="showCascader" ref="cascader" v-model="cascaderValue" @change="change"
                                @click="handleCascaderClick" :options="mdcOptions" :props="mdc" placeholder="请选择层位"
                                style="width: 200px;" popper-class="cascader-popper">
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="钻头尺寸mm" prop="ztcc">
                            <el-select v-model="formData.ztcc" multiple filterable allow-create default-first-option
                                placeholder="请选择或输入钻头尺寸" style="width: 100%" :loading="ztxxLoading">
                                <el-option v-for="item in ztxxOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="进尺最优比例" prop="jcbl">
                            <el-select v-model="formData.jcbl" placeholder="请选择进尺最优比例" clearable style="width: 100%;">
                                <el-option label="0.2" value="0.2" />
                                <el-option label="0.3" value="0.3" />
                                <el-option label="0.4" value="0.4" />
                                <el-option label="0.5" value="0.5" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="机械钻速最优比例" prop="jxzsbl">
                            <el-select v-model="formData.jxzsbl" placeholder="请选择机械钻速最优比例" clearable
                                style="width: 100%;">
                                <el-option label="0.2" value="0.2" />
                                <el-option label="0.3" value="0.3" />
                                <el-option label="0.4" value="0.4" />
                                <el-option label="0.5" value="0.5" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注" prop="bz">
                            <el-input v-model="formData.bz" type="textarea" :rows="3" placeholder="请输入备注信息"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getQkxl } from "@/api/system/jsaa";
import { getMdcByQkid } from "@/api/scientificDrill/schemeOptimization";
import { selectZtccList, listDjzt, getDjzt, addDjzt, updateDjzt, delDjzt } from "@/api/system/djzt";
export default {
    name: 'DjztIndex',
    data() {
        return {
            mdcOptions: [],
            oilOptions: [],
            mdc: {
                lazy: true,
                lazyLoad: this.loadTreeNode,
                checkStrictly: true, // 允许选择任意级别的节点
                multiple: false,
                expandTrigger: 'click', // 点击展开
                emitPath: true, // 返回完整路径
                maxLevel: 5 // 限制最多五级
            },
            cascaderValue: [],// 用于绑定 el-cascader 的 v-model
            showCascader: false,
            blockOptions: [],
            // 搜索表单
            searchForm: {
                qk: '',
                ztcc: ''
            },
            // 表格数据
            tableData: [],
            loading: false,
            // 分页
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0
            },
            // 对话框
            dialogVisible: false,
            dialogTitle: '新增',
            submitLoading: false,
            // 表单数据
            formData: {
                id: null,
                qk: '',
                ztcc: [],
                cw: '', // 层位信息
                cwid: null, // 层位ID
                mdcid: null, // 目的层ID
                dzsdmc: '', // 地质时代名称
                wjsjks: this.getFiveYearsAgoDate(), // 完井开始日期默认前五年的今天
                wjsjjs: this.getTodayDate(), // 完井结束日期默认今天
                bz: '',
                jcbl: '', // 进尺最优比例
                jxzsbl: '' // 机械钻速最优比例
            },
            // 表单验证规则
            formRules: {
                famc: [
                    { required: true, message: '请输入方案名称', trigger: 'blur' }
                ],
                qk: [
                    { required: true, message: '请输入区块', trigger: 'blur' }
                ],
                jcbl: [{ required: true, message: '请选择进尺最优比例', trigger: 'change' }],
                jxzsbl: [{ required: true, message: '请选择机械钻速最优比例', trigger: 'change' }]
            },
            // 钻头信息选项
            ztxxOptions: [],
            // 钻头信息加载状态
            ztxxLoading: false,
        }
    },
    watch: {
        'formData.qk'() {
            this.updateZtccOptionsIfReady()
        },
        'formData.wjsjks'() {
            this.updateZtccOptionsIfReady()
        },
        'formData.wjsjjs'() {
            this.updateZtccOptionsIfReady()
        }
    },
    created() {
        this.getBlockOptions();
        this.getList();
    },
    mounted() {
        this.getTableData()
    },
    methods: {
        /** 获取今天的日期 */
        getTodayDate() {
            return new Date();
        },
        /** 获取前五年的今天日期 */
        getFiveYearsAgoDate() {
            const fiveYearsAgo = new Date();
            fiveYearsAgo.setFullYear(fiveYearsAgo.getFullYear() - 5);
            return fiveYearsAgo;
        },
        /** 格式化日期为字符串 */
        formatDate(date) {
            if (!date) return '';
            const d = new Date(date);
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        /** 查看按钮操作 */
        async handleView(row) {
            try {
                const res = await getDjzt(row.id)
                console.log(res, 55555);
                if (res.code === 200) {
                    // 将获取到的详细信息传递给详情页面
                    const params = {
                        jh: res.data.jh || row.jh || '',
                        ztcc: row.ztcc || '',
                        qk: res.data.qk || row.qk || '',
                        zbid: res.data.id || row.id || '',
                        cw: row.cw || row.dc || '',
                    };

                    this.$router.push({
                        name: 'DjztDetail',
                        params: params
                    }).then(() => {
                        console.log('路由跳转成功');
                    }).catch(err => {
                        console.error('路由跳转失败:', err);
                    });
                } else {
                    this.$message.error(res.msg || '获取详情失败')
                }
            } catch (error) {
                console.error('获取详情失败:', error)
                this.$message.error('获取详情失败')
            }
        },
        /** 初始化目的层选项 */
        initMdcOptions() {
            // 加载根节点
            const params = {
                dclevel: 1,
                pid: null,
            };

            getMdcByQkid(params).then(response => {
                const options = response.data.map(item => ({
                    value: item.id,
                    label: item.mc,
                    leaf: false,
                    level: 1 // 设置根节点层级
                }));
                this.mdcOptions = options;
            }).catch(error => {
                console.error('初始化目的层选项失败:', error);
                this.mdcOptions = [];
            });
        },
        // 目的层相关方法
        openCascader() {
            this.showCascader = true;
            // 确保级联选择器正确初始化
            this.$nextTick(() => {
                if (this.$refs.cascader) {
                    console.log('级联选择器已初始化');
                    // 设置初始值
                    if (this.formData.mdcid) {
                        this.cascaderValue = [this.formData.mdcid];
                    }
                }
            });
        },
        // 处理级联选择器点击
        handleCascaderClick() {
            console.log('级联选择器被点击');
        },
        change(val) {
            console.log('选择变化:', val); // 调试信息

            if (val && val.length > 0) {
                // 获取最后选择的节点值
                const selectedValue = val[val.length - 1];

                // 设置选中层的 id 到表单中
                this.formData.mdcid = selectedValue;

                // 直接通过级联选择器获取选中的标签
                this.getSelectedLabel(val, selectedValue);

                // 延迟关闭级联选择器，确保值已经设置
                setTimeout(() => {
                    this.showCascader = false;
                    // 强制更新视图
                    this.$forceUpdate();
                    // 层位选择完成后尝试加载钻头尺寸
                    this.updateZtccOptionsIfReady();
                }, 100);
            } else {
                this.showCascader = false;
            }
        },
        // 获取选中节点的标签
        async getSelectedLabel(path, selectedValue) {
            console.log('获取选中标签:', path, selectedValue);

            // 从最后一级开始，逐级向上查找
            for (let i = path.length - 1; i >= 0; i--) {
                const currentValue = path[i];
                const level = i + 1;

                try {
                    const params = {
                        dclevel: level,
                        pid: i === 0 ? null : path[i - 1]
                    };

                    const response = await getMdcByQkid(params);
                    const nodes = response.data;

                    // 在当前级别中查找选中的节点
                    const selectedNode = nodes.find(item => item.id === currentValue);

                    if (selectedNode) {
                        console.log('找到选中节点:', selectedNode);

                        // 设置层位信息
                        this.formData.cw = selectedNode.mc; // 层位名称
                        this.formData.cwid = selectedNode.id; // 层位ID

                        // 构建地质时代名称
                        this.buildDzsdmc(path, selectedNode);

                        this.$set(this.formData, 'cw', selectedNode.mc);
                        this.$set(this.formData, 'cwid', selectedNode.id);
                        this.$set(this.formData, 'mdcid', selectedValue);
                        break;
                    }
                } catch (error) {
                    console.error('获取节点信息失败:', error);
                }
            }
        },
        // 构建地质时代名称
        async buildDzsdmc(path, selectedNode) {
            console.log('构建地质时代名称:', path, selectedNode);

            if (path.length >= 2) {
                try {
                    // 构建从盆地之后到选中节点之前的完整路径
                    const eraPath = [];

                    // 从第二级开始（跳过盆地），到倒数第二级（选中节点的前一个）
                    for (let i = 1; i < path.length - 1; i++) {
                        const currentValue = path[i];
                        const level = i + 1;
                        const pid = i === 1 ? path[0] : path[i - 1]; // 父级ID

                        const params = {
                            dclevel: level,
                            pid: pid
                        };

                        const response = await getMdcByQkid(params);
                        const nodes = response.data;

                        // 找到当前级别的节点
                        const currentNode = nodes.find(item => item.id === currentValue);

                        if (currentNode) {
                            eraPath.push(currentNode.mc);
                        }
                    }

                    // 构建地质时代名称：用/连接所有级别
                    const dzsdmc = eraPath.join('/');
                    console.log('构建的地质时代名称:', dzsdmc);
                    this.formData.dzsdmc = dzsdmc;
                    this.$set(this.formData, 'dzsdmc', dzsdmc);
                } catch (error) {
                    console.error('构建地质时代名称失败:', error);
                }
            }
        },
        loadTreeNode(node, resolve) {
            // 检查是否已达到最大层级（5级）
            if (node.level >= 5) {
                console.log('已达到最大层级，不再加载子节点');
                resolve([]);
                return;
            }

            const params = {
                dclevel: node.level + 1,
                pid: node.value,
            };
            console.log('加载节点参数:', params); // 调试信息

            // 发起请求获取节点数据
            getMdcByQkid(params).then(response => {
                const oilOptions = response.data; // 获取到的数据
                console.log('加载节点数据:', oilOptions); // 调试信息

                if (Array.isArray(oilOptions) && oilOptions.length > 0) {
                    // 将数据转换为符合 Cascader 要求的格式
                    const nodes = oilOptions.map(item => ({
                        value: item.id,
                        label: item.mc,
                        leaf: node.level + 1 >= 5, // 第五级设置为叶子节点，不允许继续展开
                        level: node.level + 1 // 设置节点层级
                    }));
                    console.log('转换后的节点:', nodes); // 调试信息
                    resolve(nodes);
                } else {
                    // 如果没有数据，返回空数组
                    console.log('没有找到子节点数据');
                    resolve([]);
                }
            }).catch(error => {
                // 处理请求失败的情况
                console.error('加载节点数据失败:', error);
                resolve([]);
            });
        },
        /** 获取钻头信息下拉选项 */
        getZtxxOptions(queryParams) {
            this.ztxxLoading = true; // 开始加载
            selectZtccList(queryParams).then(response => {
                if (response.code === 200 && response.data && Array.isArray(response.data)) {
                    this.ztxxOptions = response.data.map(item => ({
                        value: item,
                        label: item
                    }))
                } else {
                    this.ztxxOptions = []
                }
            }).catch(error => {
                console.error('获取钻头信息选项失败:', error)
                this.ztxxOptions = []
            }).finally(() => {
                this.ztxxLoading = false; // 加载完成
            });
        },
        // 条件满足后再请求钻头尺寸
        updateZtccOptionsIfReady() {
            const { qk, wjsjks, wjsjjs, cwid, mdcid } = this.formData;
            if (qk && wjsjks && wjsjjs && (cwid || mdcid)) {
                const params = { qk, wjsjks, wjsjjs, cwid: cwid || undefined, mdcid: mdcid || undefined };
                this.getZtxxOptions(params);
            }
        },
        // 获取表格数据
        async getTableData() {
            this.loading = true
            try {
                const params = {
                    pageNum: this.pagination.currentPage,
                    pageSize: this.pagination.pageSize,
                    ...this.searchForm
                }

                const res = await listDjzt(params)

                if (res.code === 200) {
                    this.tableData = res.rows || []
                    this.pagination.total = res.total || 0
                } else {
                    this.$message.error(res.msg || '获取数据失败')
                }
            } catch (error) {
                console.error('获取数据失败:', error)
                this.$message.error('获取数据失败')
            } finally {
                this.loading = false
            }
        },
        /** 获取区块下拉选项 */
        getBlockOptions() {
            getQkxl().then(response => {
                // 过滤掉无效的选项
                this.blockOptions = response.data.filter(item => item && item.qk);
            });
        },

        // 搜索
        getList() {
            this.pagination.currentPage = 1
            this.getTableData()
        },

        // 重置搜索
        resetSearch() {
            this.searchForm = {
                qk: '',
                ztcc: ''
            }
            this.getList()
            this.resetForm("formData");
            this.showCascader = false;
            this.cascaderValue = []; // 重置 cascaderValue
            this.ztxxOptions = []; // 清空钻头信息选项，等待条件满足后再加载
        },

        // 新增
        handleAdd() {
            this.dialogTitle = '新增'
            this.formData = {
                id: null,
                qk: '',
                ztcc: [],
                cw: '', // 层位信息
                cwid: null, // 层位ID
                mdcid: null, // 目的层ID
                dzsdmc: '', // 地质时代名称
                wjsjks: this.getFiveYearsAgoDate(),
                wjsjjs: this.getTodayDate(),
                bz: '',
                jcbl: '', // 进尺最优比例
                jxzsbl: '' // 机械钻速最优比例
            }
            this.dialogVisible = true
            // 新增打开时尝试基于默认年份加载（需等区块与层位选择后）
            this.ztxxOptions = []
        },

        // 编辑
        handleEdit(row) {
            this.dialogTitle = '编辑'
            this.formData = {
                id: row.id,
                qk: row.qk,
                ztcc: Array.isArray(row.ztcc) ? row.ztcc : (row.ztcc ? row.ztcc.split(',') : []),
                cw: row.cw || row.dc || '', // 层位信息
                cwid: row.cwid || null, // 层位ID
                mdcid: row.mdcid || null, // 目的层ID
                dzsdmc: row.dzsdmc || '', // 地质时代名称
                wjsjks: row.wjsjks ? new Date(row.wjsjks) : this.getFiveYearsAgoDate(),
                wjsjjs: row.wjsjjs ? new Date(row.wjsjjs) : this.getTodayDate(),
                bz: row.bz,
                famc: row.famc,
                jcbl: row.jcbl || '', // 进尺最优比例
                jxzsbl: row.jxzsbl || '' // 机械钻速最优比例
            }
            this.dialogVisible = true
            // 编辑时若条件已满足，立即加载钻头尺寸
            this.updateZtccOptionsIfReady()
        },

        // 删除
        handleDelete(row) {
            this.$confirm('确认删除该记录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const res = await delDjzt(row.id)

                    if (res.code === 200) {
                        this.$message.success('删除成功')
                        this.getTableData()
                    } else {
                        this.$message.error(res.msg || '删除失败')
                    }
                } catch (error) {
                    console.error('删除失败:', error)
                    this.$message.error('删除失败')
                }
            }).catch(() => { })
        },

        // 提交表单
        async handleSubmit() {
            try {
                await this.$refs.formRef.validate()
                this.submitLoading = true

                // 准备提交数据，将数组转换为字符串，将Date对象转换为字符串
                const submitData = {
                    ...this.formData,
                    ztcc: Array.isArray(this.formData.ztcc) ? this.formData.ztcc.join(',') : this.formData.ztcc,
                    dc: this.formData.cw || '', // 使用层位信息作为地层
                    cw: this.formData.cw || '', // 保留层位信息
                    cwid: this.formData.cwid || null,
                    mdcid: this.formData.mdcid || null,
                    dzsdmc: this.formData.dzsdmc || '',
                    wjsjks: this.formData.wjsjks instanceof Date ? this.formatDate(this.formData.wjsjks) : this.formData.wjsjks,
                    wjsjjs: this.formData.wjsjjs instanceof Date ? this.formatDate(this.formData.wjsjjs) : this.formData.wjsjjs
                }

                const api = this.formData.id ? updateDjzt : addDjzt
                const res = await api(submitData)

                if (res.code === 200) {
                    this.$message.success(this.formData.id ? '更新成功' : '新增成功')
                    this.dialogVisible = false
                    this.getTableData()
                } else {
                    this.$message.error(res.msg || '操作失败')
                }
            } catch (error) {
                console.error('操作失败:', error)
                if (error !== false) {
                    this.$message.error('操作失败')
                }
            } finally {
                this.submitLoading = false
            }
        },

        // 分页大小改变
        handleSizeChange(val) {
            this.pagination.pageSize = val
            this.getTableData()
        },

        // 当前页改变
        handleCurrentChange(val) {
            this.pagination.currentPage = val
            this.getTableData()
        },

        // 表单重置
        resetForm(refName) {
            if (this.$refs[refName]) {
                this.$refs[refName].resetFields();
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.djzt-container {
    padding: 10px;
    height: calc(100vh - 85px);
    overflow: hidden;
    position: relative;

    .search-form {
        margin-bottom: 10px;
    }

    .el-table {
        margin-top: 10px;
    }
}

::v-deep .el-table--medium .el-table__cell {
    padding: 5px 0 !important;
}

::v-deep.pagination-container {
    padding: 0px !important;
    margin: 0;
}
</style>