<template>
  <div class="box">
    <div style="position: relative">
      <div class="middlebox">
        <div class="contenttitle">
          职业病设置 /
          <span class="contenttitleBold">毒害因素</span>
        </div>
        <div class="seachinput">
          <el-select v-model="department" placeholder="请搜索" filterable :filter-method="remoteMethodes"
            default-first-option @change="quckDepartments" clearable size="small">
            <el-option v-for="item in quckDepartment" :key="item.id" :label="item.displayName" :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div style="display: block; margin-top: 7px; margin-right: 110px">
        <div style="background-color: #fff; padding: 15px; border-radius: 8px">
          <div id="printTest">
            <el-table :data="tableData" row-key="id" class="el-table__body-wrapper tbody" @row-click="rowClick"
              highlight-current-row height="235px" ref="tableData">
              <el-table-column prop="id" label="编号" min-width="300" align="center">
              </el-table-column>
              <el-table-column prop="displayName" label="名称" min-width="100" align="center">
              </el-table-column>
              <el-table-column prop="poisonTypeId" label="毒害类别" min-width="100" align="center">
                <template slot-scope="scope">
                  <div>
                    {{ dddw(poisonType, "id", scope.row.poisonTypeId, "displayName") }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="creatorName" label="创建者" min-width="80" align="center">
              </el-table-column>
              <el-table-column prop="lastModifierName" label="修改者" min-width="80" align="center">
              </el-table-column>
              <!-- <el-table-column prop="simpleCode" label="简称" width="180">
        </el-table-column> -->
              <el-table-column prop="creationTime" label="创建时间" min-width="150" align="center">
                <template slot-scope="scope">
                  {{ scope.row.creationTime | dateFormat }}
                </template>
              </el-table-column>
              <el-table-column prop="lastModificationTime" label="修改时间" min-width="150" align="center">
                <template slot-scope="scope">
                  {{ scope.row.lastModificationTime | dateFormat }}
                </template>
              </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>
          <PoisonAsbitem :poisonId="curRow.id"/>
        </div>
      </div>
      <!-- 按钮区域 -->
      <div style="margin-left: 10px;margin-top: 3%;position: absolute;top: 0;right: 0;">
        <el-button type="" @click="add" class="commonbutton">新增</el-button>
        <div style="margin-top: 6px">
          <el-button type="" @click="edlits" class="commonbutton">编辑</el-button>
        </div>
        <div style="margin-top: 6px">
          <el-button type="" @click="deleteid" class="deleteButton">删除</el-button>
        </div>
        <div style="margin-top: 6px">
          <el-button type="" @click="topping" class="commonbutton">置顶</el-button>
        </div>
        <div style="margin-top: 6px">
          <el-button type="" @click="toppings" class="commonbutton">置底</el-button>
        </div>
        <div style="margin-top: 6px">
          <el-button type="" :disabled="isshow" @click="assertion" class="commonbutton">排序</el-button>
        </div>
        <div style="margin-top: 6px">
          <el-button type="" :disabled="isshow" @click="cancellation" class="commonbutton">取消</el-button>
        </div>
      </div>
      <!-- <div class="cancelorconfirm"></div> -->
      <!-- 新增或者编辑弹框 -->

      <el-dialog :title="title == 1 ? '新增' : '修改'" :visible.sync="dialogVisible" width="75%" :append-to-body="true"
        :close-on-click-modal="false">
        <el-form ref="form" :model="form" label-width="80px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="编号">
                <el-input v-model="form.id" style="width: 65%" disabled size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="名称">
                <el-input ref="refinput" v-model="form.displayName" style="width: 65%" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="毒害类别">
                <el-select v-model="form.poisonTypeId" placeholder="请选择毒害类别" size="small">
                  <el-option v-for="item in poisonType" :key="item.id" :label="item.displayName"
                    :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-divider></el-divider>
            <el-col :span="4" style="margin-left: 15px">
              <el-form-item label="创建者">
                <el-input v-model="form.creatorName" disabled size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="创建时间">
                <el-input :value="form.creationTime | dateFormat" disabled size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="修改者">
                <el-input v-model="form.lastModifierName" disabled size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="修改时间">
                <el-input style="width: 85%" :value="form.lastModificationTime | dateFormat" disabled
                  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="primary" @click="addoredit" class="commonbutton">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import Sortable from "sortablejs";
import { mapState } from "vuex";
import {
  examinationlist,
  newphysical,
  listsid,
  Modifiers,
  deletecol,
  medicaltopbottom,
  examinationdragging,
} from "../../request/systemapi";
import { postapi } from '@/api/api';
import { deepCopy, dddw } from "../../utlis/proFunc";
import PoisonAsbitem from "../../components/occDisease/PoisonAsbitem.vue"

export default {
  components: {
    PoisonAsbitem,
  },
  data() {
    return {
      isshow: true,
      dialogVisible: false,
      title: 1,
      form: {
        displayName: "",
      },
      tableData: [],
      initTableData: [],
      curRow: {},
      department: "",
      quckDepartment: [],
      poisonType: []
    };
  },
  created() {
    this.getbaselist()
    this.getlist();
  },
  mounted() {
    this.rowDrop();
  },
  computed: {
    ...mapState(["window"]),
  },
  methods: {
    dddw,
    getbaselist() {
      postapi("/api/app/PoisonType/GetList").then((res) => {
        if (res.code != -1) {
          this.poisonType = [...res.data];
        }
      });
    },
    //点击列表通过id查询
    rowClick(row) {
      this.curRow = row;
      // listsid(row.id).then((res) => {
      //   if(res.code!=-1){
      //     this.curRow = { ...res.data };
      //   }
      //   // this.form = res.data;
      // });
    },
    remoteMethodes(keyWords) {
      if (keyWords) {
        this.quckDepartment = [];
        this.initTableData.forEach((item) => {
          if (
            item.displayName.toLowerCase().indexOf(keyWords.toLowerCase()) >
            -1 ||
            item.simpleCode.toLowerCase().indexOf(keyWords.toLowerCase()) > -1
            // || item.shortName.toLowerCase().indexOf(keyWords.toLowerCase()) > - 1
          ) {
            this.quckDepartment.push(item);
          }
        });
      } else {
        this.quckDepartment = [...this.initTableData];
      }
    },
    quckDepartments(e) {
      if (e) {
        this.tableData.forEach((item, index) => {
          if (e == item.id) {
            this.$refs["tableData"].setCurrentRow(item);
            this.rowClick(item);
            this.searchup(item, index)
          }
        });
      } else {
        this.remoteMethodes();
      }
    },
    searchup(data, index) {
      if (index == 0) {
        index = 1;
      }
      const targetTop = this.$refs["tableData"].$el.querySelectorAll('.el-table__body tr')[index - 1].getBoundingClientRect().top
      const containerTop = this.$refs["tableData"].$el.querySelector('.el-table__body').getBoundingClientRect().top
      const scrollParent = this.$refs["tableData"].$el.querySelector('.el-table__body-wrapper')
      scrollParent.scrollTop = targetTop - containerTop
    },
    cancellation() {
      this.$message.info("取消操作");
      this.isshow = true;
      this.getlist();
    },
    //确定排序
    assertion() {
      const result = [];
      this.tableData.forEach((item, index) => {
        // index 从0开始的， 你的displayOrder从大到小排
        // const currentDisplayOrder = this.tableData.length -1
        // const currentDisplayOrder = this.initTableData[index].displayOrder;
        // if (item.displayOrder != currentDisplayOrder) {
        // 如果它的displayOrder和它当前所在的位置不同代表挪动过位置
        result.push({ id: item.id, displayOrder: index + 1 });
        // }
      });
      postapi("/api/app/Poison/UpdateSortMany", { itemList: result }).then((res) => {
        if (res.code != -1) {
          this.getlist();
          this.isshow = true;
          //this.$message.success('操作成功')
        }
      });
    },
    //初始化
    rowDrop() {
      this.$nextTick(() => {
        const tbody = document.querySelector(".el-table__body-wrapper tbody");
        const _this = this;
        Sortable.create(tbody, {
          handle: ".move",
          animation: 300,
          // 指定父元素下可被拖拽的子元素
          // draggable: ".module-manager .el-table__row",
          onChoose({ oldIndex }) {
            _this.$refs['tableData'].setCurrentRow(_this.tableData[oldIndex]);
            _this.rowClick(_this.tableData[oldIndex])
          },
          onEnd({ newIndex, oldIndex }) {
            // console.log(arr);
            _this.isshow = false;
            const currRow = _this.tableData.splice(oldIndex, 1)[0];
            _this.tableData.splice(newIndex, 0, currRow);
            _this.tableData.map((item, index) => {
              if (index == newIndex && index == oldIndex) {
                // console.log(item, "新数据");
              } else if (index == oldIndex) {
              } else if (index == newIndex) {
              }
            });
          },
        });
      });
    },
    //置底置顶
    topping() {
      this.form = { ...this.curRow };
      if (this.form.id == undefined) {
        this.$message.warning("请选择操作的数据");
      } else {
        postapi("/api/app/Poison/UpdateManySort", { poisonId: this.form.id, sortType: 1 }).then((res) => {
          if (res.code != -1) {
            this.getlist();
            //this.$message.success('操作成功')
          }
        });
      }
    },
    toppings() {
      this.form = { ...this.curRow };
      if (this.form.id == undefined) {
        this.$message.warning("请选择操作的数据");
      } else {
        postapi("/api/app/Poison/UpdateManySort", { poisonId: this.form.id, sortType: 2 }).then((res) => {
          if (res.code != -1) {
            this.getlist();
            //this.$message.success('操作成功')
          }
        });
      }
    },
    //删除
    deleteid(row) {
      this.form = { ...this.curRow };
      if (this.form.id == undefined) {
        this.$message.warning("请选择删除的数据");
      } else {
        this.$confirm("是否确认删除,是否继续", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          cancelButtonClass: "difference",
          confirmButtonClass: "commonbutton"
        })
          .then(() => {
            postapi("/api/app/Poison/Delete", { poisonId: this.form.id }).then((res) => {
              if (res.code != -1) {
                this.curRow = this.$options.data().curRow
                this.getlist();
                //this.$message.success('删除成功')
              }
            });
          })
          .catch(() => { });
        // deletecol(this.form.id).then((res) => {
        //   console.log("删除成功");
        //   this.getlist();
        // });
      }
    },
    //edlits编辑弹框
    edlits(row) {
      this.form = { ...this.curRow };
      if (this.form.id == undefined) {
        this.$message.warning("请选择操作的数据");
      } else {
        this.title = 2;
        this.dialogVisible = true;
        postapi("/api/app/Poison/Get", { poisonId: this.form.id }).then((res) => {
          if (res.code != -1) {
            this.form = res.data;
          }
        });
      }
    },
    //确定新增或者修改
    addoredit() {
      if (this.form.displayName == undefined || this.form.displayName == "") {
        this.$message.warning("请输入名称");
      } else {
        if (this.title == 1) {
          postapi("/api/app/Poison/Create", { displayName: this.form.displayName, poisonTypeId: this.form.poisonTypeId }).then((res) => {
            // this.form.displayName = "";
            if (res.code != -1) {
              this.getlist();
              this.dialogVisible = false;
              //this.$message.success('新增成功')
            }
          });
        } else if (this.title == 2) {
          postapi("/api/app/Poison/Update", { poisonId: this.form.id, poisonTypeId: this.form.poisonTypeId, displayName: this.form.displayName }).then(
            (res) => {
              if (res.code != -1) {
                this.getlist();
                this.dialogVisible = false;
                //this.$message.success('修改成功')
              }
            }
          );
        }
      }
    },
    //新增弹框
    add() {
      this.dialogVisible = true;
      this.title = 1;
      this.form = this.$options.data().form
      this.$nextTick(() => {
        this.$refs.refinput.focus();
      });
    },
    //
    getlist() {
      postapi("/api/app/Poison/GetList").then((res) => {
        if (res.code != -1) {
          this.initTableData = [...res.data];
          this.tableData = res.data;
          this.quckDepartment = [...res.data]
        }
      });
    },
  },
};
</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;
}

: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;
}

.seachinput {
  width: 250px;
  margin-right: 110px;
}

:deep .seachinput .el-select {
  width: 100%;
}
</style>
