<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 prop="qwdj" label="勤务等级">
          <el-select clearable style="width: 100%" v-model="listQuery.qwdj">
            <el-option
              v-for="dict in D_BZ_DJQW"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>   
        <el-form-item label="勤务起止时间">
          <el-date-picker
            v-model="seqwQzsj"
            unlink-panels
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
        </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="index"
          show-overflow-tooltip
          align="center"
          width="60px"
          label="序号"
        >
        </el-table-column>
        <el-table-column
          prop="qwdj"
          align="center"
          width="120"
          label="勤务等级"
        >
          <template #default="{ row }">
            <dict-tag :options="D_BZ_DJQW" :value="row.qwdj" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column
          prop="qwkssj"
          show-overflow-tooltip
          align="center"
          width="320"
          label="勤务起止时间"
        >
          <template #default="{ row }">
            <div>{{ row.qwkssj }} 至 {{ row.qwjssj }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="ssbm"
          align="center"
          show-overflow-tooltip
          label="所属部门"
        >
        </el-table-column>
        <el-table-column
          prop="jyzqrybl"
          show-overflow-tooltip
          align="center"
          label="建议执勤人员比例"
        >
          <template #default="{ row }">
            <div>{{ row.jyzqrybl }}%</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="jyzqclbl"
          show-overflow-tooltip
          align="center"
          label="建议执勤车辆比例"
        >
          <template #default="{ row }">
            <div>{{ row.jyzqclbl }}%</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="jyzqclbl"
          show-overflow-tooltip
          align="center"
          label="状态"
        >
          <template #default="{ row }">
            <span v-if="row.fbzt == 0">未发布</span>
            <span v-if="row.fbzt == 1">已发布</span>
            <span v-if="row.fbzt == 2">已结束</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          width="320px"
        >
          <template #default="{ row }">
            <el-button @click="getJlqk(row)" size="small">警力情况</el-button>
            <el-button v-if="row.fbzt == 1" @click="jsQw(row)" size="small"
              >结束勤务</el-button
            >
            <el-button
              v-if="row.fbzt == 0"
              :loading="row.btnLoading"
              @click="fabu(row)"
              size="small"
              >发布勤务</el-button
            >
            <el-button v-if="row.fbzt == 0" @click="update(row)" size="small"
              >修改</el-button
            >
            <el-button v-if="row.fbzt != 0" @click="info(row)" size="small"
              >详情</el-button
            >
            <el-button
              v-if="row.fbzt == '0'"
              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"
            :loading="btnLoading"
            v-if="bcBtn"
            @click="submit"
            >保存</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 prop="qwdj" label="勤务等级">
          <el-select
            @change="checkQwdj"
            style="width: 100%"
            v-model="form.qwdj"
          >
            <el-option
              v-for="dict in D_BZ_DJQW"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="width: 48%" prop="qwQzsj" label="勤务起止时间">
          <el-date-picker
            style="width: 100%"
            v-model="form.qwQzsj"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            unlink-panels
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item prop="ssbmdm" label="所属部门">
           <MOSTY.Department
              width="100%"
              :placeholder="form.ssbm"
              clearable
              v-model="form.ssbmdm"
            />
        </el-form-item>
        <el-form-item prop="sfxj" label="是否发送到下级">
           <el-select style="width: 100%" v-model="form.sfxj">
            <el-option
              v-for="dict in D_BZ_SF"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="jyzqrybl" label="建议执勤人员比例（%）">
          <el-input-number
            :max="100"
            :min="0"
            style="width: 100%"
            v-model="form.jyzqrybl"
            :step="1"
          />
        </el-form-item>
        <el-form-item prop="jyzqclbl" label="建议执勤车辆比例（%）">
          <el-input-number
            style="width: 100%"
            v-model="form.jyzqclbl"
            :step="1"
          />
        </el-form-item>
        <el-form-item
          class="twoh"
          style="width: 100%"
          prop="qwyy"
          label="勤务原因"
        >
          <el-input
            v-model="form.qwyy"
            placeholder="请填写勤务原因"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
        <el-form-item
          class="twoh"
          style="width: 100%"
          prop="qwyq"
          label="勤务要求"
        >
          <el-input
            v-model="form.qwyq"
            placeholder="请填写勤务要求"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
        <el-form-item style="width: 100%" label="等级勤务方案">
          <MOSTY.FileUpload
            v-model:modelValue="form.fjdz"
            :limit="3"
            :isEdit="fileEdit"
            @handleChange="changeFile"
          ></MOSTY.FileUpload>
        </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 v-if="jlqkVisible" class="dialog">
      <div class="head_box">
        <span class="title">警力情况</span>
        <div>
          <el-button size="small" @click="jlqkVisible = false">关闭</el-button>
        </div>
      </div>
      <el-table
        :data="zqjlData"
        border
        ref="dataTreeList"
        row-key="id"
        :tree-props="{ children: 'itemList', hasChildren: true }"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :height="tableHeight1"
        :key="keyCount"
        v-loading="loadingTable"
        element-loading-background="rgba(0,0,0,0.3)"
        element-loading-text="数据加载中。。"
      >
        <el-table-column
          sortable
          prop="ksrq"
          show-overflow-tooltip
          align="center"
          label="开始日期"
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="jsrq"
          show-overflow-tooltip
          align="center"
          label="结束日期"
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="jmxzs"
          label="街面巡组数"
          align="center"
        ></el-table-column>
        <el-table-column
          sortable
          prop="xfmjs"
          label="巡防民警数"
          align="center"
        ></el-table-column>
        <el-table-column
          sortable
          prop="xffjs"
          show-overflow-tooltip
          label="巡防辅警数"
          align="center"
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="xfcls"
          show-overflow-tooltip
          label="巡防车辆数"
          align="center"
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="znzbs"
          show-overflow-tooltip
          label="智能装备数"
          align="center"
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="jyqxs"
          show-overflow-tooltip
          label="警用器械数"
          align="center"
        >
        </el-table-column>
      </el-table>
      <div class="fenye" :style="{ top: tableHeight1 + 'px' }">
        <el-pagination
          class="pagination"
          @size-change="handleSizeChangezq"
          @current-change="handleCurrentChangezq"
          :current-page="listQueryzq.pageCurrent"
          :page-sizes="[10, 20, 50]"
          :page-size="listQueryzq.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalzq"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import { getRecentDay,timeValidate } from "@/utils/tools.js";
import { qcckPost, qcckGet } from "@/api/qcckApi.js";
import * as MOSTY from "@/components/MyComponents/index";
import {
  ref,
  reactive,
  onMounted,
  onUnmounted,
  getCurrentInstance,
  watch
} from "vue";
import {
  fabuzt,
  getqwdj,
  addQwdj,
  deleteQwdj,
  getQwdjInfo,
  updateQwdj
} from "@/api/service/grade.js";
import { getItem } from "@/utils/storage";
import { ElNotification } from "element-plus";
const jlqkVisible = ref(false); //警力情况弹窗
const title = ref("新增勤务等级");
const { proxy } = getCurrentInstance();
const { D_BZ_DJQW, D_BZ_ZXFW,D_BZ_SF } = proxy.$dict("D_BZ_DJQW", "D_BZ_ZXFW","D_BZ_SF");
const searchBox = ref(null); // 搜索盒子
const tableHeight = ref(); // 表格高度
const tableHeight1 = ref(); // 表格高度
const tableData = ref([]); //表格数据
const seqwQzsj = ref([]);
watch(
  () => seqwQzsj.value,
  (val) => {
    listQuery.value.qwkssj = val[0] || "";
    listQuery.value.qwjssj = val[1] || "";
  }
);
const elform = ref(null);
const chackAdd = ref(false);
const total = ref(0);
const totalzq = ref(0);
const keyCount = ref(0); //tabel组件刷新值
const btnLoading = ref(false); //按钮截流
const bcBtn = ref(true);
const fileEdit = ref(true);
const dialogFormVisible = ref(false); //弹窗
const loadingTable = ref(false);
const zqjlData = ref([
  {
    ksrq: "2022/07/22",
    jsrq: "2022/07/23",
    jmxzs: 6,
    xfmjs: 8,
    xffjs: 20,
    xfcls: 12,
    znzbs: 35,
    jyqxs: 50
  },
  {
    ksrq: "2022/07/22",
    jsrq: "2022/07/23",
    jmxzs: 6,
    xfmjs: 8,
    xffjs: 20,
    xfcls: 12,
    znzbs: 35,
    jyqxs: 50
  }
]);
//搜索数据
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20
});
const listQueryzq = ref({
  pageCurrent: 1,
  pageSize: 20
});
//表单数据
const form = ref({
  jyzqclbl: 34,
  jyzqrybl: 34,
  qwQzsj: [],
  sfxj:'0'
});
//表单验证
const rules = reactive({
  qwdj: [
    {
      required: true,
      message: "请选择勤务等级",
      trigger: "change"
    }
  ],
  qwkssj: [
    {
      required: true,
      message: "请选择勤务开始日期",
      trigger: "change"
    }
  ],
  qwjssj: [
    {
      required: true,
      message: "请选择勤务结束日期",
      trigger: "change"
    }
  ],
  ssbmdm: [
    {
      required: true,
      message: "请选择所属部门",
      trigger: "change"
    }
  ],
  qwQzsj: [
    {
      required: true,
      message: "请选择起止时间",
      trigger: "change"
    }
  ]
});
// 文件改变事件
function changeFile(data) {
  form.value.fjdz = data;
}
//搜索
function handleFilter() {
  getListData();
}
//重置
function reset() {
  seqwQzsj.value = [];
  listQuery.value = {
    pageCurrent: 1,
    pageSize: 20
  };
  getListData();
}

// 获取一周的警情数据
const getJQList = () =>{
  let params = { startTime: getRecentDay(-6)}
  qcckGet(params,'/mosty-sjzx/tbJq/getJqCount').then(res=>{
    ElNotification({
      title:'Success',
      message:`近一周的警情有${res}条数据！`,
      type:'success'
    })
  })
}

function checkQwdj(val) {
  let obj = D_BZ_DJQW.value.find(v=>{
    return vala == v.value
  })
  if(obj) form.value.qwdjmc = obj.label
  if (form.value.qwdj == "01") {
    form.value.jyzqclbl = 100;
    form.value.jyzqrybl = 100;
  } else if (form.value.qwdj == "02") {
    form.value.jyzqclbl = 50;
    form.value.jyzqrybl = 50;
  } else {
    form.value.jyzqclbl = 34;
    form.value.jyzqrybl = 34;
  }
}
//查看警力情况
function getJlqk(row) {
  jlqkVisible.value = true;
}
//上传

//重置新增表单
function formReset() {
  form.value = {
    jyzqclbl: 34,
    jyzqrybl: 34,
    qwQzsj: [],
    sfxj:'0'
  };
}
//修改
function update(row) {
  title.value = "修改勤务等级";
  getQwdjInfo(row.id).then((res) => {
    bcBtn.value = true;
    form.value = res;
    form.value.qwQzsj = [res.qwkssj, res.qwjssj];
    chackAdd.value = false;
    fileEdit.value = true;
    dialogFormVisible.value = true;
  });
}
//详情
function info(row) {
  title.value = "勤务等级详情";
  bcBtn.value = false;
  getQwdjInfo(row.id).then((res) => {
    form.value = res;
    form.value.qwQzsj = [res.qwkssj, res.qwjssj];
    chackAdd.value = false;
    fileEdit.value = false;
    dialogFormVisible.value = true;
  });
}
//发布
function fabu(row) {
  proxy
    .$confirm("请确认发布此等级勤务", "警告", {
      type: "warning"
    })
    .then((_) => {
      tableData.value.forEach((v) => {
        if (v.id == row.id) {
          v.btnLoading = true;
          fabuzt({
            id: row.id
          }).then(() => {
            proxy.$message({
              type: "success",
              message: "发布成功"
            });
            v.btnLoading = false;
            getListData();
          });
        }
      });
    })
    .catch((_) => {
      proxy.$message.info("已取消");
    });
}
//结束勤务
function jsQw(row) {
  proxy
    .$confirm("请确认结束此等级勤务", "警告", {
      type: "warning"
    })
    .then((_) => {
      row.fbzt = "2";
      tableData.value.forEach((v) => {
        if (v.id == row.id) {
          v.btnLoading = true;
          updateQwdj(row).then(() => {
            proxy.$message({
              type: "success",
              message: "已结束该等级勤务"
            });
            v.btnLoading = false;
            getListData();
          });
        }
      });
    })
    .catch((_) => {
      proxy.$message.info("已取消");
    });
}
//删除
function delDictItem(row) {
  if (row.fbzt === "1") {
    proxy.$message({
      type: "error",
      message: "勤务已经发布，不能删除!!"
    });
  } else {
    proxy
      .$confirm("确定删除当前勤务等级？", "警告", { type: "warning" })
      .then(() => {
        deleteQwdj(row.id).then(() => {
          proxy.$message({
            type: "success",
            message: "删除成功"
          });
          getListData();
        });
      })
      .catch(() => {
        proxy.$message.info("已取消");
      });
  }
}
//获取列表数据
function getListData() {
  loadingTable.value = true;
  getqwdj(listQuery.value).then((res) => {
    tableData.value = res.records.map((item) => {
      return {
        ...item,
        btnLoading: false
      };
    });
    total.value = res.total;
    loadingTable.value = false;
  }).catch(()=>{
    loadingTable.value = false;
  });
}

function add() {
  bcBtn.value = true;
  title.value = "新增勤务等级";
  chackAdd.value = true;
  fileEdit.value = true;
  dialogFormVisible.value = true;
  getJQList()
  formReset();
}
//关闭弹窗
function close() {
  dialogFormVisible.value = false;
  formReset();
}
//提交
function submit() {
  elform.value.validate((valid) => {
    if (valid) {
      btnLoading.value = true;
      const data = {
        ...form.value,
        qwkssj:form.value.qwQzsj[0],
        qwjssj:form.value.qwQzsj[1]
      }
      delete data.qwQzsj
      
      if (chackAdd.value) {
        addQwdj(data).then(() => {
          btnLoading.value = false;
          proxy.$message({
            type: "success",
            message: "新增成功"
          });
          dialogFormVisible.value = false;
          getListData();
        }).catch(()=>{
           btnLoading.value = false;
        });
      } else {
        data.id = form.value.id
        updateQwdj(data).then(() => {
          proxy.$message({
            type: "success",
            message: "修改成功"
          });
           btnLoading.value = false;
          dialogFormVisible.value = false;
          getListData();
        }).catch(()=>{
           btnLoading.value = false;
        });;
      }
    }
  });
}
/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getListData();
};
/**
 * size 改变触发
 */
const handleSizeChangezq = (currentSize) => {
  listQueryzq.value.pageSize = currentSize;
  //   getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChangezq = (currentPage) => {
  listQueryzq.value.pageCurrent = currentPage;
  //   getListData();
};
// 表格高度计算
const tabHeightFn = () => {
 tableHeight.value = window.innerHeight - searchBox.value.offsetHeight - 240;

  tableHeight1.value = window.innerHeight - 220;
};
onMounted(() => {
  getListData();
  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";

.updata {
  &::v-deep .el-form-item__content {
    display: flex;
    flex-wrap: nowrap !important;
  }
}

.twoh {
  &::v-deep .el-textarea__inner {
    height: 64px;
  }
}

</style>
