<template>
  <div class="box">
    <div style="position: relative">
      <div class="contenttitle">
        基础资料 /
        <span class="contenttitleBold">危急值类别</span>
      </div>
      <div style="display: block; margin-top: 7px; margin-right: 110px">
        <div style="background-color: #fff; border-radius: 8px; padding: 15px">
          <el-table
            :data="tableData"
            :height="window.pageHeight < 600 ? 450 : window.pageHeight - 130"
            row-key="criticalFollowValueTypeId"
            :key="tableKey"
            default-expand-all
            :tree-props="{
              children: 'treeChildren',
              hasChildren: 'hasChildren',
            }"
            highlight-current-row
            @row-click="treeclick"
            ref="tableData"
            class="el-table__body-wrapper tbody"
          >
            <el-table-column prop="displayName" label="类别">
              <template slot-scope="scope">
                <span>
                  <span class="treeicons">
                    <!-- <i
                        class="el-icon-document-remove"
                        v-if="data.parentId == null"
                      ></i> -->
                    <img
                      style="width: 20px; height: 20px; vertical-align: sub"
                      src="@/assets/images/order.png"
                      v-if="!scope.row.parentId"
                    />
                  </span>
                  <span
                    :class="
                      !scope.row.parentId ? 'maxtitle' : 'mintitle'
                    "
                    >{{ scope.row.displayName }}</span
                  >
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="simpleCode"
              label="拼音简码"
            ></el-table-column>
            <el-table-column label="操作" width="" align="center">
              <template>
                <el-tag
                  class="move"
                  style="
                    cursor: move;
                    background-color: rgb(245, 245, 245);
                    border: none;
                  "
                  draggable="true"
                >
                  <i
                    class="el-icon-d-caret"
                    style="width: 1rem; height: 1rem; color: rgb(113, 113, 113)"
                  ></i>
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 按钮区域 -->
      <div
        style="
          margin-left: 10px;
          margin-top: 3%;
          position: absolute;
          top: 0;
          right: 0;
        "
      >
        <!-- <el-button type="" @click="addll" class="commonbutton">新增</el-button> -->
        <div
          v-if="tableData.length == '0' ? true : false"
          style="margin-bottom: 10px"
        >
          <el-button type="" class="commonbutton" @click="append"
            >新增危急值类别</el-button
          >
        </div>
        <div>
          <el-button
            type=""
            @click="addll"
            :disabled="isshow"
            class="commonbutton"
            >新增同级</el-button
          >
        </div>
        <div style="margin-top: 10px">
          <el-button
            type=""
            @click="append"
            :disabled="isshow"
            class="commonbutton"
            >新增子级</el-button
          >
        </div>
        <div style="margin-top: 10px">
          <el-button
            type=""
            @click="rena"
            :disabled="isshow"
            class="commonbutton"
            >编辑</el-button
          >
        </div>
        <div style="margin-top: 10px">
          <el-button
            type=""
            @click="deleates"
            :disabled="isshow"
            class="deleteButton"
            >删除</el-button
          >
        </div>
        <div style="margin-top: 10px">
          <el-button
            type=""
            @click="assertion"
            :disabled="isshows"
            class="commonbutton"
            >排序</el-button
          >
        </div>
        <div style="margin-top: 10px">
            <el-button
              type=""
              :disabled="isshows"
              @click="cancellation"
              class="commonbutton"
              >取消</el-button
            >
          </div>
      </div>
    </div>
    <el-dialog
      :title="title == 1 ? '新增' : '修改'"
      :visible.sync="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
    >
      
      <el-form :model="form" label-width="80px" :rules="rules" ref="ruleForm">
        <el-row v-if="title == 2 ? true : false">
          <el-col :span="12">
            <el-form-item label="上级部门">
              <el-cascader
        v-if="title == 2"
        ref="depref"
        @change="cascaderchang"
        :show-all-levels="false"
        v-model="departmentname"
        style="margin-left: 10px"
        :options="itemtypedata"
        :props="{
          checkStrictly: true,
          children: 'treeChildren',
          label: 'displayName',
          value: 'criticalFollowValueTypeId',
        }"
        clearable
        size="small"
      ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="displayName">
              <el-input
                v-model="form.displayName"
                ref="refinput"
                size="small"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="difference"
          >取 消</el-button
        >
        <el-button type="" @click="addoredit" class="commonbutton"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  criticalFollowValueType ,
  pojectadd,
  projecteditid,
  projecttype,
  projectedid,
} from "@/request/commonapi";
import { basicsetings, physicalexaminationlist } from "@/request/systemapi";
import { getapi, postapi, putapi } from "@/api/api";
import { mapState } from "vuex";
import { objCopy } from "@/utlis/proFunc";
import Sortable from "sortablejs";
export default {
  data() {
    return {
      departmentname: "",
      itemtypedata: [],
      rules: {
        displayName: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ]
      },
      defaultProps: {
        children: "treeChildren",
        label: "displayName",
      },
      title: 1,
      tableData: [],
      tableHeight: window.innerHeight - 180, //表格动态高度
      screenHeight: window.innerHeight, //内容区域高度
      form: {
        criticalFollowValueTypeId: "",
        displayName: "",
        parentId: ""
      },
      dialogVisible: false,
      guideoptions: [],
      row: {},
      isshow: true,
      activeRows: [],
      message: true,
      tableKey:'',
      isshows:true
    };
  },
  created() {
    this.getlist();
  },
  mounted() {
    this.rowDrop();
  },
  computed: {
    ...mapState(["window"]),
  },
  methods: {
    cascaderchang(v) {
      this.departmentname = v[v.length - 1];
    },

    treeToTable(tree, level, arr = []) {
      tree.map((item, index) => {
        this.$set(item, "level", level);
        arr.push(item);
        if (item.treeChildren && item.treeChildren != []) {
          arr.push(...this.treeToTable(item.treeChildren, level + 1));
        }
      });
      // 返回结果
      return arr;
    },
    flatToTree(flatData, idProp, parentIdProp) {
      const treeData = [];
      const idMap = {};

      // 将所有节点存储到 idMap 中，方便快速查找节点
      for (const node of flatData) {
        idMap[node[idProp]] = node;
        node.treeChildren = [];
      }

      // 遍历所有节点，将它们添加到树形结构中
      for (const node of flatData) {
        const parent = idMap[node[parentIdProp]];
        if (parent) {
          parent.treeChildren.push(node);
        } else {
          treeData.push(node);
        }
      }

      return treeData;
    },
    screenData(tree,row,increase,arr = []){
      if(increase){
        arr.push(row)
      }
      tree.map((item,index)=>{
        if(item.parentId===row.criticalFollowValueTypeId){
          arr.push(item)
          if(item.treeChildren && item.treeChildren != []){
            arr.push(...this.screenData(item.treeChildren,item));
          }
        }
      })
      return arr;
    },
    //初始化
    rowDrop() {
      this.$nextTick(() => {
        const tbody = document.querySelector(".el-table__body-wrapper tbody");
        const _this = this;
        Sortable.create(tbody, {
          handle: ".move",
          animation: 300,
          //   onStart: () => { // 开始拖拽前把树形结构数据扁平化
          //   _this.activeRows = _this.treeToTable(_this.tableData) // 把树形的结构转为列表再进行拖拽
          // },
          onMove({ dragged, related }) {
            // if(dragged.rowIndex<related.rowIndex){
            //   if (_this.message) {
            //     _this.$message.warning("不允许向下拖拽");
            //     _this.message = false;
            //   }
            //   return false;
            // }
            const oldRow = _this.activeRows[dragged.rowIndex];
            const newRow = _this.activeRows[related.rowIndex];
            if (
              oldRow.level !== newRow.level ||
              oldRow.parentId !== newRow.parentId
            ) {
              if (_this.message) {
                _this.$message.warning("不允许跨级拖拽");
                _this.message = false;
              }
              return false;
            }
          },
          onChoose({newIndex,oldIndex }) {
            _this.$refs['tableData'].setCurrentRow(_this.activeRows[oldIndex]);
            _this.treeclick(_this.activeRows[oldIndex]);
            // const oldRow = _this.activeRows[oldIndex];
            // const newRow = _this.activeRows[newIndex];
            // if(oldRow.level === newRow.level ||
            //   oldRow.parentId === newRow.parentId){
            //     _this.$refs['tableData'].setCurrentRow(_this.activeRows[newIndex]);
            //   }
          },
          onEnd({ newIndex, oldIndex }) {
            _this.message = true;
            const oldRow = _this.activeRows[oldIndex] // 移动的那个元素
          const newRow = _this.activeRows[newIndex] // 新的元素
          if (oldIndex === newIndex || oldRow.parentId !== newRow.parentId || oldRow.level != newRow.level) return
            if (oldIndex !== newIndex || oldRow.level === newRow.level || oldRow.parentId === newRow.parentId) {
            let oldRowSuffixData=_this.screenData(_this.activeRows,oldRow,true)
            let newRowSuffixData=_this.screenData(_this.activeRows,newRow,true)
            const targetRows = _this.activeRows.splice(oldIndex, oldRowSuffixData.length)
              if (oldIndex > newIndex) {
                _this.activeRows.splice(newIndex, 0, ...targetRows)
              } else if (oldIndex < newIndex) {
                _this.activeRows.splice(newIndex + newRowSuffixData.length - oldRowSuffixData.length, 0, ...targetRows)
              }
            let data = _this.flatToTree(
              _this.activeRows,
              "criticalFollowValueTypeId",
              "parentId"
            );
            _this.$set(_this,'tableData',data)
            _this.isshows = false;
            let beforeScrollTop = _this.$refs.tableData.$el.querySelector('div.el-table__body-wrapper').scrollTop
            _this.tableKey = new Date().getTime()
            _this.$nextTick(() => {
            _this.$refs.tableData.doLayout()
              _this.$refs["tableData"].setCurrentRow(
                oldRow
              );
              _this.treeclick(oldRow);
              setTimeout(() => {
              _this.$refs.tableData.$el.querySelector('div.el-table__body-wrapper').scrollTop = beforeScrollTop
              }, 0)
              _this.rowDrop()
            });
            }
          }
        })
      });
    },
    //确定排序
    assertion() {
      const result = [];
      this.activeRows.forEach((item, index) => {
          result.push({ id: item.criticalFollowValueTypeId, displayOrder: index+1 });
      });
      postapi("/api/app/CriticalFollowValueType/UpdateSortMany",{ itemList: result }).then((res) => {
        if (res.code != -1) {
          this.isshows = true;
        }
      });
    },
    //取消按钮
    cancellation() {
      this.getlist()
      this.isshows=true
    },
    //编辑弹框
    rena() {
      this.departmentname = this.row.parentId;
      this.title = 2;
      this.dialogVisible = true;
      if (this.$refs.ruleForm !== undefined) {
        this.$refs.ruleForm.resetFields();
      }
      postapi("/api/app/CriticalFollowValueType/Get",{
        criticalFollowValueTypeId:this.row.criticalFollowValueTypeId
      }).then((res) => {
        if (res.code != -1) {
          objCopy(res.data, this.form);
          this.form.criticalFollowValueTypeId=res.data.id
        }
      });
      // getapi(`/api/app/item/in-item-type/${data.id}`).then((res) => {
      //   this.itemtypedata = res.data;
      //   console.log(res, "222222222222222222");
      // });
      //获取项目类别数据结构数据
      criticalFollowValueType().then(
        (res) => {
          if (res.code != -1) {
            this.itemtypedata = res.data;
          }
        }
      );
    },
    // 删除
    deleates() {
      this.$confirm("是否删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        cancelButtonClass: "difference",
        confirmButtonClass: "commonbutton",
      })
        .then(() => {
          postapi("/api/app/CriticalFollowValueType/Delete",{
            criticalFollowValueTypeId:this.row.criticalFollowValueTypeId
          }).then((res) => {
            if (res.code != -1) {
              //this.$message.success("删除成功");
              this.row = this.$options.data().row;
              this.getlist();
              this.isshow = true;
            }
          });
        })
        .catch(() => {
          this.$message("取消成功");
        });
    },
    append() {
      // this.form = {};
      // if(node&& data){
      //   this.form.parentId = data.id;
      // }
      // Object.assign(this.$data.form, this.$options.data().form);
      this.form = this.$options.data().form;
      this.form.parentId = this.row.criticalFollowValueTypeId;
      this.dialogVisible = true;
      if (this.$refs.ruleForm !== undefined) {
        this.$refs.ruleForm.resetFields();
      }
      this.$nextTick(() => {
        this.$refs.refinput.focus();
      });
    },
    //新增弹框
    addll() {
      // this.form = {};
      // this.form.parentId = data.parentId;
      // Object.assign(this.$data.form, this.$options.data().form);
      this.form = this.$options.data().form;
      this.form.parentId = this.row.parentId;
      this.dialogVisible = true;
      this.title = 1;
      if (this.$refs.ruleForm !== undefined) {
        this.$refs.ruleForm.resetFields();
      }
      this.$nextTick(() => {
        this.$refs.refinput.focus();
      });
    },
    //确定新增或者编辑
    addoredit() {
      this.$refs.ruleForm.validate((v) => {
        if (v) {
          if (this.title == 1) {
            if (this.tableData.length == 0) {
                postapi("/api/app/CriticalFollowValueType/Create", {
            displayName: this.form.displayName,
          }).then((res) => {
            if (res.code != -1) {
                  this.getlist();
                  this.$refs["tableData"].setCurrentRow("");
                  this.dialogVisible = false;
                  this.isshow = true;
            }
          });
            } else {
              postapi("/api/app/CriticalFollowValueType/Create", {
                parentId: this.form.parentId,
                displayName: this.form.displayName
              }).then((res) => {
                if (res.code != -1) {
                  //this.$message.success("新增成功");
                  this.getlist();
                  this.$refs["tableData"].setCurrentRow("");
                  this.dialogVisible = false;
                  this.isshow = true;
                }
              });
            }

            // console.log(this.form);
          } else if (this.title == 2) {
            postapi("/api/app/CriticalFollowValueType/Update",{
              criticalFollowValueTypeId: this.form.criticalFollowValueTypeId,
              displayName: this.form.displayName
            }).then((res) => {
              if (res.code != -1) {
                //this.$message.success("修改成功");
                this.getlist();
                this.$refs["tableData"].setCurrentRow("");
                this.dialogVisible = false;
                this.isshow = true;
              }
            });
          }
        }
      });
    },
    // 点击获取每一列
    treeclick(row) {
      this.row = { ...row };
      this.isshow = false;
    },
    getlist() {
      criticalFollowValueType().then((res) => {
        if (res.code != -1) {
          this.tableData = [...res.data];
          this.activeRows = this.treeToTable(this.tableData, 1);
        }
      });
    },
  },
};
</script>
<style scoped>
@import "../../assets/css/global_button.css";
@import "../../assets/css/global_dialog.css";
@import "../../assets/css/global_table.css";
@import "../../assets/css/global_form.css";
@import "../../assets/css/global_input.css";
@import "../../assets/css/global.css";

.box {
  display: flex;
  flex-direction: column;
}

.layeredleftright {
  width: 100%;
  display: flex;
  flex-direction: column;
}

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

/* el-dialog的头部样式 */
:deep .el-dialog__header {
  padding: 11px 20px 11px;
}

/* el-dialog的主体样式 */
:deep .el-dialog__body {
  padding: 0px 20px 0px;
}

/* el-divider样式 */
:deep .el-divider--horizontal {
  margin: 0px 0 12px;
}

/* el-dialog的底部样式 */
:deep .el-dialog__footer {
  padding: 0px 20px 14px;
}
:deep .el-table tr {
  height: 35px;
}
</style>
