<template>
  <div>
    <div class="searchBox" ref="searchBox">
      <el-form :model="listQuery" :inline="true">
        <el-form-item label="起止时间">
          <el-date-picker
            v-model="QzrqS"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="upQzrqS"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </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
        ref="dataTreeList"
        row-key="id"
        :tree-props="{ children: 'itemList', hasChildren: true }"
        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="selection" width="40" align="center" />
        <el-table-column
          type="index"
          show-overflow-tooltip
          align="center"
          width="60px"
          label="序号"
        >
        </el-table-column>
        <el-table-column
          prop="ssbm"
          show-overflow-tooltip
          align="center"
          label="值班部门"
        >
        </el-table-column>
        <el-table-column
          prop="zbpbksrq"
          show-overflow-tooltip
          align="center"
          sortable
          label="开始日期"
        >
        </el-table-column>
        <el-table-column
          prop="zbpbjsrq"
          show-overflow-tooltip
          align="center"
          sortable
          label="结束日期"
        >
        </el-table-column>
        <el-table-column
          prop="mrbc"
          show-overflow-tooltip
          align="center"
          label="班次数量"
        >
          <template #default="{ row }">
            <el-tag
              class="mx-1"
              v-for="item in bcslOptions"
              v-show="item.value == row.mrbc"
              :key="item.value"
              >{{ item.label }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column
          prop="xhlx"
          show-overflow-tooltip
          align="center"
          label="排班类型"
        >
          <template #default="{ row }">
            <el-tag
              class="mx-1"
              v-for="item in D_BZ_PBXHLX"
              v-show="item.value == row.xhlx"
              :key="item.value"
              >{{ item.label }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template #default="{ row }">
            <el-button @click="showInfo(row.id)" size="small">详情</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 size="small" @click="close">关闭</el-button>
        </div>
      </div>
      <el-form
        ref="elform"
        :model="formData"
        :rules="rules"
        :inline="true"
        label-position="top"
      >
        <el-form-item label="值班部门">
          <el-cascader
            style="width: 100%"
            ref="cascader"
            v-model="formData.ssbmdm"
            :options="depList"
            @change="handleChange"
            :props="props"
            :show-all-levels="false"
          />
        </el-form-item>
        <el-form-item prop="zbpbksrq" label="开始日期">
          <el-date-picker
            style="width: 100%"
            v-model="formData.zbpbksrq"
            placeholder="请选择"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="有无期限">
          <el-radio-group v-model="formData.jsrqlx">
            <el-radio label="0" size="large">无期限</el-radio>
            <el-radio label="1" size="large">有期限</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="zbpbjsrq" label="结束日期">
          <el-date-picker
            style="width: 100%"
            v-model="formData.zbpbjsrq"
            placeholder="请选择"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled="formData.jsrqlx == '0'"
          />
        </el-form-item>
        <el-form-item style="width: 48%" label="循环周期">
          <el-radio-group v-model="formData.xhzq" @change="chooceDay">
            <el-radio :label="1">1天</el-radio>
            <el-radio :label="2">2天</el-radio>
            <el-radio :label="3">3天</el-radio>
            <el-radio :label="7">一周</el-radio>
            <el-radio :label="0">自定义</el-radio>
            <el-input-number
              v-model="dayCount"
              :min="1"
              @change="handleCOuntDay"
              :max="10"
              :disabled="formData.xhzq != 0"
            />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="每日班次数量">
          <el-select
            v-model="formData.mrbc"
            placeholder="请选择"
            @change="chooseBc"
          >
            <el-option
              v-for="item in bcslOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排班类型">
          <el-select v-model="formData.xhlx" placeholder="请选择">
            <el-option
              v-for="item in D_BZ_PBXHLX"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-row v-for="(item, index) in list.zbList" :key="index">
          <div class="jgtitle">
            <div class="title">第{{ index + 1 }}天</div>
          </div>
          <el-row v-for="(v, i) in item.mrbclist" :key="i" class="zbbcList">
            <el-form-item label="值班领导">
              <el-input
                clearable
                @click="handleChoose(index, i, 'zzld')"
                style="width: 100%"
                v-model="v.zbld"
                placeholder="请选择"
              ></el-input>
            </el-form-item>
            <el-form-item prop="zbzhzXm" label="值班指挥长">
              <el-input
                clearable
                @click="handleChoose(index, i, 'zhz')"
                style="width: 100%"
                v-model="v.zbzhzXm"
                placeholder="请选择"
              ></el-input>
            </el-form-item>
            <el-form-item prop="zzzhzXm" label="专职指挥长">
              <el-input
                clearable
                style="width: 100%"
                v-model="v.zzzhzXm"
                @click="handleChoose(index, i, 'zzzhz')"
                placeholder="请选择"
              ></el-input>
            </el-form-item>
            <el-form-item prop="fzzbXm" label="法制值班">
              <el-input
                clearable
                style="width: 100%"
                v-model="v.fzzbXm"
                @click="handleChoose(index, i, 'fzzb')"
                placeholder="请选择"
              ></el-input>
            </el-form-item>
            <el-form-item prop="zbdh" label="值班电话">
              <el-input
                style="width: 100%"
                v-model="v.zbdh"
                placeholder="请填写值班电话"
              ></el-input>
            </el-form-item>
            <el-form-item prop="hh" label="呼号">
              <el-input
                style="width: 100%"
                v-model="v.hh"
                placeholder="请填写呼号"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="值班民警"
              @click.stop="choosePolice('MJ', index, i)"
            >
              <div class="ipt">
                <el-tag
                  v-for="tag in v.mjList"
                  :key="tag.id"
                  class="mx-1"
                  closable
                  :type="tag.type"
                  @close="handleClose(tag, 'mj', index, i)"
                >
                  {{ tag.jlxm }}
                </el-tag>
              </div>
            </el-form-item>
            <el-form-item
              label="值班辅警"
              @click.stop="choosePolice('FJ', index, i)"
            >
              <div class="ipt">
                <el-tag
                  v-for="tag in v.fjList"
                  :key="tag.id"
                  class="mx-1"
                  closable
                  :type="tag.type"
                  @close="handleClose(tag, 'fj', index, i)"
                >
                  {{ tag.jlxm }}
                </el-tag>
              </div>
            </el-form-item>
            <el-form-item style="width: 100%" prop="qwbcid" label="值班班次">
              <el-radio-group v-model="v.qwbcid" @change="setQwbc(v)">
                <el-radio
                  v-for="item in qwbaDataList"
                  :key="item.id"
                  :label="item.id"
                >
                  <div class="tags" :style="{ borderColor: item.bcys }">
                    <span>{{ setHm(item.kssj) }}-{{ setHm(item.jssj) }}</span>
                    <span>{{ item.bcmc }}</span>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="kssj" label="开始时间">
              <el-time-picker
                readonly
                style="width: 100%"
                v-model="v.kssj"
                format="HH时mm分"
                value-format="HH:mm:00"
                placeholder="请选择开始时间"
              />
            </el-form-item>
            <el-form-item prop="jssj" label="结束时间">
              <el-time-picker
                readonly
                style="width: 100%"
                format="HH时mm分"
                value-format="HH:mm:00"
                v-model="v.jssj"
                placeholder="请选择结束时间"
              />
            </el-form-item>
            <el-form-item prop="zbsc" label="值班时长">
              <el-input
                class="min"
                readonly
                v-model="v.zbsc"
                style="width: 100%"
              />
            </el-form-item>
            <div class="zblistLine"></div>
          </el-row>
        </el-row>

        <el-form-item label="备注" style="width: 100%">
          <el-input
            v-model="formData.bz"
            placeholder="请输入关键字"
            show-word-limit
            type="textarea"
        /></el-form-item>
      </el-form>
    </div>
    <ChooseUser
      v-model="chooseUserVisible"
      @choosedUsers="hanlderChoose"
    ></ChooseUser>
    <ChooseUser
      v-model="chooseUserVisibleZz"
      @choosedUsers="hanlderChooseZz"
    ></ChooseUser>
    <ChooseUser
      v-model="chooseUserVisibleFz"
      @choosedUsers="hanlderChooseFz"
    ></ChooseUser>
    <ChooseUser
      v-model="chooseUserVisibleZh"
      @choosedUsers="hanlderChooseZh"
    ></ChooseUser>
    <!-- 民警 -->
    <ChooseUser
      v-model="mjLoad"
      @choosedUsers="hanlderChooseMJLOAD"
    ></ChooseUser>
    <!-- 辅警 -->
    <ChoosePolice
      v-model="choosePoliceVisible"
      :PoliceType="PoliceType"
      @choosedPolice="choosedPolice"
    >
    </ChoosePolice>
  </div>
</template>

<script setup>
import * as MOSTY from "@/components/MyComponents/index";
import ChooseUser from "@/components/MyComponents/ChooseUser";
import ChoosePolice from "@/components/MyComponents/choosePolice";
import { selectDeptPage } from "@/api/user-manage";
import { getItem } from "@/utils/storage";
import { getQwbc } from "@/api/service/shift.js";
import { getQwZbByUser, zbPbDetail } from "@/api/service/shifTscheduling.js";
import {
  ref,
  reactive,
  onMounted,
  onUnmounted,
  getCurrentInstance,
  onBeforeMount,
  nextTick
} from "vue";
const { proxy } = getCurrentInstance();
const {D_BZ_PBXHLX} = proxy.$dict('D_BZ_PBXHLX')
const searchBox = ref(null); // 搜索盒子
const tableHeight = ref(); // 表格高度
const weekList = ref([]); //周下拉数据
const weekListend = ref([]); //周下拉数据
const QzrqS = ref([]);
const mjLoad = ref(false); //民警弹窗
const tableData = ref([]); //表格数据
const cascader = ref(null);
const chooseUserVisible = ref(false);
const chooseUserVisibleFz = ref(false);
const chooseUserVisibleZh = ref(false);
const chooseUserVisibleZz = ref(false);
const Qzrq = ref([]);
const chackipt = ref(true);
const depList = ref([]); //部门数据
const loadingtable = ref(false);
const formData = ref({
  jsrqlx: "0",
  mrbc: 1,
  xhzq: 1
}); //多单数据表单
//班次数量
const bcslOptions = ref([
  {
    value: 1,
    label: "一班"
  },
  {
    value: 2,
    label: "二班"
  },
  {
    value: 3,
    label: "三班"
  }
]); // 每日班次
//级联选择器配置
const props = {
  expandTrigger: "children",
  children: "childDeptList",
  label: "orgName",
  value: "id",
  checkStrictly: true,
  emitPath: false
};
const choosePoliceVisible = ref(false); //民警辅警弹窗
const PoliceType = ref(""); //民警辅警弹窗
const fjText = ref("");
const mjList = ref([]);
const fjList = ref([]);

const btnLoading = ref(false); //按钮截流
const keyCount = ref(0); //tabel组件刷新值
const title = ref("值班排班新增");
const elform = ref(null);
const total = ref(0);

const qwbaDataList = ref([]);

const dialogFormVisible = ref(false); //弹窗
//搜索数据
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 10
});
function upQzrq() {
  form.value.ksrq = Qzrq.value[0];
  form.value.jsrq = Qzrq.value[1];
}
//表单数据
const form = ref({});
//表单验证
const rules = ref({
  zbld: [
    {
      required: true,
      message: "请选择负责人",
      trigger: "change"
    }
  ],
  ssbmdm: [
    {
      required: true,
      message: "请选择值班部门",
      trigger: "change"
    }
  ]
});
function upQzrqS() {
  if (QzrqS.value.length == 2) {
    listQuery.value.zbpbksrq = QzrqS.value[0];
    listQuery.value.zbpbjsrq = QzrqS.value[1];
  }
}
//查询条件选择部门
function handleChange(e) {
  let data = cascader.value.getCheckedNodes();
  formData.value.ssbm = data[0].label
}
function setQwbc() {
  qwbaDataList.value.forEach((v) => {
    if (v.id == form.value.qwbcid) {
      form.value.kssj = v.kssj;
      form.value.jssj = v.jssj;
      form.value.qwbcid = v.id;
      form.value.zbsc = v.zbsc;
    }
  });
}
function getQwbcData() {
  let params = {
    pageCurrent: 1,
    pageSize: 1000,
    bclx: "01"
  };
  getQwbc(params).then((res) => {
    qwbaDataList.value = res.records.map((item) => {
      return {
        bcys: item.bcys,
        kssj: item.kssj,
        jssj: item.jssj,
        id: item.id,
        zbsc: item.zqsc,
        bcmc: item.bcmc
      };
    });
  });
}
//计算执勤时长
function setZbsc() {
  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;
    } else {
      end.setDate(end.getDate() + 1);
      time = parseInt(end - start) / 1000 / 60;
    }
    form.value.zbsc = time;
  }
}
//搜索
function handleFilter() {
  listQuery.value.pageCurrent = 1;
  listQuery.value.pageSize = 20;
  getListData();
}
//重置
function reset() {
  QzrqS.value = [];
  listQuery.value = {
    pageCurrent: 1,
    pageSize: 20
  };
  getListData();
}
//新增表单重置
function resetForm() {
  form.value = {};
  mjList.value = [];
  fjList.value = [];
}
// 去重
function uprequrie (arr,type){
  let obj={}
  let mewArr = arr.reduce((item,next)=>{
    obj[next.zbzq]?'':obj[next.zbzq] = true && item.push(next)
    return item
  },[])
  return mewArr
}
let dataCopy = ref({
  zbld: "",
  zbzhzXm: "",
  zzzhzXm: "",
  fzzbXm: "",
  zbdh: "",
  hh: "",
  qwbcid: "",
  kssj: "",
  jssj: "",
  zbsc: "",
  mjList: [],
  fjList: []
});
const list = reactive({
  zbList: [
    {
      mrbclist: [dataCopy.value]
    }
  ]
});
//修改
function showInfo(id) {
  resetForm();
  title.value = "值班排班详情";
  // chackipt.value = true;
  zbPbDetail(id).then((res) => {
    dialogFormVisible.value =true
    formData.value.ssbmdm = parseInt(res.ssbmdm)
    formData.value.ssbm = res.ssbm
    formData.value.id = res.id
    formData.value.xhlx = res.xhlx
    formData.value.xhzq = res.xhzq
    formData.value.zbpbksrq = res.zbpbksrq
    formData.value.zbpbjsrq = res.zbpbjsrq
    formData.value.jsrqlx = res.jsrqlx
    formData.value.bz = res.bz
    formData.value.mrbc = res.mrbc
    let list1 = []
    let arr = []
    arr = uprequrie(res.pbzqList)
    arr.forEach((item,index)=>{
      let obj1 = {
        mrbclist:[]
      }
      res.pbzqList.forEach((v,t)=>{
        if(item.zbzq == v.zbzq){
          let mjList1 = []
          let fjlist1 = []
          item.jlList.forEach(c=>{
              if(c.jllx == '01'){
                mjList1.push(c)
              }
              if(c.jllx == '02'){
                fjlist1.push(c)
              }
          })
          v.mjList = mjList1
          v.fjList = fjlist1
          obj1.mrbclist.push(v)
        }
      })
      list1.push(obj1)
    })
    list.zbList = list1
  });
}
function handleClose(tag, type) {
  if (type == "mj") {
    mjList.value.splice(mjList.value.indexOf(tag), 1);
  }
  if (type == "fj") {
    fjList.value.splice(fjList.value.indexOf(tag), 1);
  }
}
//获取列表数据
function getListData() {
  loadingtable.value = true;
  getQwZbByUser(listQuery.value).then((res) => {
    loadingtable.value = false;
    tableData.value = res.records;
    total.value = res.total;
  }).catch(()=>{
    loadingtable.value = false;
  });;
}
//选择用户
const hanlderChoose = (users) => {
  const user = users[0];
  form.value.zbld = user.userName;
  form.value.zbldId = user.id;
  form.value.zbdh = user.mobile;
};
//选择值班指挥长
const hanlderChooseZh = (users) => {
  const user = users[0];
  form.value.zbzhzXm = user.userName;
  form.value.zbzhzId = user.id;
};
//选择专职指挥长
const hanlderChooseZz = (users) => {
  const user = users[0];
  form.value.zzzhzXm = user.userName;
  form.value.zzzhzId = user.id;
};
//选择法制值班
const hanlderChooseFz = (users) => {
  const user = users[0];
  form.value.fzzbXm = user.userName;
  form.value.fzzbId = user.id;
};
// 选择辅警
function choosedPolice(police) {
  if (police.type == "FJ") {
    fjList.value = police.userList.map((item) => {
      fjText.value += item.xm + ";";
      return {
        jlId: item.id,
        jllx: "02",
        jlxm: item.xm,
        sfzh: item.sfzh,
        xbdm: item.xbdm,
        lxdh: item.lxdh
      };
    });
  }
}
function hanlderChooseMJLOAD(users) {
  mjList.value = users.map((item) => {
    return {
      jlId: item.id,
      jllx: "01",
      jlxm: item.userName,
      sfzh: item.idEntityCard,
      xbdm: item.sex,
      lxdh: item.mobile
    };
  });
}
//关闭弹窗
function close() {
  dialogFormVisible.value = false;
  resetForm();
}
/**
 * pageSize 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getListData();
};

//选则民警、辅警
function choosePolice(type) {
  if (type == "MJ") {
    mjLoad.value = true;
  } else {
    PoliceType.value = type;
    choosePoliceVisible.value = true;
  }
}
/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getListData();
};
// 表格高度计算
const tabHeightFn = () => {
 tableHeight.value = window.innerHeight - searchBox.value.offsetHeight - 240;
};
// 时分秒截取
function setHm(item) {
  return item.split(":")[0] + ":" + item.split(":")[1];
}
onMounted(() => {
  getQwbcData();
  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: "分钟";
}
.chooce-bc {
  width: 100%;
  min-height: 300px;
  border: 1px solid #03438b;
  padding: 4px 8px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .chooce-bc-top {
    height: 150px;
    .bc-title {
      width: 100%;
      height: 30px;
      font-size: 14px;
      color: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .colose {
        cursor: pointer;
      }
    }
  }
  .choose-bc-line {
    width: 100%;
    height: 1px;
    background: #6d6f73;
  }
  .choose-bc-bottom {
    height: 150px;
    .bc-title {
      width: 100%;
      height: 30px;
      font-size: 14px;
      color: #fff;
    }
  }
  .chooce-bc-btn-box {
    height: 118px;
    overflow: hidden;
    overflow-y: auto;
    .chooce-bc-btn-item {
      border: 2px solid;
      float: left;
      cursor: pointer;
      margin-right: 7px;
      margin-bottom: 4px;
      line-height: 12px;
      text-align: center;
      font-size: 12px;
      padding: 4px;
      border-radius: 10px;
      .item {
        line-height: 14px;
      }
    }
  }
}
.tags {
  padding: 4px 12px;
  border-radius: 4px;
  color: #fff;
  border: 2px solid;
  display: flex;
  flex-direction: column-reverse;
  align-content: center;
  align-items: center;
  > span {
    line-height: 1em;
    font-size: 12px;
  }
}
.ipt {
  border: 1px solid rgb(7, 85, 188);
  width: 100%;
  line-height: 32px;
  min-height: 32px;
  border-radius: 4px;
}
.min {
  position: relative;
}
.min::after {
  position: absolute;
  top: 0;
  right: 12px;
  bottom: 0;
  content: "分钟";
}
</style>
