<!-- 钻头使用情况 -->
<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <div class="search-wrapper">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                label-width="68px">

                <el-form-item>
                    <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                        v-hasPermi="['system:jsha:export']">导出</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 表格容器 -->
        <div class="table-container">
            <!-- 主表格区域 -->
            <div class="main-table-wrapper" :class="{ 'with-detail': selectedRow }">
                <el-table border v-loading="loading" :data="jshaList" @selection-change="handleSelectionChange"
                    @row-click="handleRowClick" height="tableHeight" style="width: 100%">
                    <el-table-column label="序号" align="center" prop="xh" width="90" show-overflow-tooltip fixed />
                    <el-table-column label="井号" align="center" prop="jh" width="110" show-overflow-tooltip fixed />
                    <el-table-column label="钻头序列号" align="center" prop="ztxlh" width="110" show-overflow-tooltip />
                    <el-table-column label="尺寸mm" align="center" prop="cc" width="90" show-overflow-tooltip />
                    <el-table-column label="开始井深m" align="center" prop="qsjs" width="110" show-overflow-tooltip />
                    <el-table-column label="结束井深m" align="center" prop="zzjs" width="110" show-overflow-tooltip />
                    <el-table-column label="进尺m" align="center" prop="jc" width="90" show-overflow-tooltip />
                    <el-table-column label="机械钻速m/h" align="center" prop="jxzs" width="110" show-overflow-tooltip />
                    <el-table-column label="所钻地层" align="center" prop="szdc" width="110" show-overflow-tooltip />
                    <el-table-column label="厂家" align="center" prop="cj" width="90" show-overflow-tooltip />
                    <el-table-column label="钻头型号" align="center" prop="ztxh" width="110" show-overflow-tooltip />
                    <el-table-column label="IADC号" align="center" prop="iadc" width="110" show-overflow-tooltip />
                    <el-table-column label="下井次数" align="center" prop="xjcs" width="110" show-overflow-tooltip />
                    <el-table-column label="类型" align="center" prop="lx" width="90" show-overflow-tooltip />
                    <el-table-column label="入井新度" align="center" prop="rjxd" width="110" show-overflow-tooltip />
                    <el-table-column label="出井新度" align="center" prop="cjxd" width="110" show-overflow-tooltip />
                    <el-table-column label="喷嘴直径1号" align="center" prop="pz1" width="110" show-overflow-tooltip />
                    <el-table-column label="喷嘴直径2号" align="center" prop="pz2" width="110" show-overflow-tooltip />
                    <el-table-column label="喷嘴直径3号" align="center" prop="pz3" width="110" show-overflow-tooltip />
                    <el-table-column label="喷嘴直径10号" align="center" prop="pz10" width="110" show-overflow-tooltip />
                    <el-table-column label="进尺工作时间合计" align="center" prop="jcsjhj" width="180" show-overflow-tooltip />
                    <el-table-column label="进尺工作时间纯钻进" align="center" prop="jcsjczj" width="180"
                        show-overflow-tooltip />
                    <el-table-column label="进尺工作时间起下钻" align="center" prop="jcsjqxz" width="180"
                        show-overflow-tooltip />
                    <el-table-column label="进尺工作时间扩划眼" align="center" prop="jcsjkhy" width="180"
                        show-overflow-tooltip />
                    <el-table-column label="钻压" align="center" prop="zy" width="90" show-overflow-tooltip />
                    <el-table-column label="转速" align="center" prop="zs" width="90" show-overflow-tooltip />
                    <el-table-column label="缸径" align="center" prop="gj" width="90" show-overflow-tooltip />
                    <el-table-column label="泵速" align="center" prop="bs" width="90" show-overflow-tooltip />
                    <el-table-column label="排量" align="center" prop="pl" width="90" show-overflow-tooltip />
                    <el-table-column label="立管泵压" align="center" prop="lgby" width="110" show-overflow-tooltip />

                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" :page-sizes="[20, 40, 60, 80, 100]" @pagination="getList"
                    style="padding: 10px 0;" />
            </div>

            <!-- 详细数据表格区域 -->
            <transition name="slide-fade">
                <div v-if="selectedRow" class="detail-table-wrapper">
                    <el-table :data="[selectedRow]" border style="width: 100%">
                        <el-table-column label="刀翼总数" prop="tzxl01" align="center" min-width="10%" />
                        <el-table-column label="布齿密度" prop="tzxl02" align="center" min-width="10%" />
                        <el-table-column label="切削齿尺寸mm" prop="tzxl03" align="center" min-width="10%" />
                        <el-table-column label="切削齿后倾角°" prop="tzxl04" align="center" min-width="10%" />
                        <el-table-column label="冠部轮廓" prop="tzxl05" align="center" min-width="10%" />
                        <el-table-column label="保径" prop="tzxl06" align="center" min-width="10%" />
                    </el-table>
                </div>
            </transition>
        </div>


    </div>
</template>

<script>
import { listDjJsha, listJsha, getJsha, delJsha, addJsha, updateJsha } from "@/api/system/jsha";
import { getBlockName, getQkxl } from "@/api/system/jsaa";
import { listTzsj } from "@/api/system/jsha";

export default {
    name: "Jsha",
    props: {
        jh: {
            type: String,
            default: ''
        },
        jhs: {
            type: String,
            default: ''
        },
        qk: {
            type: String,
            default: ''
        },
        ztcc: {
            type: String,
            default: ''
        },
        cw: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            // 区块下拉选项
            blockOptions: [],
            // 遮罩层 - 初始设置为false，避免页面加载时就显示加载动画
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 钻头数据表格数据
            jshaList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 是否为编辑操作
            isEdit: false,
            // 标记是否已经初始化过数据，避免重复加载
            dataInitialized: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 20, // 修改回默认每页显示20条
                qk: null,
                ztcc: '',
                jh: null,
                jhs: null,
                wjrqks: null,
                wjrqjs: null,
                ztxlh: null,
                ztxh: null,
                iadc: null,
                xjcs: null,
                cc: null,
                lx: null,
                cj: null,
                rjxd: null,
                cjxd: null,
                pz1: null,
                pz2: null,
                pz3: null,
                pz4: null,
                pz5: null,
                pz6: null,
                pz7: null,
                pz8: null,
                pz9: null,
                pz10: null,
                qsjs: null,
                zzjs: null,
                szdc: null,
                jc: null,
                jxzs: null,
                jcsjhj: null,
                jcsjczj: null,
                jcsjqxz: null,
                jcsjkhy: null,
                zy: null,
                zs: null,
                gj: null,
                bs: null,
                pl: null,
                lgby: null,
                ztyj: null,
                hkyh: null,
                cjl: null,
                pssd: null,
                ztsgl: null,
                bsgl: null,
                sfsdzg: null,
                sfsdzt: null,
                gllyl: null,
                ycmsqk: null,
                zcmsqk: null,
                zjmsqk: null,
                bz: null,
                npc: null,
                wpc: null,
                mstz: null,
                wz: null,
                zc: null,
                zj: null,
                qzyy: null,
                qttz: null,
                nj: null,
                zpzzs: null,
                qsrq: null,
                zzrq: null,
                pzlx: null,
                ztjg: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                jh: [
                    { required: true, message: "井号不能为空", trigger: "blur" }
                ],
                xh: [
                    { required: true, message: "序号不能为空", trigger: "blur" }
                ],
                cc: [
                    { required: true, message: "尺寸不能为空", trigger: "blur" }
                ],
                qsjs: [
                    { required: true, message: "开始井深不能为空", trigger: "blur" }
                ],
                zzjs: [
                    { required: true, message: "结束井深不能为空", trigger: "blur" }
                ],
                jc: [
                    { required: true, message: "进尺不能为空", trigger: "blur" }
                ],
                jxzs: [
                    { required: true, message: "机械钻速不能为空", trigger: "blur" }
                ]
            },
            selectedRow: null, // 当前选中的行数据
            tableHeight: null,
            // 特征数据选项
            t01Options: [],
            t02Options: [],
            t03Options: [],
            t04Options: [],
            t05Options: [],
            t06Options: [],
            formLoading: false, // 新增表单loading
        };
    },
    computed: {
        filteredBlockOptions() {
            return this.blockOptions.filter(item => item && item.qk);
        }
    },
    watch: {
        jh: {
            handler(newJh) {
                if (newJh) {
                    this.queryParams.jh = String(newJh).trim();
                    // 添加错误处理
                    try {
                        this.getList();
                    } catch (error) {
                        console.error('监听jh变化时获取数据失败:', error);
                    }
                }
            },
            immediate: true
        },
        selectedRow: {
            handler(val) {
                this.$nextTick(() => {
                    const containerElement = document.querySelector('.app-container');
                    const searchElement = document.querySelector('.search-wrapper');

                    // 检查元素是否存在
                    if (!containerElement || !searchElement) {
                        return;
                    }

                    const containerHeight = containerElement.offsetHeight;
                    const searchHeight = searchElement.offsetHeight;
                    const paginationHeight = 50; // 分页器高度

                    if (val) {
                        // 选中行时，减去详情表格高度
                        this.tableHeight = containerHeight - searchHeight - paginationHeight - 50;
                    } else {
                        // 未选中行时，使用全部可用空间
                        this.tableHeight = containerHeight - searchHeight - paginationHeight;
                    }
                });
            },
            immediate: true
        }
    },
    mounted() {
        // 初始化表格高度
        this.$nextTick(() => {
            const containerElement = document.querySelector('.app-container');
            const searchElement = document.querySelector('.search-wrapper');

            // 检查元素是否存在
            if (!containerElement || !searchElement) {
                return;
            }

            const containerHeight = containerElement.offsetHeight;
            const searchHeight = searchElement.offsetHeight;
            const paginationHeight = 50;
            this.tableHeight = containerHeight - searchHeight - paginationHeight;
        });

        // 添加窗口大小改变事件监听
        window.addEventListener('resize', this.updateTableHeight);
    },
    beforeDestroy() {
        // 移除事件监听
        window.removeEventListener('resize', this.updateTableHeight);
    },
    created() {
        // 如果传入了jh参数，设置到查询参数中
        if (this.jh) {
            this.queryParams.jh = this.jh;
        }
        // 如果传入了jhs参数，设置到查询参数中
        if (this.jhs) {
            this.queryParams.jhs = this.jhs;
        }
        // 只加载选项，不自动加载数据
        // this.getList();
        this.getBlockOptions();
        this.getFeatureOptions();
    },
    methods: {
        /** 获取区块下拉选项 */
        getBlockOptions() {
            getQkxl().then(response => {
                this.blockOptions = response.data || [];
            }).catch(error => {
                console.error('获取区块选项失败:', error);
                this.blockOptions = [];
            });
        },
        /** 获取特征数据选项 */
        getFeatureOptions() {
            const featureTypes = [
                { type: "刀翼总数", target: "t01Options" },
                { type: "布齿密度", target: "t02Options" },
                { type: "切削齿尺寸mm", target: "t03Options" },
                { type: "切削齿后倾角°", target: "t04Options" },
                { type: "冠部轮廓", target: "t05Options" },
                { type: "保径", target: "t06Options" }
            ];

            const promises = featureTypes.map(feature => {
                // 确保参数是字符串类型
                const params = {
                    tzdl: String(feature.type)
                };

                return listTzsj(params).then(response => ({
                    target: feature.target,
                    data: response.rows || []
                })).catch(error => {
                    console.error(`获取特征数据失败 - ${feature.type}:`, error);
                    return {
                        target: feature.target,
                        data: []
                    };
                });
            });

            Promise.all(promises)
                .then(results => {
                    results.forEach(result => {
                        this[result.target] = result.data;
                    });
                })
                .catch(error => {
                    console.error('获取特征数据选项失败:', error);
                    this.$modal.msgError("获取特征数据选项失败");
                });
        },
        /** 查询钻头数据列表 */
        getList() {
            this.loading = true;

            // 确保参数类型正确，过滤掉空值
            const params = {};

            if (this.ztcc && this.ztcc.trim()) {
                params.ztccs = String(this.ztcc).trim();
            }

            if (this.qk && this.qk.trim()) {
                params.qk = String(this.qk).trim();
            }

            if (this.cw && this.cw.trim()) {
                params.cw = String(this.cw).trim();
            }

            console.log('API参数:', params);

            listDjJsha(params).then(response => {
                this.jshaList = response.rows || [];
                this.total = response.total || 0;
                this.loading = false;
            }).catch(error => {
                console.error('获取钻头数据失败:', error);
                this.$modal.msgError("获取钻头数据失败");
                this.loading = false;
            });
        },


        // 取消按钮
        cancel() {
            this.formLoading = false;
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.formLoading = false;
            this.form = {
                jh: null,
                xh: null,
                ztxlh: null,
                ztxh: null,
                iadc: null,
                xjcs: null,
                cc: null,
                lx: null,
                cj: null,
                rjxd: null,
                cjxd: null,
                pz1: null,
                pz2: null,
                pz3: null,
                pz4: null,
                pz5: null,
                pz6: null,
                pz7: null,
                pz8: null,
                pz9: null,
                pz10: null,
                qsjs: null,
                zzjs: null,
                szdc: null,
                jc: null,
                jxzs: null,
                jcsjhj: null,
                jcsjczj: null,
                jcsjqxz: null,
                jcsjkhy: null,
                zy: null,
                zs: null,
                gj: null,
                bs: null,
                pl: null,
                lgby: null,
                ztyj: null,
                hkyh: null,
                cjl: null,
                pssd: null,
                ztsgl: null,
                bsgl: null,
                sfsdzg: null,
                sfsdzt: null,
                gllyl: null,
                ycmsqk: null,
                zcmsqk: null,
                zjmsqk: null,
                bz: null,
                npc: null,
                wpc: null,
                mstz: null,
                wz: null,
                zc: null,
                zj: null,
                qzyy: null,
                qttz: null,
                nj: null,
                zpzzs: null,
                qsrq: null,
                zzrq: null,
                pzlx: null,
                ztjg: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams.wjrqks = '';
            this.queryParams.wjrqjs = '';
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.jh)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.isEdit = false;
            this.open = true;
            this.title = "添加钻头数据";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.isEdit = true;
            const query = {
                jh: row.jh,
                xh: row.xh
            }
            getJsha(query).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改钻头数据";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.formLoading = true;
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.isEdit) {
                        updateJsha(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.formLoading = false;
                        });
                    } else {
                        addJsha(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.formLoading = false;
                        });
                    }
                } else {
                    this.formLoading = false;
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const query = {
                jh: row.jh,
                xh: row.xh
            };
            this.$modal.confirm('是否确认删除钻头数据编号为"' + row.jh + '"的数据项？').then(function () {
                return delJsha(query);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            const exportParams = {
                // ...this.queryParams,
                ztcc: this.ztcc,
                qk: this.qk
            };
            this.download('system/jshaPdc/export', exportParams, `jsha_${new Date().getTime()}.xlsx`)
        },

        /** 处理行点击 */
        async handleRowClick(row, column) {
            // 如果点击的是操作列，不执行任何操作
            if (column && column.property === 'operation') {
                return;
            }

            try {
                const query = {
                    jh: row.jh,
                    xh: row.xh
                }
                const res = await getJsha(query);
                this.selectedRow = res.data;
            } catch (error) {
                console.error('获取详细数据失败:', error);
                this.selectedRow = null;
            }
        },
        updateTableHeight() {
            this.$nextTick(() => {
                const containerElement = document.querySelector('.app-container');
                const searchElement = document.querySelector('.search-wrapper');

                // 检查元素是否存在
                if (!containerElement || !searchElement) {
                    return;
                }

                const containerHeight = containerElement.offsetHeight;
                const searchHeight = searchElement.offsetHeight;
                const paginationHeight = 50;

                if (this.selectedRow) {
                    this.tableHeight = containerHeight - searchHeight - paginationHeight - 120;
                } else {
                    this.tableHeight = containerHeight - searchHeight - paginationHeight;
                }
            });
        },
        /** 限制只能输入三位数字 */
        handleNumberInput(value, key) {
            // 如果值为空，直接返回
            if (value === '') {
                this.form[key] = '';
                return;
            }
            // 移除非数字字符
            value = value.toString().replace(/[^\d]/g, '');
            // 限制长度为3位
            if (value.length > 3) {
                value = value.slice(0, 3);
            }
            // 更新表单数据
            this.form[key] = value;
        },

        /** 限制只能输入数字且保留两位小数 */
        handleDecimalInput(value, key) {
            // 如果值为空，直接返回
            if (value === '') {
                this.form[key] = '';
                return;
            }
            // 只允许输入数字和小数点
            value = value.toString().replace(/[^\d.]/g, '');
            // 保证只有一个小数点
            const parts = value.split('.');
            if (parts.length > 2) {
                value = parts[0] + '.' + parts.slice(1).join('');
            }
            // 限制小数点后两位
            if (parts.length === 2 && parts[1].length > 2) {
                value = parts[0] + '.' + parts[1].slice(0, 2);
            }
            // 更新表单数据
            this.form[key] = value;
        },
        /**
         * 外部调用：加载数据
         */
        loadData() {
            // 每次激活都刷新列表
            this.getList();
        }
    }
};
</script>
<style lang="scss" scoped>
.app-container {
    height: calc(100vh - 160px);
    display: flex;
    flex-direction: column;
    padding: 10px;
    box-sizing: border-box;
    overflow: hidden;
}

.search-wrapper {
    flex: none;

}

.table-container {
    flex: 1;
    position: relative;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.main-table-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    transition: all 0.3s ease;
    overflow: hidden;
}

.detail-table-wrapper {
    height: 75px;
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    background: #fff;
    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    z-index: 1;
}

.slide-fade-enter-active,
.slide-fade-leave-active {
    transition: all 0.3s ease;
}

.slide-fade-enter,
.slide-fade-leave-to {
    transform: translateY(120px);
    opacity: 0;
}

::v-deep .el-table {
    flex: 1;
}

::v-deep .el-table__body-wrapper {
    overflow-y: auto;
}

::v-deep .el-table__cell>.cell {
    font-weight: normal;
}

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

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

.form-section {
    margin-bottom: 20px;

    .section-title {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 15px;
        padding-left: 10px;
        border-left: 3px solid #409EFF;
    }
}

::v-deep .el-form-item {
    margin-bottom: 18px;
    padding-right: 20px;
}

::v-deep .el-form-item {
    margin-bottom: 10px !important;
}
</style>
