<template>
  <div class="container" style="padding-top: 13vw">
    <TopNav :navTitle="obj.bbInfo ? '巡防报备信息' : '巡防报备'" :showRight="true" rightIcon="comment-circle-o"
      @clickRight="onClickRight" />
    <van-form @submit="onSubmit">
      <div class="title_tab">班次岗位</div>
      <!-- @click="handelXfrq" -->
      <van-cell title="巡防日期">
        <template #value>
          <span>{{ chooseTime }}</span>
        </template>
      </van-cell>
      <van-field class="change" required name="radio" label-width="70px" label="勤务类型">
        <template #input>
          <van-radio-group v-model="normalForm.qwlx" direction="horizontal" :disabled="disableForm">
            <van-radio checked-color="#3e6ee8" name="00">街面巡防</van-radio>
            <van-radio checked-color="#3e6ee8" name="09">护校安园</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field class="change" v-show="normalForm.qwlx == '00'" required name="radio" label-width="70px" label="巡防岗位">
        <template #input>
          <van-radio-group v-model="normalForm.xffwlx" direction="horizontal" :disabled="disableForm">
            <!-- 基本巡组、叠加巡组、警务站巡组、屯警点执勤组、重装巡组、临时勤务 -->
            <van-radio shape="square" checked-color="#3e6ee8" name="1">基本巡组</van-radio>
            <van-radio shape="square" checked-color="#3e6ee8" name="2">叠加巡组</van-radio>
            <van-radio shape="square" checked-color="#3e6ee8" name="3">警务站巡组</van-radio>
            <van-radio shape="square" checked-color="#3e6ee8" name="4">屯警点执勤组</van-radio>
            <van-radio shape="square" checked-color="#3e6ee8" name="5">重装巡组</van-radio>
            <van-radio shape="square" checked-color="#3e6ee8" name="6">临时勤务</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <!-- 护校安园的选择巡防区 -->
      <van-field v-if="normalForm.qwlx == '09'" v-model="normalForm.xfqMc" readonly name="picker" label="护校安园"
        input-align="right" is-link placeholder="请选择护校安园" @click="showDialogfn('xfq')" />
      <!-- 截面巡防的选择 -->
      <div v-show="normalForm.qwlx == '00'">
        <van-field v-if="normalForm.xffwlx === '1' || normalForm.xffwlx === '2'" v-model="normalForm.xfqMc" readonly
          name="picker" :label="normalForm.xffwlx === '1' ? '基本巡组' : '叠加巡组'" input-align="right" is-link
          :placeholder="normalForm.xffwlx === '1' ? '请选择基本巡组' : '请选择叠加巡组'" @click="showDialogfn('xfq')" />
        <van-field v-if="normalForm.xffwlx === '4'" v-model="normalForm.kfdMc" readonly name="picker" label="屯警点执勤组"
          input-align="right" is-link placeholder="请选择屯警点执勤组" @click="showDialogfn('kfd')" />
        <van-field v-if="normalForm.xffwlx === '3'" v-model="normalForm.jczMc" readonly name="picker" label="警务站巡组"
          input-align="right" is-link placeholder="请选择警务站巡组" @click="showDialogfn('jcz')" />
      </div>
      <van-calendar v-model:show="calShow" @confirm="onConfirmTime" :min-date="minDate" :max-date="maxDate"
        color="#3e6ee8"></van-calendar>
      <!-- <van-field v-model="normalForm.bcmc" @click="showDialogfn('qwbc')" name="巡防班次" readonly is-link label="巡防班次"
        placeholder="请选择巡防班次" input-align="right" /> -->
      <van-field readonly :rules="[{ required: true, message: '请选择开始时间' }]" required v-model="normalForm.kssj"
        placeholder="请选择开始时间" input-align="right" is-link label="开始时间" @click="handleStartTime" />
      <van-field v-model="normalForm.jssj" @click="handleEndTime" readonly
        :rules="[{ required: true, message: '请选择结束时间' }]" required placeholder="请选择结束时间" input-align="right" is-link
        label="结束时间" />
      <van-popup v-model:show="showkssjPicker" position="bottom">
        <div>开始日期</div>
        <van-datetime-picker v-model="normalForm.kssjtime" type="time" title="选择时间" @cancel="showkssjPicker = false"
          @confirm="ksConfirm" />
      </van-popup>
      <van-popup v-model:show="showjssjPicker" position="bottom">
        <van-datetime-picker v-model="normalForm.jssjtime" type="time" title="选择时间" @cancel="showjssjPicker = false"
          @confirm="jsConfirm" />
      </van-popup>


      <div class="title_tab">人员车辆</div>
      <!-- <van-field v-model="normalForm.jzMc" name="选择警组" readonly input-align="right" label="选择警组" is-link
        placeholder="请选择警组" @click="showDialogfn('jz')" /> -->
      <van-field v-model="normalForm.fzrXm" required readonly input-align="right" :clearable="true" name="picker"
        label="负责人" :rules="[{ required: true, message: '请选择负责人' }]" />

      <van-cell class="mulSelect" title="民警" color="#1989fa">
        <template #right-icon>
          <van-icon @click.stop="showDialogfn('mj')" name="add-o" color="#1989fa" size="22" />
        </template>
        <template #default>
          <div class="selected-box">
            <div class="check-item-tag" v-for="(item, index) in normalForm.mjList" :key="index">
              <van-tag color="#7232dd" closeable @close="deleteCheckTag(item, index, 'mj')" plain>{{ item.xm ||
                item.jlxm
                }}</van-tag>
            </div>
          </div>
        </template>
      </van-cell>
      <van-cell class="mulSelect" title="辅警" color="#1989fa">
        <template #right-icon>
          <van-icon @click.stop="showDialogfn('fj')" name="add-o" color="#1989fa" size="22" />
        </template>
        <template #default>
          <div class="selected-box">
            <div class="check-item-tag" v-for="(item, index) in normalForm.fjList" :key="index">
              <van-tag closeable @close="deleteCheckTag(item, index, 'fj')" color="#7232dd" plain>{{ item.xm ||
                item.jlxm
                }}</van-tag>
            </div>
          </div>
        </template>
      </van-cell>
      <van-cell class="mulSelect" title="巡防车辆" color="#1989fa">
        <template #right-icon>
          <van-icon @click.stop="showDialogfn('cl')" name="add-o" color="#1989fa" size="22" />
        </template>
        <template #default>
          <div class="selected-box">
            <div class="check-item-tag" v-for="(item, index) in normalForm.clList" :key="index">
              <van-tag color="#7232dd" closeable @close="deleteCheckTag(item, index, 'cl')" plain>{{ item.value ||
                item.jdchphm }}</van-tag>
            </div>
          </div>
        </template>
      </van-cell>
      <div class="title_tab">装备</div>
      <van-cell class="mulSelect" title="智能装备" color="#1989fa">
        <template #right-icon>
          <van-icon @click.stop="showDialogfn('zn')" name="add-o" color="#1989fa" size="22" />
        </template>
        <template #default>
          <div class="selected-box">
            <div class="check-item-tag" v-for="(item, index) in normalForm.znzbList" :key="index">
              <van-tag closeable @close="deleteCheckTag(item, index, 'zn')" color="#7232dd" plain>{{ item.value ||
                item.sbmc }}</van-tag>
            </div>
          </div>
        </template>
      </van-cell>
      <!-- <van-cell class="mulSelect" title="警用器械" color="#1989fa">
        <template #right-icon>
          <van-icon @click.stop="showDialogfn('jy')" name="add-o" color="#1989fa" size="22" />
        </template>
        <template #default>
          <div class="selected-box">
            <div class="check-item-tag" v-for="(item, index) in normalForm.jyqxList" :key="index">
              <van-tag closeable @close="deleteCheckTag(item, index, 'jy')" color="#7232dd" plain>{{ item.value ||
                item.qxmc }} * {{ item.qxsl }}</van-tag>
            </div>
          </div>
        </template>
      </van-cell> -->
      <van-field class="change" name="radio" label="警用器械">
        <template #input>
          <van-radio-group v-model="normalForm.jyqxSfagdxd" direction="horizontal" :disabled="disableForm">
            <van-radio checked-color="#3e6ee8" name="1">是</van-radio>
            <van-radio checked-color="#3e6ee8" name="0">否</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field class="change" name="checkbox" label="武器装备">
        <template #input>
          <!-- <van-radio-group v-model="normalForm.xlfs" direction="horizontal" :disabled="disableForm">
            <van-radio checked-color="#3e6ee8" name="1">是</van-radio>
            <van-radio checked-color="#3e6ee8" name="0">否</van-radio>
          </van-radio-group> -->
          <van-checkbox-group v-model="normalForm.wqzbList" :disabled="disableForm">
            <van-checkbox v-for="item in D_BZ_WQZB" :name="item.dm" :key="item.dm">{{ item.zdmc }}</van-checkbox>
          </van-checkbox-group>
        </template>
      </van-field>

      <div class="title_tab" v-if="normalForm.jyqxList.length > 0">
        警用器械数量
      </div>
      <van-field :disabled="disableForm" v-for="item in normalForm.jyqxList" :key="item.qxid" v-model="item.qxsl"
        type="digit" :label="item.qxmc">
      </van-field>
      <div class="title_tab">巡逻方式</div>

      <van-field class="change" name="radio" label="巡逻方式">
        <template #input>
          <van-radio-group v-model="normalForm.xlfs" direction="horizontal" :disabled="disableForm">
            <van-radio checked-color="#3e6ee8" name="1">步巡</van-radio>
            <van-radio checked-color="#3e6ee8" name="0">车巡</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field class="change" name="radio" label="着装类型">
        <template #input>
          <van-radio-group v-model="normalForm.zzlx" direction="horizontal" :disabled="disableForm">
            <van-radio checked-color="#3e6ee8" name="0">制服</van-radio>
            <van-radio checked-color="#3e6ee8" name="1">便衣</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <!-- <van-field class="change" name="radio" label="武装类型">
        <template #input>
          <van-radio-group v-model="normalForm.wzlx" direction="horizontal" :disabled="disableForm">
            <van-radio checked-color="#3e6ee8" name="0">武装</van-radio>
            <van-radio checked-color="#3e6ee8" name="1">非武装</van-radio>
          </van-radio-group>
        </template>
      </van-field> -->
      <!-- <van-field class="change" name="radio" label="动中备勤">
        <template #input>
          <van-radio-group
            v-model="normalForm.dzbq"
            direction="horizontal"
            :disabled="disableForm"
          >
            <van-radio checked-color="#3e6ee8" name="0">否</van-radio>
            <van-radio checked-color="#3e6ee8" name="1">是</van-radio>
          </van-radio-group>
        </template>
      </van-field> -->
      <van-row>
        <van-col span="24">
          <van-field rows="3" type="textarea" v-model="normalForm.bz" name="备注" :disabled="disableForm"
            placeholder="备注信息" />
        </van-col>
      </van-row>
      <div style="padding: 0 5vw" v-if="obj.bbInfo">
        <van-button style="margin: 16px 0" :loading="loading" round @click="editFn(0)" block type="success">
          下班打卡
        </van-button>
      </div>
      <div style="margin: 16px 0; padding: 0 5vw" v-else>
        <van-button :loading="loading" round native-type="submit" block type="primary">
          开始报备
        </van-button>
      </div>
    </van-form>
    <!-- 负责人 -->
    <Select bclx="02" :dwlx="dwlx" :xfqSx="xfqSx" :checked="r_checked" :selectType="selectType" :show="showSelect"
      v-if="showSelect" :checkedList="hasCheckedList" @update:cancel="showSelect = false" @update:confirm="onComfirm"
      :key="selectIndex" />
  </div>
</template>

<script setup>
import {
  getKfdListById,
  getXfqListById,
  getBcListById,
} from "../../../api/xfbbAndZbbb.js";
import { getItem } from "../../../utils/storage";
import TopNav from "../../../components/topNav";
import Select from "../../../components/Select.vue";
import { Dialog, Toast } from "vant";
import { getDictList, setDict } from "@/utils/dict";
import { addXFBB } from "../../../api/report";
import {
  getMybbTodayNew,
  finishReport,
  getMyXfpbToday,
  getYestoday,
} from "../../../api/common";
import {
  dateFormat,
  hintToast,
  getRecentDay,
  timeValidate,
} from "../../../utils/tools.js";
import { ref, reactive, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { get } from "vant/lib/utils";
Toast.allowMultiple();
const { D_BZ_WQZB } = getDictList("D_BZ_WQZB");
const router = useRouter();
const route = useRoute();
const userInfo = getItem("userInfo");
const showSelect = ref(false); //弹窗的显示和隐藏
const dwlx = ref("01"); //弹窗的单位类型
const xfqSx = ref('01');//巡防区属性 01.基本巡区 02.叠加巡区 03.护校巡区")
const calShow = ref(false); //是否显示巡防日期选择器
const chooseTime = ref(dateFormat("", new Date()));
const minDate = new Date(2000, 0, 1); // 巡防日期最小时间
const maxDate = new Date(2050, 0, 1); // 巡防日期最大时间
const disableForm = ref(false);
const loading = ref(false); //报备按钮的节流
const normalForm = ref({
  bcmc: "", //班次名称
  xfrq: dateFormat(),
  kssj: "", // 开始时间
  jssj: "", //结束时间
  xffwlx: "", //岗位类型
  xfqMc: "", //巡防区
  bbzt: "0",
  xlfs: "1",
  zzlx: "1",
  wzlx: "1",
  jzMc: "",
  jzId: "",
  ssbm: userInfo.deptName,
  ssbmdm: userInfo.deptList[0].deptCode,
  lxrsfzh: userInfo.idEntityCard,
  lxrid: userInfo.id,
  fzrXm: userInfo.userName,
  fzrSfzh: userInfo.idEntityCard,
  fzrLxdh: userInfo.mobile,
  fzrInfo: userInfo.userName,
  fzrId: userInfo.id,
  znzbList: [],
  jyqxList: [],
  clList: [],
  jlList: [],
  bz: "",
  xffwid: "",
  xffwList: [],
  kfdMc: "",
  jczMc: "",
  mjList: [],
  fjList: [],
  dzbq: "0",
  wqzbList: [], //武器装备
  qwlx: '1'
});
const selectIndex = ref(1); //选择器组件KEY
const selectType = ref(""); //弹窗选择的类型
const showkssjPicker = ref(false); //开始时间结束时间弹窗
const showjssjPicker = ref(false); //结束时间结束时间弹窗
const dataList = reactive({
  bcList: [], //存班次的数据
  xfqList: [], //存的巡防区域list
  kfdList: [], //快返点数据
  jczList: [], //快返点数据
  jzList: [], //警组数据
  fzrList: [], //负责人数据
  mjList: [], //民警数据
  fjList: [], //辅警数据
  znzbList: [], //智能装备数据
  clList: [], //车辆数据
  jyqxList: [], //警用器械
});
// 获取数据
const list = reactive({
  xfqList: [], //巡防区
  kfdList: [], //快返点
  jczList: [], //检查站
  bcList: [], //班次数据
  jyqxList: [], //警用器械
});

const hasCheckedList = ref([]); //多选状态
const r_checked = ref(""); //单选框默认选中
const isUserDept = ref(false); //是否是用户本部门
const kwd = ref(""); //选择器关键字
const obj = reactive({ bbInfo: null, pbInfo: null });

watch(
  () => normalForm.value,
  (val) => {
    if (val.kssj && val.jssj) {
      let startTime = handleTime(val.kssj);
      let endTime = handleTime(val.jssj);
      if (startTime >= endTime) {
        let end = val.jssj.slice(11, 19);
        normalForm.value.jssj = getRecentDay(1, "ymd") + " " + end;
      }
      setZqsc(); //执勤时长
    }
  },
  { immediate: true, deep: true }
);
onMounted(() => {
  _getMybbTodayNew();
});

// 处理时间
function handleTime(time) {
  var deteString = Date.parse(new Date(time));
  return deteString;
}

//计算执勤时长
function setZqsc() {
  if (normalForm.value.jssj && normalForm.value.kssj) {
    let start = new Date();
    let startTime = normalForm.value.kssj.slice(11, 19);
    start.setHours(startTime.split(":")[0]);
    start.setMinutes(startTime.split(":")[1]);
    let end = new Date();
    let endTime = normalForm.value.jssj.slice(11, 19);
    end.setHours(endTime.split(":")[0]);
    end.setMinutes(endTime.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;
    }
    normalForm.value.zqsc = time >> 0;
  }
}

// 跳转特殊报备
function onClickRight() {
  router.push("/yyzx/xfbb/addtsXfbb");
}

// 查询巡防范围
function _getXfqList(id) {
  getXfqListById(id).then((res) => {
    res.value = `${res.ssbm}-${res.xfqMc}`;
    res.key = res.id;
    list.xfqList = list.xfqList.concat([res]);
    _setHxData(list.xfqList, "id", res.id, "xfq");
  });
}
//获取快反点数据
function _getKfdList(id, type) {
  getKfdListById(id).then((res) => {
    if (res) {
      res.value = `${res.ssbm}-${res.kfdMc}`;
      res.key = res.kfdId;
      if (type == "kfd") list.kfdList = [res];
      if (type == "jcz") list.kfdList = [res];
      _setHxData([res], "kfdId", res.kfdId, type);
    }

  });
}

// 根据id获取班次
function getBcInfoById(id) {
  getBcListById(id).then((res) => {
    if (!res) return false;
    normalForm.value.bcmc = res.bcmc;
  });
}

// 点击开始时间
function handleStartTime() {
  if (disableForm.value) return false;
  showkssjPicker.value = true;
}

// 点击结束时间
function handleEndTime() {
  if (disableForm.value) return false;
  showjssjPicker.value = true;
}

// 点击巡防日期
function handelXfrq() {
  if (disableForm.value) return false;
  calShow.value = true;
}

//获取用户的报备信息
function _getMybbTodayNew() {
  getMybbTodayNew().then((res) => {
    if (res) {
      const resData = JSON.parse(JSON.stringify(res));
      obj.bbInfo = resData;
      disableForm.value = true;
      _setSubmitData(resData);
    } else {
      disableForm.value = false;
      _getMyXfpbToday(); //没有报备信息 查询排版信息
    }
  })
    .catch((err) => { });
}

//设置需要提交的参数
function _setSubmitData(obj) {
  console.log(obj, 'obj');
  if (!obj) return false;
  normalForm.value = obj;
  normalForm.value.xfrq = getRecentDay(0, "ymd");
  let startTime = obj.kssj || "";
  let endTime = obj.jssj || "";
  normalForm.value.kssj = getRecentDay(0, "ymd") + " " + startTime;
  normalForm.value.jssj = getRecentDay(0, "ymd") + " " + endTime;
  normalForm.value.bbkssj = timeValidate(new Date());
  normalForm.value.zbsj = timeValidate(new Date());
  normalForm.value.mjList = obj.pbmj ? JSON.parse(obj.pbmj) : [];
  normalForm.value.fjList = obj.pbfj ? JSON.parse(obj.pbfj) : [];
  normalForm.value.znzbList = obj.txzb ? JSON.parse(obj.txzb) : [];
  normalForm.value.jyqxList = obj.jyqx ? JSON.parse(obj.jyqx) : [];
  normalForm.value.clList = obj.pbcl ? JSON.parse(obj.pbcl) : [];
  normalForm.value.wqzbList = obj.wqzb ? obj.wqzb.split(',') : [];
  getBcInfoById(obj.qwbcId); //班次
  if (obj.jzId) dataList.jzList = [{ key: obj.jzId }]; // 警组
  if (obj.xffwlx == 1) {
    let ids = obj.xffwid.split(",");
    normalForm.value.xfqMc = "";
    ids.forEach((item) => {
      _getXfqList(item);
    });
  } else if (obj.xffwlx == 2) {
    _getKfdList(obj.xffwid, "kfd");
  } else if (obj.xffwlx == 3) {
    _getKfdList(obj.xffwid, "jcz");
  }
}
/**
 * 返回回显对象数据
 * @param {*} array 比对数据
 * @param {*} key 比对key
 * @param {*} val 比对值
 */
function _setHxData(array, key, val, type) {
  let arr = val ? val.split(",") : [];
  switch (type) {
    case "xfq":
      normalForm.value.xffwList = [];
      let data = handelArr(arr, array, key, "XFQ");
      dataList.xfqList = data.crr;
      data.crr.forEach((item) => {
        normalForm.value.xfqMc += item.xfqMc + ",";
        normalForm.value.xffwList.push({
          fwMc: item.xfqMc,
          glbid: item.id,
          id: item.id,
          qwlx: "1",
          xffwlx: normalForm.value.xffwlx,
        });
      });
      break;
    case "kfd":
      let obj = handelArr(arr, array, key, "KFD");
      normalForm.value.kfdMc = obj.str;
      dataList.kfdList = obj.crr;
      break;
    case "jcz":
      let obj1 = handelArr(arr, array, key, "JCZ");
      normalForm.value.jczMc = obj1.str;
      dataList.jczList = obj1.crr;
      break;
  }
}

// 处理数组
function handelArr(arr, brr, key, type) {
  let obj = { str: "", crr: [] };
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < brr.length; j++) {
      if (arr[i] == brr[j][key]) {
        if (type == "XFQ") {
          obj.str += brr[j].xfqMc + ",";
        }
        if (type == "KFD" || type == "JCZ") {
          obj.str += brr[j].kfdMc + ",";
        }
        obj.crr.push(brr[j]);
      }
    }
  }
  return obj;
}

//确认巡防日期选择
function onConfirmTime(val) {
  calShow.value = false;
  chooseTime.value = dateFormat("", val);
  normalForm.c.xfrq = chooseTime.value;
}
//打开选择框
function showDialogfn(type) {
  if (disableForm.value) return false;
  selectType.value = type; //选取的类型
  showSelect.value = true; //打开弹窗
  hasCheckedList.value = [];
  r_checked.value = "";
  if (type == "kfd") {
    if (normalForm.value.xffwlx == '4') {
      dwlx.value = "04";
    } else {
      dwlx.value = "01";
    }
  } else if (type == "jcz") {
    dwlx.value = "02";
  }
  //巡防区属性 01.基本巡区 02.叠加巡区 03.护校巡区")
  if (type == 'xfq') {
    if (normalForm.value.xffwlx == '1') {
      xfqSx.value = '01'
    } else if (normalForm.value.xffwlx == '2') {
      xfqSx.value = '02'
    }
    if (normalForm.value.qwlx == '09') {
      xfqSx.value = '03'
    }
  }
  hasChooseData();
  selectIndex.value++;
}

// 已经选取的数据回显
function hasChooseData() {
  switch (selectType.value) {
    case "qwbc":
      if (!dataList.bcList.length) return false;
      r_checked.value = dataList.bcList[0].key;
      break;
    case "xfq":
      if (!dataList.xfqList.length) return false;
      hasCheckedList.value = dataList.xfqList.map((item) => {
        return item.key;
      });
      break;
    case "kfd":
      if (!dataList.kfdList.length) return false;
      r_checked.value = dataList.kfdList[0].key;
      break;
    case "jcz":
      if (!dataList.jczList.length) return false;
      r_checked.value = dataList.jczList[0].key;
      break;
    case "jz":
      if (!dataList.jzList.length) return false;
      r_checked.value = dataList.jzList[0].key;
      break;
    case "fzr":
      if (!dataList.fzrList.length) return false;
      r_checked.value = dataList.fzrList[0].key;
      break;
    case "mj":
      if (!dataList.mjList.length) return false;
      hasCheckedList.value = dataList.mjList.map((item) => {
        return item.key;
      });
      break;
    case "fj":
      if (!dataList.fjList.length) return false;
      hasCheckedList.value = dataList.fjList.map((item) => {
        return item.key;
      });
      break;
    case "zn":
      if (!dataList.znzbList.length) return false;
      hasCheckedList.value = dataList.znzbList.map((item) => {
        return item.key;
      });
      break;
    case "cl":
      if (!dataList.clList.length) return false;
      hasCheckedList.value = dataList.clList.map((item) => {
        return item.key;
      });
      break;
    case "jy":
      if (!dataList.jyqxList.length) return false;
      hasCheckedList.value = dataList.jyqxList.map((item) => {
        return item.key;
      });
      break;
  }
}

//获取用户排班信息
function _getMyXfpbToday() {
  getMyXfpbToday().then((res) => {
    if (res) {
      const resData = JSON.parse(JSON.stringify(res));
      if (!resData.jyqx) resData.jyqx = JSON.stringify([]);
      if (!resData.pbmj) resData.pbmj = JSON.stringify([]);
      if (!resData.pbfj) resData.pbfj = JSON.stringify([]);
      if (!resData.txzb) resData.txzb = JSON.stringify([]);
      if (!resData.pbcl) resData.pbcl = JSON.stringify([]);
      obj.pbInfo = resData;
      _setSubmitData(resData);
    } else {
      hintToast("没有排班和报备信息，请自行填写并报备");
      getYesterdayDate();
    }
  });
}

// 获取昨天的数据
function getYesterdayDate() {
  let data = { sfzh: userInfo.idEntityCard };
  getYestoday(data).then((res) => {
    console.log(res);
    _setSubmitData(res);
  });
}

// 开始时间弹窗
function ksConfirm(val) {
  normalForm.value.kssj = getRecentDay(0, "ymd") + " " + val + ":00";
  showkssjPicker.value = false;
}
// 结束时间弹窗
function jsConfirm(val) {
  normalForm.value.jssj = getRecentDay(0, "ymd") + " " + val + ":00";
  showjssjPicker.value = false;
}

//确认选择
function onComfirm(val) {
  if (val.length <= 0) return false;
  switch (selectType.value) {
    case "qwbc":
      dataList.bcList = val; //选取的班次数据
      onbcConfirm(val[0]);
      break;
    case "xfq":
      normalForm.value.xfqMc = "";
      dataList.xfqList = val; //选取的巡防区数据
      normalForm.value.xffwList = [];
      val.forEach((item) => {
        toggle(item);
      });
      break;
    case "kfd":
      dataList.kfdList = val; //选取的快返点数据
      onkfdConfirm(val[0]);
      break;
    case "jcz":
      dataList.jczList = val; //选取的快返点数据
      onkfdConfirm(val[0]);
      break;
    case "jz":
      dataList.jzList = val; //选取的警组数据
      onjzConfirm(val[0]);
      break;
    case "fzr":
      dataList.fzrList = val; //选取的负责人数据
      onfzrConfirm(val[0]);
      break;
    case "mj":
      normalForm.value.mjList = [];
      dataList.mjList = val;
      val.forEach((item) => {
        toggle(item);
      });
      break;
    case "fj":
      normalForm.value.fjList = [];
      dataList.fjList = val;
      val.forEach((item) => {
        toggle(item);
      });
      break;
    case "zn":
      dataList.znzbList = val;
      normalForm.value.znzbList = [];
      val.forEach((item) => {
        toggle(item);
      });
      break;
    case "cl":
      dataList.clList = val;
      normalForm.value.clList = [];
      val.forEach((item) => {
        toggle(item);
      });
      break;
    case "jy":
      dataList.jyqxList = val;
      normalForm.value.jyqxList = [];
      val.forEach((item) => {
        toggle(item);
      });
      break;
  }
}
//选中的勤务班次数据
function onbcConfirm(val) {
  normalForm.value.bcmc = val.bcmc;
  normalForm.value.qwbcId = val.id;
  normalForm.value.zqsc = val.zqsc;
  normalForm.value.kssj = getRecentDay(0, "ymd") + " " + val.kssj;
  normalForm.value.jssj = getRecentDay(0, "ymd") + " " + val.jssj;
}

//设置选中值
const toggle = (item) => {
  switch (selectType.value) {
    case "xfq":
      normalForm.value.xfqMc += item.xfqMc + ",";
      normalForm.value.xffwList.push({
        fwMc: item.xfqMc,
        glbid: item.id,
        id: item.id,
        qwlx: "1",
        xffwlx: normalForm.value.xffwlx,
      });
      break;
    case "mj":
      normalForm.value.mjList.push({
        jh: item.jh,
        jllx: item.fl,
        jlxm: item.xm,
        sfzh: item.sfzh,
        xm: item.xm,
        lxdh: item.lxdh,
        xfbmid: item.xbdm,
        id: item.ryid,
        qwjzId: "",
        jlId: item.ryid,
      });
      break;
    case "fj":
      normalForm.value.fjList.push({
        jh: item.jh,
        jllx: item.fl,
        jlxm: item.xm,
        id: item.id,
        sfzh: item.sfzh,
        xm: item.xm,
        lxdh: item.lxdh,
        xfbmid: item.xbdm,
        qwjzId: "",
        jlId: item.id,
      });
      break;
    case "zn":
      normalForm.value.znzbList.push({
        sbmc: item.sbmc,
        text: item.sbmc,
        txzblx: item.scode,
        txzbId: item.id,
        hh: item.sbbh,
        sfrh: item.sfrh,
        sfxt: item.sfxt,
        sfzy: item.sfzy,
      });
      break;
    case "jy":
      normalForm.value.jyqxList.push({
        qxid: item.id,
        qxmc: item.qxMc,
        text: item.qxMc,
        qxsl: item.sl ? item.sl : 1,
        qxlx: item.scode,
      });
      normalForm.value.wzlx = "0";
      break;
    case "cl":
      normalForm.value.clList.push({
        clId: item.cid,
        jdchphm: item.cph,
        text: item.cph,
        jdchpzldm: item.cllx,
        gpsId: item.gpsId,
      });
      normalForm.value.xlfs = "0";
      break;
  }
};

// 警组回显
function onjzConfirm(val) {
  normalForm.value.mjList = [];
  normalForm.value.fjList = [];
  normalForm.value.clList = [];
  normalForm.value.znzbList = [];
  normalForm.value.jyqxList = [];
  normalForm.value.jzMc = val.jzMc;
  normalForm.value.jzId = val.id;

  dataList.fzrList = []; //负责人
  dataList.fzrList = [{ key: val.ddMjid }];
  normalForm.value.jh = val.ddMjjh;

  // 民警辅警已有赋值
  dataList.mjList = []; //缓存民警
  dataList.fjList = []; //缓存辅警
  val.jzryList.forEach((m) => {
    m.key = m.ryId;
    if (m.jllx === "01") {
      dataList.mjList.push(m);
      normalForm.value.mjList.push({
        jh: m.jh,
        jllx: m.jllx,
        jlxm: m.jlxm,
        text: m.jlxm,
        nl: m.nl,
        qwjzId: m.qwjzId,
        jlId: m.ryId,
        sfzh: m.sfzh,
        xfbmid: m.xbdm,
        xm: m.jlxm,
        jh: m.jh,
        lxdh: m.lxdh,
      });
    }
    if (m.jllx === "02") {
      dataList.fjList.push(m);
      normalForm.value.fjList.push({
        jh: m.jh,
        jllx: m.jllx,
        jlxm: m.jlxm,
        text: m.jlxm,
        nl: m.nl,
        qwjzId: m.qwjzId,
        jlId: m.ryId,
        sfzh: m.sfzh,
        xfbmid: m.xbdm,
        xm: m.jlxm,
        jh: m.jh,
        lxdh: m.lxdh,
      });
    }
  });
  // 车辆
  dataList.clList = [];
  if (val.clList.length > 0) {
    normalForm.value.xlfs = "0";
    val.clList.forEach((c) => {
      c.key = c.clId;
      dataList.clList.push(c);
      normalForm.value.clList.push({
        clId: c.clId,
        jdchphm: c.jdchphm,
        text: c.jdchphm,
        jdchpzldm: c.jdchpzldm,
        gpsId: c.gpsId,
        qwjzId: c.qwjzId,
      });
    });
  }
  // 警用器械
  dataList.jyqxList = [];
  val.jyqxList.forEach((j) => {
    j.key = j.qxId;
    dataList.jyqxList.push(j);
    normalForm.value.jyqxList.push({
      qxid: j.qxid,
      qxmc: j.qxmc,
      text: j.qxmc,
      qxsl: j.sl ? j.sl : 1,
      qxlx: j.qxlx,
      qwjzId: j.qwjzId,
    });
  });
  // 智能装备
  dataList.znzbList = [];
  val.txzbList.forEach((z) => {
    z.key = z.zbId;
    dataList.znzbList.push(z);
    normalForm.value.znzbList.push({
      sbmc: z.sbmc,
      text: z.sbmc,
      txzblx: z.txzblx,
      txzbId: z.zbId,
      qwjzId: z.qwjzId,
      hh: z.hh,
      sfrh: z.sfrh,
      sfxt: z.sfxt,
      sfzy: z.sfzy,
    });
  });
}

//选中负责人
function onfzrConfirm(val) {
  normalForm.value.xfbmid = val.xbdm;
}

//删除选中数据
function deleteCheckTag(item, index, val) {
  if (disableForm.value) return false;
  switch (val) {
    case "mj":
      normalForm.value.mjList.splice(index, 1);
      dataList.mjList.splice(index, 1);
      break;
    case "fj":
      normalForm.value.fjList.splice(index, 1);
      dataList.fjList.splice(index, 1);
      break;
    case "zn":
      normalForm.value.znzbList.splice(index, 1);
      dataList.znzbList.splice(index, 1);
      break;
    case "jy":
      normalForm.value.jyqxList.splice(index, 1);
      dataList.jyqxList.splice(index, 1);
      list.jyqxList.forEach((el) => {
        if (el.id === item.qxid) el.qxsl = 1;
      });
      if (!normalForm.value.jyqxList.map((j) => j.scode).includes("01")) {
        normalForm.value.wzlx = "2";
      }
      break;
    case "cl":
      normalForm.value.clList.splice(index, 1);
      dataList.clList.splice(index, 1);
      if (normalForm.value.clList.length == 0) normalForm.value.xlfs = "1";
      break;
  }
}

// 新增报备接口
function onSubmit() {
  normalForm.value.jlList = [...normalForm.value.mjList, ...normalForm.value.fjList,];
  normalForm.value.xfbmid = normalForm.value.ssbmid ? normalForm.value.ssbmid : userInfo.deptList[0].deptId;
  normalForm.value.xfpbId = obj.pbInfo ? obj.pbInfo.id : "";
  normalForm.value.bblx = "01";
  if (!normalForm.value.xffwlx) return hintToast("请选择巡防类型！！");

  if (!normalForm.value.bz && !normalForm.value.xffwid) {
    if (normalForm.value.xffwlx == "1" && !normalForm.value.xfqMc) {
      return hintToast("请选择巡防区或者填写备注");
    }
    if (normalForm.value.xffwlx == "2" && !normalForm.value.kfdMc) {
      return hintToast("请选择快反点或者填写备注");
    }
    if (normalForm.value.xffwlx == 3 && !normalForm.value.jczMc) {
      return hintToast("请选择检查站或者填写备注");
    }
  }
  Dialog.confirm({ title: "提示", message: "是否确认警组信息是否无误,若需要修改警组信息，请结束报备后重新开始!", confirmButtonColor: "#3e6ee8", }).then((res) => {
    normalForm.value.kssj = normalForm.value.kssj.slice(11, 19);
    normalForm.value.jssj = normalForm.value.jssj.slice(11, 19);
    if (!normalForm.value.kssj || !normalForm.value.jssj) return hintToast("请选择时间!");
    normalForm.value.ssbmdm = userInfo.deptList[0].deptCode
    normalForm.value.ssbm = userInfo.deptList[0].deptName
    if (normalForm.value.wqzbList.length > 0) {
      normalForm.value.wqzb = normalForm.value.wqzbList.join(',')
    }
    normalForm.value.id = getUUid()
    addXFBB(normalForm.value).then((res) => {
      loading.value = true;
      getMybbTodayNew().then((_res) => {
        if (!_res) return false;
        userInfo.bbId = _res.id;
        userInfo.jzId = _res.jzId;
        userInfo.jzMc = _res.jzMc;
        loading.value = false;
        setStorage("userInfo", JSON.stringify(userInfo));
      });
      hintToast("报备成功!");
      router.go(-1);
      finishReport({ bbzt: "0", id: res }).then((res) => { });
    }).catch(() => {
      loading.value = false;
    });
  });
}

function getUUid() {
  var list = [];
  var hexDigits = "0123456789abcdefghijklmnopqrstuvwxyz";
  for (var i = 0; i < 32; i++) {
    list[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  list[14] = "4";
  list[19] = hexDigits.substr((list[19] & 0x3) | 0x8, 1);
  list[8] = list[13] = list[18] = list[23];
  let uuid = list.join("");
  return uuid;
}

//结束报备
function editFn(e) {
  Dialog.confirm({
    title: "提示",
    message: "是否确认结束报备!",
    confirmButtonColor: "#3e6ee8",
  }).then((res) => {
    loading.value = true;
    finishReport({ bbzt: "1", id: obj.bbInfo.id })
      .then((res) => {
        loading.value = false;
        hintToast("报备结束成功");
        userInfo.bbId = "";
        userInfo.jzId = "";
        userInfo.jzMc = "";
        router.go(-1);
        setStorage("userInfo", JSON.stringify(userInfo));
      })
      .catch(() => {
        loading.value = false;
      });
  });
}

function onkfdConfirm(val) {
  if (selectType.value == "jcz") {
    normalForm.value.jczMc = val.kfdMc;
  } else {
    normalForm.value.kfdMc = val.kfdMc;
  }
  normalForm.value.xffwid = val.kfdId;
}
</script>

<style lang="scss" scoped>
@import "../../../assets/styles/mixin.scss";

.popupTitle {
  text-align: center;
  background-color: rgb(11, 137, 247);
  height: 6vh;
  line-height: 6vh;
}

.popbtn-box {
  width: 100%;
  display: flex;
  justify-content: space-around;
}

.check-item-tag {
  display: inline-block;
  margin: 0 6px;
}

.check-data-box {
  height: 25vh;
  overflow: auto;
}

.time-box {
  display: flex;
}

::v-deep .mulSelect .van-cell__title,
.van-cell__value {
  flex: unset;
}

::v-deep .mulSelect .van-cell__value {
  flex: 1;
}

.title_tab {
  @include font_color($font-color-theme);
  padding-left: 7vw;
  position: relative;
  margin: 2vw 0;
  letter-spacing: 2px;
}

.title_tab::after {
  content: "";
  position: absolute;
  top: 0;
  left: 5vw;
  bottom: 0;
  width: 4px;
  background: #3b6be7;
  border-radius: 2px;
}

.van-cell:after {
  display: none;
}

.van-cell {
  @include table_item_color($table-item-theme);
  box-sizing: border-box;
  border-radius: 4px;
  padding: 6px;
  margin: 8px 5%;
  width: 90%;
  overflow: hidden;
  color: var(--van-cell-text-color);
  font-size: var(--van-cell-font-size);
  line-height: var(--van-cell-line-height);
}

.popupTitle {
  color: #fff;
}

::v-deep .van-field__label {
  margin-right: 0px;
}

::v-deep .van-radio-group--horizontal,
.van-checkbox-group--horizontal {
  flex-wrap: wrap;
  @include font_size($font_medium_s);
}

::v-deep .van-checkbox-group {
  display: flex;
}

::v-deep .van-field__control--custom {
  justify-content: flex-end;
}

::v-deep .van-checkbox {
  margin-left: 10px;
}

::v-deep .van-radio {
  margin-bottom: 4px;
}
</style>
