<template>
  <div>
    <div>
      <div class="contenttitle">
        基础资料 /<span class="contenttitleBold">分诊叫号房间设置</span>
      </div>
      <!--分组信息-->
      <div style="display: flex; font-size: 14px">
        <div :style="'display: block;width:' + (window.pageWidth - window.pageMarginWidth - 110 - 5) + 'px;'">
          <div style="display: flex">
            <div>
              <span>体检中心：</span>
              <el-select v-model="medicalCenterId" placeholder="请选择体检中心" default-first-option clearable filterable
                style="margin-left: 10px" @change="changeMedicalCenter" size="small">
                <el-option v-for="item in dict.medicalCenter" :key="item.id" :label="item.displayName" :value="item.id">
                  {{ item.displayName }}
                </el-option>
              </el-select>
            </div>
          </div>
          <div>
            <el-table :data="tableData" ref="tableData" style="margin-top: 2px" row-key="id" border height="240px"
              size="small" highlight-current-row :row-class-name="handleRowClassName" @row-click="rowClick">
              <el-table-column type="index" label="序号" width="50" align="center" />
              <el-table-column label="id" prop="id" min-width="200" align="center" />
              <el-table-column label="房间号" prop="roomNo" min-width="60" align="center" />              
              <el-table-column prop="displayName" label="名称" min-width="150" />
              <el-table-column prop="medicalCenterId" label="体检中心" min-width="150">
                <template slot-scope="scope">
                  {{ dddw(dict.medicalCenter, "id", scope.row.medicalCenterId, "displayName") }}
                </template>
              </el-table-column>
              <el-table-column prop="itemTypeId" label="项目类别" min-width="80">
                <template slot-scope="scope">
                  {{ dddw(dict.itemTypeTree, "id", scope.row.itemTypeId, "displayName") }}
                </template>
              </el-table-column>
              <el-table-column prop="forSexId" label="适用性别" min-width="80" align="center">
                <template slot-scope="scope">
                  {{ dddw(dict.forSex, "id", scope.row.forSexId, "displayName") }}
                </template>
              </el-table-column>
              <el-table-column prop="roomTypeFlag" label="房间类别" min-width="80" align="center">
                <template slot-scope="scope">
                  {{ dddw(dict.roomType, "id", scope.row.roomTypeFlag, "displayName") }}
                </template>
              </el-table-column>
              <el-table-column prop="queueTime" label="候诊时间" min-width="80" align="center" >
                <template slot-scope="scope">
                  <div>{{ scope.row.queueTime}} 分钟</div>
                </template>
              </el-table-column>
              <el-table-column prop="isActive" label="启用" min-width="40" align="center">
                <template slot-scope="scope">
                  <div style="font-family: 'Microsoft YaHei';">{{ scope.row.isActive == 'Y' ? '√' : '' }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="creatorName" label="创建者" min-width="60" align="center" />
              <el-table-column label="创建时间" min-width="150" align="center">
                <template slot-scope="scope">
                  {{ scope.row.creationTime ? moment(scope.row.creationTime).format("yyyy-MM-DD HH:mm:ss") : "" }}
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="40" 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="display: block; margin-left: 5px">
          <div v-show="checkPagePriv(pagePriv.privs, '新增')" style="margin-top: 45px">
            <el-button class="commonbutton" @click="btnAdd('')">新增</el-button>
          </div>
          <div v-show="checkPagePriv(pagePriv.privs, '编辑')" style="margin-top: 5px">
            <el-button class="commonbutton" @click="btnEdit">编辑</el-button>
          </div>
          <div v-show="checkPagePriv(pagePriv.privs, '删除')" style="margin-top: 5px">
            <el-button class="deleteButton" @click="btnDel">删除</el-button>
          </div>
          <div v-show="checkPagePriv(pagePriv.privs, '置顶')" style="margin-top: 5px">
            <el-button class="commonbutton" @click="btnSetBottomOrTop(1)">置顶</el-button>
          </div>
          <div v-show="checkPagePriv(pagePriv.privs, '置底')" style="margin-top: 5px">
            <el-button class="commonbutton" @click="btnSetBottomOrTop(2)">置底</el-button>
          </div>
          <div v-show="checkPagePriv(pagePriv.privs, '保存排序')" style="margin-top: 5px">
            <el-button class="commonbutton" @click="btnSort" :disabled="!isDrag">保存排序</el-button>
          </div>
        </div>
      </div>

      <!--分组项目信息 -->
      <div>
        <RoomAsbitem :room="curRoom" />
      </div>
    </div>

    <!-- 新增或者编辑弹框 -->
    <el-dialog :title="dataTransOpts.tableS.room.id ? '编辑' : '新增'" :close-on-click-modal="false"
      :visible.sync="dialogWin.RoomEdit" width="800px" @close="close_dialogWinRoomEdit">
      <RoomEdit :params="RoomEditParams" />
    </el-dialog>
    <!--  -->
  </div>
</template>
<script>
import moment from "moment";
import Sortable from "sortablejs";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { mapState } from "vuex";
import {
  getPagePriv,
  checkPagePriv,
  dddw,
  deepCopy,
  objCopy,
  arrayExistObj,
  tcdate,
} from "../../utlis/proFunc";

import RoomAsbitem from "./RoomAsbitem.vue";
import RoomEdit from "./RoomEdit.vue";

export default {
  components: {
    RoomAsbitem, RoomEdit
  },
  data() {
    return {
      pagePriv: {
        routeUrlorPageName: "customerOrgGroup", //当前页面归属路由或归属页面权限名称
        privs: [], // 页面权限
      },

      tableData: [], //体检单位分组
      curRoom: {}, // 当前选中房间
      RoomEditParams: {}, //房间 新增时 用到参数 
      medicalCenterId: "", // 体检中心

      isDrag: false,
      form: {
        id: "",
        displayName: "",
        itemTypeId: "",
        medicalCenterId: "",
        forSexId: "A",
        roomTypeFlag: "0",
        queueTime: 0,
        isActive: "Y"
      },
      formInit: {}, //表单初始值
    };
  },
  computed: {
    ...mapState(["personnelUnit", "window", "dict", "dialogWin", "dataTransOpts"]),
  },
  created() {
    //获取用户当前页面的权限
    let userPriv = window.sessionStorage.getItem("userPriv");
    if (userPriv)
      this.pagePriv.privs = deepCopy(getPagePriv(this.pagePriv.routeUrlorPageName));

    // 清除当前选中的分组ID
    this.dataTransOpts.tableS.customer_org_group.id = ''

    this.rowDrop();
    this.formInit = deepCopy(this.form);
  },
  mounted() {
    //获取初始数据（单位、适用性别）
    this.dictInit();

    this.getRoom()
  },
  methods: {
    moment,
    checkPagePriv,
    dddw,
    deepCopy,
    //刷新分组价格（供子组件调用）
    refreshMoney(formData) {
      //console.log('this is parent')
      let lfind = arrayExistObj(this.tableData, "id", formData.id);
      if (lfind > -1) this.tableData[lfind].price = formData.price;
    },

    //确定排序
    btnSort() {
      const result = [];
      this.tableData.forEach((item, index) => {
        result.push({ id: item.id, displayOrder: index });
      });
      postapi("/api/app/Room/updatesortmany", {
        itemList: result,
      }).then((res) => {
        console.log("操作成功");
        this.isDrag = false;
      });
    },

    //初始化Sortable组件
    rowDrop() {

      this.$nextTick(() => {
        const el = document.querySelector(".el-table__body-wrapper tbody");
        //console.log('el0',el)
        const that = this;
        Sortable.create(el, {
          handle: ".move",
          animation: 300,
          //拖拽结束
          onEnd({ newIndex, oldIndex }) {
            that.isDrag = true;
            const currRow = that.tableData.splice(oldIndex, 1)[0];
            that.tableData.splice(newIndex, 0, currRow);
            console.log("el", el);
          },
        });
      });
    },

    // 置底 或 置顶
    btnSetBottomOrTop(sortType) {
      if (!this.dataTransOpts.tableS.room.id) {
        this.$message.warning("请选择操作的数据");
        return;
      }
      let body = {
        roomId: this.dataTransOpts.tableS.room.id,
        sortType
      }
      postapi('/api/app/Room/UpdateManySort', body)
        .then((res) => {
          if (res.code > -1) {
            console.log("操作成功");
            let lfind = arrayExistObj(this.tableData, "id", body.roomId);
            if (lfind > -1) {
              let currentRow = {};
              currentRow = this.tableData.splice(lfind, 1)[0]; //删除并赋值
              if (sortType == 2) {
                this.tableData.push(currentRow);
              } else {
                this.tableData.unshift(currentRow);
              }
              this.$refs["tableData"].setCurrentRow(currentRow);
            }
          }
        });
    },


    //选中颜色
    handleRowClassName({ row, rowIndex }) {
      // highLightBg 为 'selected'的高亮
      //console.log(rowIndex, row)
      //return row.highLightBg == 'selected' ? 'high-light-bg' : '';
      if (row.choosed) {
        return "current-row";
      } else {
        return "";
      }
    },

    //获取初始数据
    dictInit() {
      //获取体检中心
      getapi("/api/app/organization-units/by-code-all").then((res) => {
        if (res.code > -1) {
          this.dict.medicalCenter = res.data;
        }
      });

      // 项目类别 树结构
      getapi("/api/app/item-type/by-code-all").then((res) => {
        if (res.code != -1) {
          this.dict.itemTypeTree = res.data;
          tcdate(this.dict.itemTypeTree);
        }
      });

      //获取适用性别
      getapi("/api/app/for-sex").then((res) => {
        if (res.code != -1) {
          this.dict.forSex = res.data;
        }
      });

    },

    //获取房间列表   
    getRoom(medicalCenterId) {
      this.dataTransOpts.tableS.room.id = ""
      this.curRoom = {}
      this.isDrag = false;
      objCopy(this.formInit, this.form);
      this.form.medicalCenterId = medicalCenterId;
      this.tableData = [];
      postapi('/api/app/Room/GetList').then((res) => {
        if (res.code > -1) {
          this.tableData = res.data.filter(e => {
            return medicalCenterId ? (e.medicalCenterId == medicalCenterId) : e
          });
        }
      });
    },

    //选择体检中心
    changeMedicalCenter(v) {
      // console.log('changeMedicalCenter', v)
      this.getRoom(v)
    },

    //点击房间
    rowClick(row) {
      this.curRoom = row
      this.dataTransOpts.tableS.room.id = row.id
      this.dataTransOpts.refresh.room_detail.M++;
    },

    // 新增(编辑调用时，传入id值) 弹框
    btnAdd(id) {
      if (!id) this.dataTransOpts.tableS.room.id = ''

      this.dataTransOpts.refresh.room.S++
      if (!id) this.dataTransOpts.refresh.room_detail.M++; //新增则清掉已选组合项目

      this.RoomEditParams = {
        medicalCenterId: this.medicalCenterId
      }
      this.dialogWin.RoomEdit = true;
    },

    //编辑弹框
    btnEdit() {
      if (!this.dataTransOpts.tableS.room.id) {
        this.$message.warning("请先选择分诊叫号房间");
        return;
      }
      this.btnAdd(this.dataTransOpts.tableS.room.id)
    },

    //删除
    btnDel() {
      if (!this.dataTransOpts.tableS.room.id) {
        this.$message.warning("请选择需要操作的数据");
        return;
      }

      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "  否  ",
        type: "warning",
      })
        .then(() => {
          return postapi('/api/app/Room/Delete', { roomId: this.dataTransOpts.tableS.room.id });
        })
        .then((res) => {
          if (res.code != -1) {
            console.log("删除成功");
            let lfind = arrayExistObj(this.tableData, "id", this.dataTransOpts.tableS.room.id);
            if (lfind > -1) this.tableData.splice(lfind, 1);
            this.dataTransOpts.tableS.room.id = ''
            this.dataTransOpts.refresh.room_detail.M++
          }
        })
        .catch((err) => {
          if (err == "cancel") {
            console.log("已取消删除");
            // this.$message.info("已取消删除");
          }
        });
    },

    // 关闭 分组 新增/编辑
    close_dialogWinRoomEdit() {
      let id = this.dataTransOpts.tableS.room.id
      if (id) {
        // 点编辑 或 新增有提交
        postapi('/api/app/Room/Get', { roomId:id })
          .then(res => {
            if (res.code != -1) {
              let lfind = -1
              lfind = arrayExistObj(this.tableData, 'id', id)
              if (lfind > -1) {
                objCopy(res.data, this.tableData[lfind])
              } else {
                lfind = this.tableData.length
                this.tableData.push(res.data)
              }

              // 选中当前操作的列
              this.$refs["tableData"].setCurrentRow(); //清除选择
              this.$refs["tableData"].setCurrentRow(this.tableData[lfind]);

              // 更新 customer_org_group_detail 参数
              this.curRoom = deepCopy(res.data);

              this.dataTransOpts.refresh.room_detail.M++;
            }
          })
      } else {
        // 点 新增 但未提交
        this.dataTransOpts.tableS.room.id = this.curRoom.id || ''
        this.dataTransOpts.refresh.room_detail.M++;
      }

      
    },
  },
};
</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";

.btnClass {
  width: 100px;
  margin-bottom: 5px;
}
</style>
