<template>
  <div class="app-container" ref="layout">
    <el-row :gutter="20">
      <el-col :span="5">
        <div class="left" ref="box">
          <div class="name">
            第一层
            <el-button plain icon="el-icon-circle-plus-outline" size="mini" @click="handleUpdateserve"></el-button>
            <el-button v-if="this.itemname" plain icon="el-icon-s-tools" size="mini" @click="handleedit"></el-button>
            <el-button v-if="this.itemname" plain icon="el-icon-delete" size="mini" @click="handledelete"></el-button>
          </div>
          <div>
            <el-input v-model="name" placeholder="请输入字段名称" clearable />
          </div>
          <div class="listitem">
            <div :class="itemname == null ? 'allactive' : 'all'" @click="itemdata()">
              全部
            </div>
            <!-- <span class="count">{{ count }}</span> -->
          </div>
          <div class="listitem" :key="index" @click="itemdata(item)" v-for="(item, index) in DepartmentoList">
            <div :class="itemname == item.id ? 'allactive' : 'all'">
              {{ item.termContent }}
            </div>
            <span class="count"></span>
          </div>
        </div>
      </el-col>
      <el-col :span="19" :xs="24">
        <div ref="topform" class="form">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="内容名称" prop="termContent">
              <el-input v-model="queryParams.termContent" placeholder="请输入内容名称" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="父编码" prop="parentTermCode">
        <el-input
          v-model="queryParams.parentTermCode"
          placeholder="请输入父编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="层级，从1开始，1,2,3……" prop="termLevel">
        <el-input
          v-model="queryParams.termLevel"
          placeholder="请输入层级，从1开始，1,2,3……"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
            <!-- <el-form-item label="内容排序" prop="termSort">
        <el-input
          v-model="queryParams.termSort"
          placeholder="请输入内容排序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
            <el-form-item label="内容备注信息" prop="termRemark" label-width="220">
              <el-input v-model="queryParams.termRemark" 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-form-item>
          </el-form>
        </div>
        <div ref="mb8" class="mb8">
          <el-row :gutter="10" class="">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['system:bank:add']">新增</el-button>
            </el-col>

            <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                v-hasPermi="['system:bank:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                @click="handleDelete" v-hasPermi="['system:bank:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                v-hasPermi="['system:bank:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </div>
        <div ref="table">
          <el-table :max-height="maxTableHeight" v-loading="loading" :data="bankList"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="内容名称" align="center" prop="termName" /> -->
            <el-table-column label="字段名称" align="center" prop="termContent" />
            <el-table-column label="层级" align="center" prop="termLevel" />
            <el-table-column label="内容排序" align="center" prop="termSort" />
            <el-table-column label="内容备注信息" align="center" prop="termRemark" />
            <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button type="text" icon="el-icon-plus" size="mini" @click="handle(scope.row)"
                  v-hasPermi="['system:bank:add']">第三层</el-button>
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:bank:edit']">修改</el-button>

                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:bank:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" /> -->
        <myPagination v-show="total > 0" :total="total" :pageSize="queryParams.pageSize"
          :indexFromWrap="queryParams.pageNum" @updateCPage="updateCPage"></myPagination>
      </el-col>
    </el-row>

    <!-- </el-row> -->
    <!-- 添加或修改常用术语(知识库)对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="画像标签和知识库字段表id" prop="termCode">
          <el-input
            v-model="form.termCode"
            placeholder="请输入画像标签和知识库字段表id"
          />
        </el-form-item> -->
        <!-- <el-form-item label="内容名称" prop="termName">
          <el-input v-model="form.termName" placeholder="请输入内容名称" />
        </el-form-item> -->
        <el-form-item label="内容名称" prop="termContent">
          <el-input v-model="form.termContent" placeholder="请输入内容名称" />
          <!-- <editor v-model="form.termContent" :min-height="192" /> -->
        </el-form-item>
        <el-form-item label="父级名称" prop="parentTermCode">
          <el-select v-model="form.parentTermCode" placeholder="请选择" @change="change" style="width:360px">
            <el-option v-for="item in treeOptions" :key="item.termCode" :label="item.termContent"
              :value="item.termCode">
            </el-option>
          </el-select>
          <!-- <el-cascader
            :props="{ checkStrictly: true }"
            :options="treeOptions"
            @change="change($event)"
            style="width: 205px"
            v-model="form.parentId"
            :show-all-levels="false"
            clearable
            ref="cascader"
          ></el-cascader> -->
          <!-- <el-input v-model="form.parentTermCode" placeholder="请输入父编码" /> -->
        </el-form-item>
        <!-- <el-form-item label="层级，从1开始，1,2,3……" prop="termLevel">
          <el-input
            v-model="form.termLevel"
            placeholder="请输入层级，从1开始，1,2,3……"
          />
        </el-form-item> -->
        <el-form-item label="内容排序" prop="termSort">
          <el-input v-model="form.termSort" placeholder="请输入内容排序" />
        </el-form-item>
        <el-form-item label="内容备注信息" prop="termRemark">
          <el-input v-model="form.termRemark" placeholder="请输入内容备注信息" />
        </el-form-item>
      </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>
    <!-- 第一层 -->
    <el-dialog :title="titles" :visible.sync="opens" width="500px" append-to-body>
      <el-form ref="format" :model="format" :rules="rules" label-width="120px" :inline="true">
        <el-form-item label="内容名称" prop="termContent">
          <el-input v-model="format.termContent" placeholder="请输入内容名称" />
        </el-form-item>
        <el-form-item label="排序" prop="termSort">
          <el-input v-model="format.termSort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="备注信息" prop="termRemark">
          <el-input v-model="format.termRemark" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForms">确 定</el-button>
        <el-button @click="cancels">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBank,
  getBank,
  delBank,
  addBank,
  updateBank,
  selectTermBankList,
} from "@/api/system/bank";
export default {
  name: "Bank",
  data() {
    return {
      opens: false,
      itemname: null,
      count: "", //全部
      treeOptions: [],
      DepartmentoList: [], //左侧数组
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 常用术语(知识库)表格数据
      bankList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      maxTableHeight: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        termCode: null,
        termName: null,
        termContent: null,
        parentTermCode: null,
        termLevel: 2,
        termSort: null,
        termRemark: null,
      },
      name: "",
      querydepartmen: {
        termContent: "",
      },
      format: {
        termContent: "",
        id: "",
      },
      // 表单参数
      form: {},
      titles: "",
      // 表单校验
      rules: {
        termCode: [
          {
            required: true,
            message: "画像标签和知识库字段表id不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    name(val) {
      this.querydepartmen.termContent = val;
      this.mentlist();
    },
  },
  created() {
    this.getList();
    this.mentlist();
  },
  mounted() {
    this.getMaxTableHeight()
    this.screenChange()
  },
  methods: {
    change(e) {
      this.form.termLevel = this.treeOptions?.find(
        (f) => f.termCode == e
      )?.termLevel;
    },
    // 左侧提交
    submitForms() {
      this.$refs["format"].validate((valid) => {
        if (valid) {
          if (this.format.id != "") {
            updateBank(this.format).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.opens = false;
              this.mentlist();
            });
          } else {
            addBank(this.format).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.opens = false;
              this.mentlist();
            });
          }
        }
      });
    },
    cancels() {
      this.opens = false
      this.reset();
    },
    // change(e) {
    //   // this.form.parentId = e;
    //   if (e) {
    //     this.form.parentId = e[e.length - 1];
    //   }
    // },
    // gettreelist() {
    //   agencyList().then((res) => {
    //     // 接口请求
    //     this.deptOptions = res.data;
    //     this.treeOptions = res.data.map((item) => {
    //       return { value: item.id, ...item };
    //     });
    //     // this.treeOption = {
    //     //   lazy: true,
    //     //   checkStrictly: true,
    //     //   lazyLoad: this.lazyLoad,
    //     // };
    //   });
    // },
    // 左侧服务方式列表
    mentlist() {
      this.loading = true;
      selectTermBankList(this.querydepartmen).then((response) => {
        this.DepartmentoList = response.data;
        this.treeOptions = response.data;
        // let sum = 0;
        // this.DepartmentoList.forEach((item) => {
        //   if (item.serviceContentNum) {
        //     sum += item.serviceContentNum;
        //   }
        //   this.count = sum;
        // });
        this.loading = false;
      });
    },
    // 左侧科室
    itemdata(item) {
      if (item) {
        this.queryParams.parentTermCode = item.termCode;
        this.queryParams.termLevel = 2;
        this.bankList = [];
        this.getList();
        this.itemname = item.id;
      } else {
        this.itemname = null;
        this.queryParams.termLevel = 2;
        this.queryParams.parentTermCode = '';
        this.bankList = [];
        this.getList();
      }
    },
    // 修改服务方式
    handleedit() {
      this.resetformat();
      this.format.id = this.itemname;
      if (this.itemname) {
        getBank(this.itemname).then((response) => {
          this.format = response.data;
          this.opens = true;
          this.title = "修改常用术语";
        });
      } else {
        this.$message.error("请先选择一种常用术语");
      }
      // this.format.serviceWayName = "";
      // this.titles = "修改内容";
    },
    handledelete() {
      this.resetformat();
      const id = this.itemname;
      this.$modal
        .confirm("是否确认删除此内容？")
        .then(function () {
          return delBank(id);
        })
        .then(() => {
          this.mentlist();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    // },
    handleUpdateserve() {
      this.resetformat();
      this.titles = "新增内容名称";
      // this.format.serviceWayName = "";
      this.format.id = "";
      this.opens = true;
    },
    /** 查询常用术语(知识库)列表 */
    getList() {
      this.loading = true;
      listBank(this.queryParams).then((response) => {
        if (response.rows.length > 0) {
          response.rows.forEach((e) => {
            // if(e.termLevel==1){
            //   this.DepartmentoList.push(e);
            // }
            // else
            if (e.termLevel == 2) {
              this.bankList.push(e);
              // this.bankList.push(e);
              this.total = this.bankList.length;
            }
          });
        } else {
          this.bankList = [];
          // this.DepartmentoList=[]
        }
        // this.bankList = response.rows;
        // this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        termCode: null,
        termName: null,
        termContent: null,
        parentTermCode: null,
        termLevel: null,
        termSort: null,
        termRemark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    // 表单重置
    resetformat() {
      this.format = {
        id: null,
        termCode: null,
        termName: null,
        termContent: null,
        parentTermCode: null,
        termLevel: null,
        termSort: null,
        termRemark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("format");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.bankList = [];
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加常用术语(知识库)";
    },
    handle(row) {
      // this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews }) => {
      this.$router.push({
        path: "/knowledge/bankSpecialization",
        query: {
          path: "/knowledge/bank",
          parentTermCode: row.termCode,
          termLevel: row.termLevel,
          termContent: row.termContent,
          // routeName: row.routeName,
        },
      });
      // })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBank(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改常用术语(知识库)";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBank(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.bankList = [];
              this.getList();
            });
          } else {
            addBank(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.bankList = [];
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除常用术语(知识库)编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBank(ids);
        })
        .then(() => {
          this.bankList = [];
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/bank/export",
        {
          ...this.queryParams,
        },
        `bank_${new Date().getTime()}.xlsx`
      );
    },
    updateCPage(index, size) {
      this.queryParams.pageNum = index
      this.queryParams.pageSize = size
      this.getList();
    },
    // 获取表格最高高度
    getMaxTableHeight() {
      const windowInnerHeight = window.innerHeight // 屏幕可视高度
      const layoutDiv = this.$refs.layout
      const formDiv = this.$refs.topform
      const mb8Div = this.$refs.mb8
      this.maxTableHeight =
        windowInnerHeight - 134 -
        this.getBoxPadding(layoutDiv) -
        this.getBoxHeight(mb8Div) -
        this.getBoxHeight(formDiv)
    },
    // 屏幕resize监听
    screenChange() {
      // 屏幕resize监听事件：一旦屏幕宽高发生变化，就会执行resize
      window.addEventListener('resize', this.getMaxTableHeight, true)
      // 将屏幕监听事件移除
      // 这步是必须的。离开页面时不移除，再返回，或者进入到别的有相同元素的页面会报错
      // 或者将这里的方法直接写在beforeDestroy函数中也可以
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', this.getMaxTableHeight, true)
      })
    },
  },
};
</script>
<style lang="scss">
.left {
  height: calc(100vh - 119px);
  overflow-y: auto;

  .name {
    font-weight: 700;
    margin-bottom: 10px;
  }

  .listitem {
    width: 100%;
    height: 50px;
    border-bottom: 1px solid #dcdfe6;

    .count {
      display: inline-block;
      position: relative;
      // right: -172px;
      left: 216px;
      color: #a4a6aa;
      top: -35px;
      font-size: 13px;
    }

    .all {
      height: 50px;
      line-height: 50px;
      padding-left: 13px;
    }

    .allactive {
      background: #e8f4ff;
      height: 50px;
      line-height: 50px;
      padding-left: 13px;
      border-left: 3px solid #4d9de7;
    }
  }
}
</style>
<style lang="scss" scoped>
.app-container {
  padding: 20px 0 0 20px !important;
}

::v-deep .el-row {
  height: 100% !important;
}
</style>
