<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item prop="jh">
        <el-input v-model="queryParams.jh" 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" icon="el-icon-plus" size="mini" @click="handleAdd">新建井</el-button>
      </el-form-item>
    </el-form>
    <div class="card-container">
      <el-card class="box-card" v-for="item in ytLists" :key="item.id"
        style="margin: 10px 10px 0 0; width: calc(20% - 10px);">
        <div slot="header" class="clearfix header">
          <div class="header-content">
            <div class="left">
              <img style="width: 80px;height: 80px" :src="wellImg" class="sidebar-logo" />
            </div>
            <div class="right">
              <div> <!-- 使用v-for指令循环渲染每一条数据 -->
                <div style="font-size: 24px;color: #1c84c6;font-weight: bold;cursor: pointer"
                  @click="toDesignScheme(item)">{{ item.jh }} <!-- 在循环中使用当前数据项的属性 -->
                </div>
                <div>
                  <i style="color: #909399" class="el-icon-user-solid"></i>
                  <span style="color: #909399">{{ item.jd }}</span> <!-- 在循环中使用当前数据项的属性 -->
                </div>
              </div>
            </div>
          </div>
          <div class="text item" style="display: flex; justify-content: flex-end;margin: 10px;">
            <el-button size="large" icon="el-icon-edit-outline" style="margin-right: 10px" type="text"
              @click="handleEdit(item)"></el-button>
            <el-button size="medium" icon="el-icon-delete" style="margin-right: 10px" type="text"
              @click="handleDelete(item)"></el-button>
            <el-button size="medium" icon="el-icon-lock" style="margin-right: 10px" type="text"
              @click="handleLock(item)"></el-button>

            <!-- <el-button size="medium" icon="el-icon-unlock" style=" margin-right: 10px" type="text" @click="handleFinalize"></el-button> -->
          </div>

        </div>
      </el-card>
    </div>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="78%" append-to-body>

      <div class="jsjStyle"
        style="background-color: #f4f8fe;border-radius: 10px;margin: -30px -10px -30px;padding: 10px;">
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <div class="cardStyle" style="border: 1px solid #eee">
            <div style="font-size: 14px;padding: 10px;border-bottom: 1px solid #eee;margin-top: -10px;">基本信息</div>
            <el-row style="margin-top: 10px">
              <el-col :span="8">
                <el-form-item label="盆地" prop="pd">
                  <el-select style="width: 200px" clearable v-model="form.pd" placeholder="请选择" @change="basinChange">
                    <el-option v-for="item in basinOptions" :key="item.id" :label="item.pdmc" :value="item.pdmc">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="钻井公司" prop="deptId">
                  <treeselect style="width: 200px" v-model="form.deptId" :options="deptOptions" :show-count="true"
                    placeholder="请选择钻井公司" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="区块" prop="qkmc">
                  <el-select clearable v-model="form.qkmc" placeholder="请选择">
                    <el-option v-for="item in blockOptions" :key="item.id" :label="item.qkmc" :value="item.qkmc">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="油田公司" prop="ytgs">
                  <el-select v-model="form.ytgs" clearable placeholder="请选择" style="width: 200px">
                    <el-option v-for="dict in dict.type.jt_ytgs" :key="dict.value" :label="dict.label"
                      :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="井号" prop="jh">
                  <el-input style="width: 200px" v-model="form.jh" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="井型" prop="jx">
                  <el-select v-model="form.jx" placeholder="请选择">
                    <el-option v-for="dict in dict.type.jt_jx" :key="dict.value" :label="dict.label"
                      :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="井队" prop="jd">
                  <el-input style="width: 200px" v-model="form.jd" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设计作业周期" prop="sjzyzq">
                  <el-input style="width: 200px" v-model="form.sjzyzq" clearable
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    @blur="form.sjzyzq = $event.target.value" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="井别" prop="jb">
                  <el-select v-model="form.jb" placeholder="请选择">
                    <el-option v-for="dict in dict.type.jt_jb" :key="dict.value" :label="dict.label"
                      :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

          </div>
          <div class="cardStyle" style="border: 1px solid #eee;margin-top: 10px">
            <div style="font-size: 14px;padding: 10px;border-bottom: 1px solid #eee;margin-top: -10px;">地质信息</div>
            <el-row style="margin-top: 10px">
              <el-col :span="8">
                <el-form-item label="井口坐标(X)" prop="jkzbx">
                  <el-input style="width: 200px" v-model="form.jkzbx" clearable
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    @blur="form.jkzbx = $event.target.value" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="井口坐标(Y)" prop="jkzby">
                  <el-input style="width: 200px" v-model="form.jkzby" clearable
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    @blur="form.jkzby = $event.target.value" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="入靶点A坐标(X)" prop="rbdazb">
                  <el-input style="width: 180px" v-model="form.rbdazb" clearable
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    @blur="form.rbdazb = $event.target.value" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="入靶点A坐标(Y)" prop="rbdbzb">
                  <el-input style="width: 200px" v-model="form.rbdbzb" clearable
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    @blur="form.rbdbzb = $event.target.value" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="地面海拔" prop="dmhb">
                  <el-input style="width: 200px" v-model="form.dmhb" clearable
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    @blur="form.dmhb = $event.target.value" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="完井方式" prop="wjfs">
                  <el-select v-model="form.wjfs" placeholder="请选择" style="width: 180px">
                    <el-option style="width: 180px" v-for="dict in dict.type.jt_wjfs" :key="dict.value"
                      :label="dict.label" :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="定稿设计井深m" prop="dgsjjs" style="width: 200px">
                  <el-input style="width: 200px" v-model="form.dgsjjs" clearable
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    @blur="form.dgsjjs = $event.target.value" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="深度零点" prop="sdld">
                  <el-select v-model="form.sdld" placeholder="请选择" style="width: 200px">
                    <el-option v-for="dict in dict.type.jt_sdld" :key="dict.value" :label="dict.label"
                      :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="目的层" prop="mdc">
                  <el-input style="width: 180px" v-if="!showCascader" v-model="form.mdc" readonly>
                    <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="form.mdc" @change="change"
                    :props="mdc"></el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="定稿设计水平段长度" prop="dgsjspdcd">
                  <el-input style="width: 200px" v-model="form.dgsjspdcd" clearable
                    oninput="value=value.replace(/^([0-9-]\d*\.?\d{0,2})?.*$/,'$1')"
                    @blur="form.dgsjspdcd = $event.target.value" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

        </el-form>
        <div style="display: flex;justify-content: center;margin: 10px;" slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- <el-dialog title="定稿" :visible.sync="openFinalize" width="300px" append-to-body>
            <el-form ref="form" :model="finalizeForm" :rules="rules" label-width="90px">
                <el-form-item label="井设计方案" prop="menuType">
                    <el-select v-model="finalizeForm.wellDesignScheme" placeholder="请选择">
                        <el-option v-for="item in wellDesignSchemeOptions" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFinalizeForm">确 定</el-button>
                <el-button @click="cancelFinalizeForm">取 消</el-button>
            </div>
        </el-dialog> -->
  </div>
</template>
<script>
import wellImg from '@/assets/images/home/well.png'
import { listFayh, deptTreeSelect, getBasinSelect, getBlockByPdid, deleteJtDjjc, addJtDjjc, getJtDjjc, updateJtDjjc, getMdcByQkid, LockJtDjjc } from "@/api/scientificDrill/schemeOptimization";
import { blob } from 'd3';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "tabsCard",
  components: { Treeselect },
  dicts: ['jt_ytgs', 'jt_jx', 'jt_jb', 'jt_wjfs', 'jt_sdld', 'jt_qklx'],
  props: {
    tabsId: {
      type: String,
      default: ''
    },


  },


  watch: {
    tabsId: {
      handler(val) {
        if (val) {
          this.getList();
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      showCascader: false,
      mdcOptions: [],
      zjgs: "",
      jh: "",
      jhdm: "",
      wellImg: wellImg,
      ytLists: [],
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        jh: undefined,
        pageNum: 1,
        pageSize: 10
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openFinalize: false,
      // 表单参数
      form: {
        remark: "",
        jh: "",
        pd: "",
        ytgs: "",
        zjgs: "",
        jd: "",
        qkdm: "",
        qkmc: "",
        jx: "",
        sjzyzq: "",
        jb: "",
        jkzbx: "",
        jkzby: "",
        rbdazb: "",
        rbdbzb: "",
        dmhb: "",
        wjfs: "",
        dgsjjs: "",
        sdld: "",
        dgsjspdcd: "",
        deptId: "",
        mdcid: "",
        mdc: "",
      },
      finalizeForm: {},
      // 表单校验
      rules: {
        jh: [
          { required: true, message: "井号不能为空", trigger: "blur" }
        ],
        ytgs: [
          { required: true, message: "油田公司不能为空", trigger: "blur" }
        ],
        zjgs: [
          { required: true, message: "钻井公司不能为空", trigger: "blur" }
        ],
        jd: [
          { required: true, message: "井队不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "钻井公司不能为空", trigger: "blur" }
        ],
      },
      basinValue: "",
      selectedBasinId: "",
      basinOptions: [],
      deptOptions: undefined,
      blockOptions: [],
      oilOptions: [],
      wellTypeOptions: [],
      wellClassifyOptions: [],
      completionMethodOptions: [],
      zeroDepthOptions: [],
      wellDesignSchemeOptions: [],
      pd: "",
      mdc: {
        lazy: true,
        lazyLoad: this.loadTreeNode // 直接将 loadTreeNode 方法作为 lazyLoad 属性传递
      },
      selectedBasinId: null, // 添加一个用于存储选中盆地的变量
      oilOptions: [] // 用于存储 MDC 数据
    }



  },


  mounted() {
    console.log('this.tabsId', this.tabsId);
    this.getList();
    this.getDeptTree();
    this.getBasinSelect();


  },

  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.jh = ''
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
      this.getList()
    },
    openCascader() {
      this.showCascader = true;

    },

    change(val) {
      this.showCascader = false; // 选择后关闭级联选择器
      let nodesObj = this.$refs['cascader'].getCheckedNodes();
      console.log(nodesObj, 'nodesObj');
      if (nodesObj && nodesObj.length > 0) {
        const lastNode = nodesObj[nodesObj.length - 1];
        this.form.mdc = lastNode.label; // 设置选中层的 mc 到表单中
        console.log(this.form.mdc, 'this.form.mdc ');
        this.form.mdcid = lastNode.value; // 设置选中层的 id 到表单中
        console.log(this.form.mdcid, 'this.form.mdcid ');
      }
    },

    // 查询
    getList() {
      // 创建一个本地变量，初始值为 props 中的 tabsId
      let localTabsId = this.tabsId;
      // 如果 localTabsId 为 "所有油田"，则将其设置为空字符串
      if (localTabsId === "所有油田") {
        localTabsId = "";
      }

      const val = {
        ytgs: localTabsId,
        jh: this.queryParams.jh
      }
      listFayh(val).then(response => {
        console.log('this.tabsId', localTabsId);
        console.log('查询');
        this.ytLists = response.rows;
        console.log(this.ytLists, 'this.ytLists');
      });
    },

    /** 查询部门树结构 */
    getDeptTree() {
      deptTreeSelect({ level: "3" }).then(response => {
        this.deptOptions = response.data;
        console.log(this.deptOptions, 'this.deptOptions');
      });
    },
    // 查询盆地结构
    getBasinSelect() {
      getBasinSelect().then(response => {
        this.basinOptions = response;

        console.log(this.basinOptions, ' this.basinOptions');
        this.blockOptions = []; // 清空区块选项
        this.form.qkmc = ''; // 清空所选区块的值
        this.basinChange();


      });
    },

    // 盆地选项改变时触发 区块
    basinChange() {
      const selectedBasinName = this.form.pd; // 获取选中的盆地名称
      console.log(selectedBasinName, 'selectedBasinName');
      const selectedBasin = this.basinOptions.find(item => item.pdmc === selectedBasinName); // 根据名称获取相应的盆地对象
      console.log(selectedBasin, 'selectedBasin');
      if (selectedBasin) {
        getBlockByPdid(selectedBasin.id).then(response => { // 使用盆地对象的ID来获取区块
          this.blockOptions = response.rows;
        });
      }
    },

    // 获取 MDC 数据
    // getMdc() {
    //     const params = {
    //         dclevel: '1',
    //         pid: ''
    //     };
    //     getMdcByQkid(params).then(response => {
    //         const oilOptions = response.data; // 保存获取到的数据
    //         console.log(oilOptions, 'this.oilOptions');
    //         this.oilOptions = oilOptions; // 将数据存储到组件的属性中
    //         this.loadTreeNode((nodes) => {
    //             this.mdcOptions = nodes;
    //         }, oilOptions);
    //     }).catch(error => {
    //         console.error('Error fetching MDC data:', error);
    //     });
    // },
    loadTreeNode(node, resolve) {
      console.log(node, 'node');
      console.log(resolve, 'resolve');
      const params = {
        dclevel: node.level + 1,
        pid: node.value,
      };
      console.log(params, 'params');
      // 发起请求获取节点数据
      getMdcByQkid(params).then(response => {
        const oilOptions = response.data; // 获取到的数据
        console.log(oilOptions, 'this.oilOptions');
        if (Array.isArray(oilOptions)) {
          // 将数据转换为符合 Cascader 要求的格式
          const nodes = oilOptions.map(item => ({
            value: item.id,
            label: item.mc,
            leaf: item.dclevel >= 5
          }));
          console.log(nodes, 'nodes');
          resolve(nodes);
        } else {
          // 处理异常情况
        }
      }).catch(error => {
        // 处理请求失败的情况

      });
    },

    //点击卡片
    toDesignScheme(item) {
      this.$store.dispatch('setJh', item.jh);
      this.$store.dispatch('setJhdm', item.jhdm);
      console.log(item, 'item');
      this.$router.push({
        path: "/designScheme",
        query: {
          jhdm: item.jhdm,
          jh: item.jh
        }
      })
    },
    //新建井
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增井设计"
    },
    //编辑
    handleEdit(item) {
      this.reset();
      this.open = true;
      console.log(item, 'item');
      const jhdm = item.jhdm;
      getJtDjjc(jhdm).then(response => {
        this.form = response.data;
        // this.form.mdc = response.data.mdcid;

        console.log(response, 'response');
        this.open = true;
        this.title = "修改";
      });
      this.title = "修改井设计"
    },
    /** 提交按钮 */
    submitForm() {

      // const pd = this.form.pd
      // this.form.pdid = pd == '' ? '' : this.basinOptions.find(item => item.pdmc == pd).pdid
      // const qkmc = this.form.qkmc
      // this.form.qkdm = qkmc == '' ? '' : this.blockOptions.find(item => item.qkmc == qkmc).qkdm
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.jhdm != null && this.form.jhdm !== '') {
            // 如果 jhdm 存在且不为空，则执行更新操作
            updateJtDjjc(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 否则执行新增操作
            addJtDjjc(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    // 表单重置
    reset() {
      this.form = {

      };
      this.resetForm("form");
    },

    cancel() {
      this.open = false;

    },


    /** 删除按钮操作 */
    handleDelete(item) {
      const jhdms = item.jhdm;
      this.$modal.confirm('是否确认删除编号为"' + jhdms + '"的数据项？').then(function () {
        return deleteJtDjjc(jhdms);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    /** 锁定按钮操作 */
    handleLock(item) {
      const jhdm = item.jhdm;
      this.$modal.confirm('是否确认锁定？').then(function () {
        return LockJtDjjc(jhdm);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("已锁定");
      }).catch(() => { });
    },


    submitFinalizeForm() {
      this.openFinalize = false

    },
    cancelFinalizeForm() {
      this.openFinalize = false

    },

  }
}
</script>

<style scoped lang="scss">
.cardStyle {
  // border: 1px solid red;
  border: 1px solid #dedede;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.1);
  padding: 12px;
}

.cardStyle:hover {
  box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.2);
}

::v-deep .el-form-item {
  margin-bottom: 10px;
}

.text {
  font-size: 14px;
}



.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.card-container {
  display: flex;
  flex-wrap: wrap;
  /* 当空间不足时换行 */
  justify-content: flex-start;
  /* 卡片从左向右排列 */
  align-items: flex-start;
  /* 卡片顶部对齐 */
  margin-top: -10px;
}

.box-card {
  flex: 0 0 auto;
  width: 300px;
}

.header-content {
  display: flex;
  align-items: center;
  /* 垂直居中对齐 */
}

.left {
  margin-right: 10px;
  /* 左右间距 */
}

.right {
  flex-grow: 1;
  /* 右侧内容占据剩余空间 */
}

::v-deep .el-card__body {
  padding: 0 !important;
}
</style>
