<template>
  <div style="padding-top: 13vw">
    <TopNav :navTitle="title" />
    <van-form @submit="onSubmit" style="height: calc(100vh - 13vw);">
      <div class="infoBox">
        <ul class="cardInfo">
          <li class="item">
            <van-field v-model="normalForm.xfsj" required name="时间" is-link readonly label="时间" placeholder="点击设置"
              input-align="right" :rules="[{ required: true, message: '请选择时间' }]" />
          </li>
          <li class="item">
            <van-field v-model="normalForm.xfzzXm" required name="巡访主责人" is-link readonly label="巡访主责人"
              placeholder="点击设置" input-align="right" :rules="[{ required: true, message: '请选择巡访主责人' }]"
              @click="showDialogfn('xfzz')" />
          </li>
          <li class="item">
            <van-field v-model="normalForm.xfzzSfzh" required name="身份证号" readonly input-align="right" label="身份证号"
              :rules="[{ required: true, message: '请输入组长身份证号' }]" />
          </li>
          <li class="item">
            <van-field v-model="normalForm.xfmj" name="巡访同行人(民警)" is-link label-width="108px" readonly label="巡访同行人(民警)"
              placeholder="点击设置" input-align="right" @click="showDialogfn('xfmj')" />
          </li>
          <li class="item">
            <van-field v-model="normalForm.xffj" name="巡访同行人(辅警)" is-link label-width="108px" readonly label="巡访同行人(辅警)"
              placeholder="点击设置" input-align="right" @click="showDialogfn('xffj')" />
          </li>

          <li class="item">
            <van-field v-model="normalForm.sfdw" name="巡访单位" is-link readonly label="巡访单位" placeholder="点击设置"
              input-align="right" required :rules="[{ required: true, message: '请选择巡访单位' }]"
              @click="showDialogfn('xfdw')" />
          </li>
          <li class="item">
            <van-field v-model="normalForm.dz" required name="巡访地点" label="巡访地点" placeholder="输入地点" input-align="right"
              :rules="[{ required: true, message: '请选择巡访地点' }]" />
          </li>
          <li class="item">
            <van-field v-model="normalForm.xflxmc" required name="巡访类型" is-link readonly label="巡访类型" placeholder="点击设置"
              input-align="right" :rules="[{ required: true, message: '请选择巡访类型' }]" @click="getCommonPop('xflx')" />
          </li>
          <li class="item">
            <van-field v-model="normalForm.rwztmc" name="任务状态" is-link readonly label="任务状态" placeholder="选择任务状态"
              input-align="right" @click="getCommonPop('rwzt')" />
          </li>

          <li class="item">
            <van-field name="巡访内容" @click="showDialogfn('xfnr')" readonly label="巡访内容" />
          </li>
          <div class="textarea">
            <van-field placeholder="请输相关内容" v-model="normalForm.xfnr" rows="4" autosize maxlength="500" show-word-limit type="textarea"></van-field>
          </div>
          <li class="item">
            <div><span class="mark"></span>拍照打卡</div>
          </li>
          <!-- 附件 -->
          <div class="fjBox">
            <van-uploader v-model="fileList" multiline :max-count="3" :after-read="afterRead"></van-uploader>
          </div>
        </ul>
        <div class="footer">
          <van-button round block type="primary" native-type="submit" :loading="isLoading" loading-type="spinner" loading-text="登录中...">提交</van-button>
        </div>
      </div>
    </van-form>
    <!-- 弹窗 -->
    <van-popup v-model:show="isShowCommonPicker" round position="bottom">
      <van-picker :columns="columns" @cancel="isShowCommonPicker = false" @confirm="onConfirm" />
    </van-popup>

    <!-- 弹窗 -->
    <Select v-if="showSelect" :checked="r_checked" :selectType="selectType" :show="showSelect"
      :checkedList="hasCheckedList" @update:cancel="showSelect = false" @update:confirm="onComfirm"
      :key="selectIndex" />
  </div>
</template>
<script setup>
import { baseUrl2 } from "@/utils/request.js";
import ImageCompressor from "image-compressor.js";
import { upImage } from "@/api/common";
import Select from "./components/Select.vue";
import { hintToast, timeValidate } from "../../../utils/tools";
import { rwDetail, eidtRw, addRw } from "../../../api/xfgl.js";
import TopNav from "../../../components/topNav.vue";
import { useRouter, useRoute } from "vue-router";
import { getDictList, setDict } from "../../../utils/dict";
import { ref, onMounted, reactive, defineProps, nextTick } from "vue";
const { D_BZ_XFLX, D_BZ_RWZT } = getDictList("D_BZ_XFLX", "D_BZ_RWZT");
const route = useRoute();
const router = useRouter();
const fileList = ref([]);

const normalForm = ref({
  xfsj: timeValidate(),
  rwztmc: '正常',
  rwzt: 0
});
const title = ref("新增巡防任务");
const clickType = ref(""); //点击选择
const columns = ref([]);
const time = ref();
const isShowCommonPicker = ref(false);
const showSelect = ref(false);
const selectType = ref(""); //选择的类型
const r_checked = ref(""); //选择的类型
const hasCheckedList = ref([]); //选择的类型
const selectIndex = ref(1); //选择器组件KEY
const wpTpIdList = ref([]);
const isLoading = ref(false)
const urlImg = `${baseUrl2}/mosty-api/mosty-base/minio/image/download/`;

const dataList = reactive({
  fzrList: [], //巡访组长
  nrList: [], //巡访内容
  mjList: [], //组员民警
  fjList: [], //组员辅警
  xfdwList: [],//巡访单位
});
onMounted(() => {
  title.value = route.query.id ? "编辑巡防任务" : "新增巡防任务";
  if (route.query.id) {
    nextTick(() => {
      _getDetailById(); //根据id获取详情
    });
  }
});
// 打开弹窗
function showDialogfn(type) {
  selectType.value = type; //选取的类型
  showSelect.value = true; //打开弹窗
  hasCheckedList.value = [];
  r_checked.value = "";
  selectIndex.value++;
  hasChooseData();
}
// 已经选取的数据回显
function hasChooseData() {
  switch (selectType.value) {
    case "xfzz":
      if (!dataList.fzrList.length) return false;
      r_checked.value = dataList.fzrList[0].key;
      break;
    case "xfnr":
      if (!dataList.nrList.length) return false;
      r_checked.value = dataList.nrList[0].key;
      break;
    case "xfmj":
      if (!dataList.mjList.length) return false;
      hasCheckedList.value = dataList.mjList.map((item) => {
        return item.key;
      });
      break;
    case "xffj":
      if (!dataList.fjList.length) return false;
      hasCheckedList.value = dataList.fjList.map((item) => {
        return item.key;
      });
      break;
    case "xfdw":
      if (!dataList.xfdwList.length) return false;
      hasCheckedList.value = dataList.xfdwList.map((item) => {
        return item.key;
      });
      break;
  }
}

//确认选择
function onComfirm(val) {
  if (val.length <= 0) return false;
  switch (selectType.value) {
    case "xfzz":
      dataList.fzrList = val; //选取的负责人数据
      normalForm.value.xfzzXm = val[0].xm;
      normalForm.value.xfzzSfzh = val[0].sfzh;
      break;
    case "xfnr":
      dataList.nrList = val; //巡防内容
      normalForm.value.xfnr = val[0].nr;
      break;
    case "xfmj":
      dataList.mjList = val; //选取的组员民警
      normalForm.value.xfmj = val.map(v => { return v.xm }).join(',')
      break;
    case "xffj":
      dataList.fjList = val; //选取的组员辅警
      normalForm.value.xffj = val.map(v => { return v.xm }).join(',')
      break;
    case "xfdw":
      dataList.xfdwList = val; //选取的单位
      normalForm.value.sfdw = val.map(v => { return v.dwmc }).join(',')
      normalForm.value.dz = val[0].dz
      break;
  }
}

//根据id获取详情
function _getDetailById() {
  rwDetail(route.query.id).then((res) => {
    let List = JSON.parse(res.xfzy);
    dataList.mjList = List.filter(v => { return v.fl == '01' })
    res.xfmj = dataList.mjList.map(it => { return it.xm }).join(',')
    dataList.fjList = List.filter(v => { return v.fl == '02' })
    res.xffj = dataList.fjList.map(it => { return it.xm }).join(',')

    D_BZ_XFLX.value.forEach((element) => {
      if (element.dm == res.xflx) res.xflxmc = element.text;
    });
    D_BZ_RWZT.value.forEach((element) => {
      if (element.dm == res.rwzt) res.rwztmc = element.text;
    });
    dataList.xfdwList = JSON.parse(res.xfdw)
    res.sfdw = dataList.xfdwList.map(it => { return it.dwmc }).join(',')
    res.dz = dataList.xfdwList.length > 0 ? dataList.xfdwList[0].dz : '';
    let ids = res.xfzp.split(',')
    fileList.value = []
    ids.forEach(item => {
      let img = baseUrl2 + "/mosty-api/mosty-base/minio/image/download/" + item;
      let obj = {
        url: img,
        codeId: item,
        isImage: true,
        status: "done",
        message: "上传成功",
      };
      fileList.value.push(obj)
    });
    normalForm.value = res;
  });
}

// 打开弹窗
function getCommonPop(val) {
  clickType.value = val;
  switch (val) {
    case "xflx":
      columns.value = D_BZ_XFLX.value;
      break;
    case "rwzt":
      columns.value = D_BZ_RWZT.value;
      break;
  }
  isShowCommonPicker.value = true;
}

// 确定选择
function onConfirm(val) {
  isShowCommonPicker.value = false;
  switch (clickType.value) {
    case "xflx":
      normalForm.value.xflxmc = val.text;
      normalForm.value.xflx = val.dm;
      break;
    case "rwzt":
      normalForm.value.rwztmc = val.text;
      normalForm.value.rwzt = val.dm;
      break;

  }
}

// 文件预览
async function afterRead(file) {
  file.message = "上传中...";
  let fileBlob = await _compressImage(file.file);
  let fileData = new File([fileBlob], fileBlob.name, { type: fileBlob.type });
  const data = new FormData();
  data.append("file", fileData);
  file.status = "uploading";
  upImage(data).then((res) => {
    file.status = "done";
    file.message = "上传成功";
    if (!wpTpIdList.value.includes(res)) wpTpIdList.value.push(res);
  });
}
//压缩图片
const _compressImage = (file) => {
  return new Promise((resolve, reject) => {
    new ImageCompressor(file, {
      quality: 0.6, //压缩质量
      success(res) {
        resolve(res);
      },
      error(e) {
        reject(e);
      },
    });
  });
};

// 提交
function onSubmit() {
  let arr = [...dataList.mjList, ...dataList.fjList]
  let params = {
    ...normalForm.value,
    xfzy: JSON.stringify(arr),
    xfdw: JSON.stringify(dataList.xfdwList),
  }
  let ids1 = fileList.value.filter(item => { return item.codeId }).map(v => { return v.codeId })
  let ids2 = wpTpIdList.value.join(',')
  params.xfzp = (ids1.concat(ids2)).join(',')
  isLoading.value = true;
  if (title.value == '编辑巡防任务') {
    eidtRw(params).then(res => {
      hintToast('编辑成功')
      router.go(-1);
    })
  } else {
    addRw(params).then(res => {
      hintToast('新增成功')
      router.go(-1);
    })
  }
}
</script>
<style lang="less" scoped>
.infoBox {
  height: 100%;
  position: relative;

  .cardInfo {
    height: calc(100vh - 13vw);
    padding: 1vw 4vw;
    box-sizing: border-box;
    overflow: hidden;
    overflow-y: auto;

    .item {
      position: relative;
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      border-bottom: 1px solid #e5e5e5;

      .mark {
        margin: 0 10px;
        color: red;
        font-size: 16px;
      }

      .text {
        color: #767676;
      }
    }

    .item::before {
      position: absolute;
      content: "";
      left: 0;
      top: 32%;
      background: #0066ff;
      width: 2px;
      height: 12px;
      z-index: 11;
    }
  }

  .footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 60px;
    text-align: center;

    .btn {
      padding: 2vw 6vw;
      background: #1989fa;
      color: #fff;
      border-radius: 4px;
    }
  }
}

.textarea {
  ::v-deep .van-field__control {
    background: #f8fafd;
    padding-left: 4px;
  }
}

.fjBox {
  padding: 4vw;
  box-sizing: border-box;
}
</style>