<template>
  <div>
    <div class="titleBox">
      <div class="title">勤务班次</div>
      <div class="btnBox">
        <el-button type="primary" @click="add">
          <el-icon style="vertical-align: middle">
            <CirclePlus />
          </el-icon>
          <span style="vertical-align: middle">新增</span>
        </el-button>
      </div>
    </div>
    <div class="searchBox" ref="searchBox">
      <el-form :model="listQuery" :inline="true">
       <el-form-item label="所属部门">
          <MOSTY.Department
            width="100%"
            clearable
            v-model="listQuery.ssbmdm"
          />
        </el-form-item>
        <el-form-item label="班次名称">
          <el-input
            v-model="listQuery.bcmc"
            placeholder="请输入班次名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="排班级别">
          <el-select v-model="listQuery.pbjb" placeholder="请选择排班级别">
            <el-option
              v-for="dict in D_BZ_PBJB"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排班类型">
          <el-select placeholder="请选择排班类型" v-model="listQuery.bclx">
            <el-option
              v-for="dict in D_BZ_PBLX"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleFilter"> 查询 </el-button>
          <el-button @click="reset()"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tabBox">
      <el-table
        :data="tableData"
        border
        row-key="id"
        style="width: 100%"
        :key="keyCount"
        :height="tableHeight"
        v-loading="loadingTable"
        element-loading-background="rgba(0,0,0,0.3)"
        element-loading-text="数据加载中。。"
      >
        <el-table-column
          type="index"
          show-overflow-tooltip
          align="center"
          width="60px"
          label="序号"
        >
        </el-table-column>
        <el-table-column
          prop="bcmc"
          show-overflow-tooltip
          align="center"
          label="班次名称"
        >
        </el-table-column>
        <el-table-column
          prop="ssbm"
          show-overflow-tooltip
          align="center"
          label="所属部门"
          width="320"
        >
        </el-table-column>
        <el-table-column
          prop="pbjb"
          show-overflow-tooltip
          align="center"
          label="排班级别"
        >
          <template #default="{ row }">
            <dict-tag :options="D_BZ_PBJB" :value="row.pbjb" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column
          prop="bclx"
          show-overflow-tooltip
          align="center"
          label="排班类型"
        >
          <template #default="{ row }">
            <dict-tag :options="D_BZ_PBLX" :value="row.bclx" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column
          prop="kssj"
          show-overflow-tooltip
          align="center"
          label="开始时间"
        >
        </el-table-column>
        <el-table-column
          prop="jssj"
          show-overflow-tooltip
          align="center"
          label="结束时间"
        >
        </el-table-column>
        <el-table-column
          prop="zqsc"
          show-overflow-tooltip
          align="center"
          label="值班时长"
        >
          <template #default="{ row }">
            <span>{{ row.zqsc + "分钟" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="160"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button @click="update(row)" size="small">修改</el-button>
            <el-button type="danger" size="small" @click="delDictItem(row)"
              >注销</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="fenye" :style="{ top: tableHeight + 'px' }">
        <el-pagination
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.pageCurrent"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <div v-if="dialogFormVisible" class="dialog">
      <div class="head_box">
        <span class="title">{{ title }}</span>
        <div>
          <el-button
            type="primary"
            size="small"
            @click="submit"
            :loading="btnLoading"
            >保存</el-button
          >
          <el-button size="small" @click="close">关闭</el-button>
        </div>
      </div>
      <el-form
        ref="elform"
        :model="form"
        :rules="rules"
        :inline="true"
        label-position="top"
      >
        <el-form-item label="所属部门" prop="ssbmdm">
          <MOSTY.Department
            width="100%"
            :placeholder="form.ssbm"
            clearable
            v-model="form.ssbmdm"
          />
        </el-form-item>

        <el-form-item prop="bclx" label="排班类型">
          <el-select v-model="form.bclx" readonly>
            <el-option
              v-for="dict in D_BZ_PBLX"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="bcmc" label="班次名称">
          <el-input
            v-model="form.bcmc"
            placeholder="请输入班次名称"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item prop="kssj" label="开始时间">
          <el-time-picker
            style="width: 100%"
            @change="setZqsc"
            v-model="form.kssj"
            format="HH时mm分"
            value-format="HH:mm:00"
            placeholder="请选择开始时间"
          />
        </el-form-item>
        <el-form-item prop="jssj" label="结束时间">
          <el-time-picker
            style="width: 100%"
            @change="setZqsc"
            format="HH时mm分"
            value-format="HH:mm:00"
            v-model="form.jssj"
            placeholder="请选择结束时间"
          />
        </el-form-item>
        <el-form-item prop="zqsc" label="执勤时长">
          <el-input
            class="min"
            readonly
            v-model="form.zqsc"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item prop="pbjb" label="排班级别">
          <el-select
            v-model="form.pbjb"
            @change="pbjbChange"
            placeholder="请选择排班级别"
          >
            <el-option
              v-for="dict in D_BZ_PBJB"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用部门" prop="ssbmdm" v-if="form.pbjb == '03'">
          <el-cascader
            style="width: 100%"
            ref="cascader"
            v-model="form.ssbmdm"
            :options="depList"
            @change="handleChange"
            :props="props"
            :show-all-levels="false"
          />
        </el-form-item>
        <el-form-item prop="bcys" label="字体颜色">
          <el-color-picker v-model="form.bcys" />
        </el-form-item>
        <el-form-item label="备注" style="width: 100%">
          <el-input
            v-model="form.bz"
            placeholder="请输入关键字"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  onUnmounted,
  getCurrentInstance,
  watch
} from "vue";
import {
  getQwbc,
  addQwbc,
  deleteQwbc,
  getQwbcInfo,
  updateQwbc
} from "@/api/service/shift.js";
import { selectDeptPage } from "@/api/user-manage";
import * as MOSTY from "@/components/MyComponents/index";
import { dateFormat } from "@/utils/auth";
const { proxy } = getCurrentInstance();
const { D_BZ_PBJB, D_BZ_PBLX } = proxy.$dict("D_BZ_PBJB", "D_BZ_PBLX");
const searchBox = ref(null); // 搜索盒子
const tableHeight = ref(); // 表格高度
const chackAdd = ref(false);
const tableData = ref([]); //表格数据
const loadingTable = ref(true);
const btnLoading = ref(false); //按钮截流
const keyCount = ref(0); //tabel组件刷新值
const title = ref("新增班次");
const elform = ref(null);
const total = ref(0);
const dialogFormVisible = ref(false); //弹窗
const depList = ref([]); //部门数据
const cascader = ref("");
//搜索数据
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20
});
//表单数据
const form = ref({
  bcys: "#FFFFFF",
  bclx: "02",
  ssbmdm:''
});
const department =
  window.localStorage.getItem("deptId") &&
  JSON.parse(window.localStorage.getItem("deptId"))[0];
function pbjbChange(val) {
  if (val == "03") {
    form.value.ssbmdm = department.deptId;
    form.value.ssbm = department.deptName;
  }
}
//级联选择器配置
const props = {
  expandTrigger: "children",
  children: "childDeptList",
  label: "orgName",
  value: "id",
  checkStrictly: true,
  emitPath: false
};
//查询条件选择部门
function handleChange(e) {
  let data = cascader.value.getCheckedNodes();
  form.value.ssbm = data[0].label;
}
//表单验证
const rules = reactive({
  bcmc: [
    {
      required: true,
      message: "请输班次名称",
      trigger: "change"
    }
  ],
  kssj: [
    {
      required: true,
      message: "请选择开始时间",
      trigger: "blur"
    }
  ],
  jssj: [
    {
      required: true,
      message: "请选择结束时间",
      trigger: "blur"
    }
  ],
  pbjb: [
    {
      required: true,
      message: "请选择排班级别",
      trigger: "change"
    }
  ],
  bclx: [
    {
      required: true,
      message: "请选择排班类型",
      trigger: "change"
    }
  ],
  ssbmdm: [
    {
      required: true,
      message: "请选择所属部门",
      trigger: "change"
    }
  ],
  zqsc: [{ validator: checkZqsc, trigger: "change" }]
});

//执勤时长验证
function checkZqsc(rule, value, callback) {
  if (value <= 0) {
    return callback(new Error("请选择正确的时间范围"));
  } else {
    callback();
  }
}
//搜索
function handleFilter() {
  getListData();
}
//计算执勤时长
function setZqsc() {
  if (form.value.jssj && form.value.kssj) {
    let end = new Date();
    end.setHours(form.value.jssj.split(":")[0]);
    end.setMinutes(form.value.jssj.split(":")[1]);
    let start = new Date();
    start.setHours(form.value.kssj.split(":")[0]);
    start.setMinutes(form.value.kssj.split(":")[1]);
    let time;
    if (end >= start) {
      time = parseInt(end - start) / 1000 / 60;
      form.value.kts = 0;
    } else {
      end.setDate(end.getDate() + 1);
      time = parseInt(end - start) / 1000 / 60;
      form.value.kts = 1;
    }
    form.value.zqsc = time >> 0;
  }
}
//重置
function reset() {
  listQuery.value = {
    pageCurrent: 1,
    pageSize: 20
  };
  getListData();
}
//新增表单重置
function resetForm() {
  form.value = {
    bcys: "#FFFFFF",
    bclx: "02"
  };
}
//新增
function add() {
  chackAdd.value = true;
  resetForm();
  title.value = "新增班次";
  dialogFormVisible.value = true;
}
//修改
function update(row) {
  getQwbcInfo(row.id).then((res) => {
    resetForm();
    form.value = res;
    if (res.pbjb == "03") {
      form.value.ssbmdm = parseInt(res.ssbmdm);
      form.value.ssbm = res.ssbm;
    }
    chackAdd.value = false;
    title.value = "修改班次";
    dialogFormVisible.value = true;
  });
}
//注销
function delDictItem(row) {
  proxy
    .$confirm("确定删除该班次？", "警告", { type: "warning" })
    .then(() => {
      deleteQwbc(row.id).then(() => {
        proxy.$message({
          type: "success",
          message: "删除成功"
        });
        getListData();
      });
    })
    .catch(() => {
      proxy.$message.info("已取消");
    });
}
//获取列表数据
function getListData() {
  loadingTable.value = true;
  getQwbc(listQuery.value).then((res) => {
    tableData.value = res.records;
    total.value = res.total;
    loadingTable.value = false;
  }).catch(()=>{
    loadingTable.value = false;
  });
}
//关闭弹窗
function close() {
  dialogFormVisible.value = false;
  // formReset();
}
//提交
function submit() {
  elform.value.validate((valid) => {
    if (valid) {
      btnLoading.value = true;
      setTimeout(() => {
        btnLoading.value = false;
      }, 1500);
      if (chackAdd.value) {
        addQwbc(form.value).then((res) => {
          proxy.$message({
            type: "success",
            message: "新增成功"
          });
          dialogFormVisible.value = false;
          getListData();
        });
      } else {
        updateQwbc(form.value).then(() => {
          proxy.$message({
            type: "success",
            message: "修改成功"
          });
          dialogFormVisible.value = false;
          getListData();
        });
      }
    }
  });
}
/**
 * pageSize 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getListData();
};
// 表格高度计算
const tabHeightFn = () => {
 tableHeight.value = window.innerHeight - searchBox.value.offsetHeight - 240;
};
onMounted(() => {
  getListData();
  selectDeptPage({}).then((res) => {
    depList.value = res.records;
  }); //查询部门
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
  tabHeightFn();
  window.onresize = function () {
    tabHeightFn();
  };
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
});
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";
.min {
  position: relative;
}
.min::after {
  position: absolute;
  top: 0;
  right: 12px;
  bottom: 0;
  content: "分钟";
}
</style>
