<!-- 地层 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="井号" prop="jh">
        <el-input v-model="queryParams.jh" placeholder="请输入井号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="层位" prop="cw">
        <el-input v-model="queryParams.cw" placeholder="请输入层位" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:jsbb:add']">新增</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:jsbb:export']">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table border v-loading="loading" :data="jsbbList" @selection-change="handleSelectionChange"
      style="width: 100%; flex: 1;" height="100%">
      <el-table-column label="井号" align="center" prop="jh" min-width="90" show-overflow-tooltip />
      <el-table-column label="地质时代名称" align="center" prop="dzsdmc" min-width="110" show-overflow-tooltip />
      <el-table-column label="层位" align="center" prop="cw" min-width="90" show-overflow-tooltip />
      <el-table-column label="目的层" align="center" prop="mdc" min-width="90" show-overflow-tooltip />
      <el-table-column label="设计底界深度" align="center" prop="sjdjsd" min-width="110" show-overflow-tooltip />
      <el-table-column label="实际底界深度" align="center" prop="sjdjsd2" min-width="110" show-overflow-tooltip />
      <el-table-column label="设计厚度" align="center" prop="sjhd" min-width="90" show-overflow-tooltip />
      <el-table-column label="实际厚度" align="center" prop="sjhd2" min-width="90" show-overflow-tooltip />
      <el-table-column label="主要岩性描述" align="center" prop="zyyxms" min-width="130" show-overflow-tooltip />
      <el-table-column label="地层走向" align="center" prop="dczx" min-width="90" show-overflow-tooltip />
      <el-table-column label="地层倾角" align="center" prop="dcqj" min-width="90" show-overflow-tooltip />
      <el-table-column label="备注" align="center" prop="bz" min-width="130" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:jsbb:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:jsbb:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" :page-sizes="[20, 50, 100]" />

    <!-- 添加或修改地质简介地层及岩性描述数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="井号" prop="jh">
              <el-input v-model="form.jh" placeholder="请输入井号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="层位" prop="cw">
              <el-input v-model="form.cw" placeholder="请输入层位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="目的层" prop="mdc">
              <el-input v-if="!showCascader" v-model="form.mdc" readonly style="width: 200px;">
                <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-col :span="12">
            <el-form-item label="设计底界深度" prop="sjdjsd">
              <el-input v-model="form.sjdjsd" placeholder="请输入设计底界深度"
                @input="handleDecimalInput(form.sjdjsd, 'sjdjsd')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="实际底界深度" prop="sjdjsd2">
              <el-input v-model="form.sjdjsd2" placeholder="请输入实际底界深度"
                @input="handleDecimalInput(form.sjdjsd2, 'sjdjsd2')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设计厚度" prop="sjhd">
              <el-input v-model="form.sjhd" placeholder="请输入设计厚度" @input="handleDecimalInput(form.sjhd, 'sjhd')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="实际厚度" prop="sjhd2">
              <el-input v-model="form.sjhd2" placeholder="请输入实际厚度" @input="handleDecimalInput(form.sjhd2, 'sjhd2')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地层走向" prop="dczx">
              <el-input v-model="form.dczx" placeholder="请输入地层走向" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="地层倾角" prop="dcqj">
              <el-input v-model="form.dcqj" placeholder="请输入地层倾角" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主要岩性描述" prop="zyyxms">
              <el-input v-model="form.zyyxms" placeholder="请输入主要岩性描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备注" prop="bz">
              <el-input v-model="form.bz" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listJsbb, getJsbb, delJsbb, addJsbb, updateJsbb } from "@/api/system/jsbb";
import { getMdcByQkid } from "@/api/scientificDrill/schemeOptimization";

export default {
  name: "Jsbb",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 地质简介地层及岩性描述数据表格数据
      jsbbList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为新增操作
      isAdd: false,
      // 目的层相关
      showCascader: false,
      mdcOptions: [],
      oilOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        sjdjsd: null,
        sjdjsd2: null,
        sjhd: null,
        sjhd2: null,
        zyyxms: null,
        dczx: null,
        dcqj: null,
        bz: null
      },
      // 表单参数
      form: {},
      // 目的层配置
      mdc: {
        lazy: true,
        lazyLoad: this.loadTreeNode,
        checkStrictly: true, // 允许选择任意级别的节点
        multiple: false,
        expandTrigger: 'click', // 点击展开
        emitPath: true // 返回完整路径
      },
      // 表单校验
      rules: {
        sjdjsd2: [
          { required: true, message: "实际底界深度不能为空", trigger: "blur" }
        ],
        jh: [
          { required: true, message: "井号不能为空", trigger: "blur" }
        ],
        sjhd2: [
          { required: true, message: "实际厚度不能为空", trigger: "blur" }
        ],
        cw: [
          { required: true, message: "层位不能为空", trigger: "blur" }
        ],
      },
      cascaderValue: [] // 用于绑定 el-cascader 的 v-model
    };
  },
  created() {
    this.getList();
    this.initMdcOptions();
  },
  methods: {
    /** 初始化目的层选项 */
    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
        }));
        this.mdcOptions = options;
      }).catch(error => {
        console.error('初始化目的层选项失败:', error);
        this.mdcOptions = [];
      });
    },
    /** 查询地质简介地层及岩性描述数据列表 */
    getList() {
      this.loading = true;
      listJsbb(this.queryParams).then(response => {
        this.jsbbList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        jh: null,
        dzsdmc: null,
        cw: null,
        mdc: null,
        mdcid: null,
        sjdjsd: null,
        sjdjsd2: null,
        sjhd: null,
        sjhd2: null,
        zyyxms: null,
        dczx: null,
        dcqj: null,
        bz: null
      };
      this.resetForm("form");
      this.showCascader = false;
      this.cascaderValue = []; // 重置 cascaderValue
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      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.open = true;
      this.isAdd = true;
      this.title = "添加地质简介地层及岩性描述数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const jh = row.jh || this.ids;
      const sjdjsd = row.sjdjsd;
      this.isAdd = false;
      getJsbb({ jh: jh, sjdjsd: sjdjsd }).then(response => {
        this.form = response.data;
        // 如果有目的层ID，需要设置级联选择器的值
        if (this.form.mdcid) {
          this.cascaderValue = [this.form.mdcid];
        }
        this.open = true;
        this.title = "修改地质简介地层及岩性描述数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.isAdd) {
            updateJsbb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addJsbb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const jhs = row.jh || this.ids;
      const sjdjsd = row.sjdjsd;
      this.$modal.confirm('是否确认删除地质简介地层及岩性描述数据编号为"' + jhs + '"的数据项？').then(function () {
        return delJsbb({ jh: jhs, sjdjsd: sjdjsd });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/jsbb/export', {
        ...this.queryParams
      }, `jsbb_${new Date().getTime()}.xlsx`)
    },
    /** 限制只能输入数字且保留两位小数 */
    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;
    },
    // 目的层相关方法
    openCascader() {
      this.showCascader = true;
      // 确保级联选择器正确初始化
      this.$nextTick(() => {
        if (this.$refs.cascader) {
          console.log('级联选择器已初始化');
          // 设置初始值
          if (this.form.mdcid) {
            this.cascaderValue = [this.form.mdcid];
          }
        }
      });
    },
    // 处理级联选择器点击
    handleCascaderClick() {
      console.log('级联选择器被点击');
    },
    change(val) {
      console.log('选择变化:', val); // 调试信息

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

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

        // 根据选中的值查找对应的标签
        this.findNodeLabel(val, this.mdcOptions).then(label => {
          this.form.mdc = label; // 设置选中层的 mc 到表单中
          console.log('设置目的层:', label, selectedValue);
          // 延迟关闭级联选择器，确保值已经设置
          setTimeout(() => {
            this.showCascader = false;
            // 确保值被正确设置
            this.$set(this.form, 'mdc', label);
            this.$set(this.form, 'mdcid', selectedValue);
            // 强制更新视图
            this.$forceUpdate();
          }, 100);
        }).catch(error => {
          console.error('查找节点标签失败:', error);
          // 如果查找失败，直接使用最后一个值作为标签
          this.form.mdc = selectedValue;
          setTimeout(() => {
            this.showCascader = false;
            this.$set(this.form, 'mdc', selectedValue);
            this.$set(this.form, 'mdcid', selectedValue);
            this.$forceUpdate();
          }, 100);
        });
      } else {
        this.showCascader = false;
      }
    },
    // 递归查找节点标签
    async findNodeLabel(path, options) {
      if (!options || !path || path.length === 0) return '';

      const currentValue = path[0];
      const node = options.find(item => item.value === currentValue);

      if (!node) return '';

      if (path.length === 1) {
        return node.label;
      }

      // 如果有子节点，继续查找
      if (node.children) {
        return this.findNodeLabel(path.slice(1), node.children);
      }

      // 如果没有子节点但路径还有值，需要动态加载
      const params = {
        dclevel: path.length + 1,
        pid: currentValue,
      };

      try {
        const response = await getMdcByQkid(params);
        const children = response.data.map(item => ({
          value: item.id,
          label: item.mc,
          leaf: false
        }));

        return this.findNodeLabel(path.slice(1), children);
      } catch (error) {
        console.error('加载子节点失败:', error);
        return node.label;
      }
    },
    loadTreeNode(node, resolve) {
      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: false // 移除叶子节点限制，允许选择任意级别
          }));
          console.log('转换后的节点:', nodes); // 调试信息
          resolve(nodes);
        } else {
          // 如果没有数据，返回空数组
          console.log('没有找到子节点数据');
          resolve([]);
        }
      }).catch(error => {
        // 处理请求失败的情况
        console.error('加载节点数据失败:', error);
        resolve([]);
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.app-container {
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
  padding: 10px;
}

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

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

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

// 级联选择器样式
::v-deep .cascader-popper {
  z-index: 3000 !important;
}

::v-deep .el-cascader {
  width: 100%;
}

::v-deep .el-cascader__dropdown {
  z-index: 3000 !important;
}
</style>
