<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 class="itemlabel"><span class="mark"></span>拍照打卡</div>
          </li>

          <!-- 附件 -->
          <div class="fjBox">
            <van-uploader v-model="fileList" multiline :max-count="3" :after-read="afterRead"
              :before-delete="deleteFj"></van-uploader>
          </div>
          <li class="item">
            <van-field v-model="sbsj" required name="申报时间" readonly label="申报时间" input-align="right"
              :rules="[{ required: true, message: '请选择时间' }]" />
          </li>
          <li class="item">
            <van-field v-model="normalForm.sblxmc" required name="申报类型" is-link readonly label="申报类型" placeholder="点击设置"
              input-align="right" :rules="[{ required: true, message: '请选择申报类型' }]" @click="getCommonPop('sblx')" />
          </li>
          <li class="item">
            <van-field required name="申报原因" readonly label="申报原因" />
          </li>
          <van-field placeholder="请输入相关内容" v-model="normalForm.sbyy" rows="4" autosize accept=".txt,.png,.zip,jpg,jpeg"
            maxlength="500" show-word-limit type="textarea"></van-field>
          <li class="item">
            <div class="itemlabel"><span class="mark"></span>添加附件</div>
          </li>
          <!-- 附件 -->
          <div class="fjBox">
            <van-uploader v-model="fjData" multiline :max-count="3" accept="" :after-read="afterReadFjsb"
              :before-delete="beforeDeletefJ">
            </van-uploader>
          </div>

          <li class="item">
            <div class="itemlabel"><span class="mark"></span>附件列表</div>
          </li>
          <div class="fjBox">
            <div v-for="(it, idex) in fileBoxs" :key="idex" class="listitem">
              <span class="name">{{ it.name }}</span>
              <span> <van-icon name="close" color="#ff0000" @click="deletDate(it, idex)"></van-icon> </span>
            </div>
          </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, D_SB_SBLX } = getDictList("D_BZ_XFLX", "D_BZ_RWZT", "D_SB_SBLX");
const route = useRoute();
const router = useRouter();
const fileList = ref([]);
const fjData = ref([]) //附件
const normalForm = ref({
  xfsj: timeValidate(),
  sbsj: timeValidate(),
  rwztmc: '正常',
  rwzt: 0,
  ssbmdm: JSON.parse(window.localStorage.getItem("userInfo")).deptList[0].deptCode
});
const sbsj = timeValidate()
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 sbTpIdList = ref([]);
const isLoading = ref(false)
const fileBoxs = ref([]) //附件其他类型
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(',')
    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 ? res.xfzp.split(',') : []
    fileList.value = []
    wpTpIdList.value = []
    ids.forEach(item => {
      wpTpIdList.value.push(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)
    });

    fjData.value = []
    fileBoxs.value = []
    sbTpIdList.value = []
    let fjarr = res.sbfj ? JSON.parse(res.sbfj) : [];
    let imgType = ['image/png', 'image/jpeg', 'image/jpg']
    fjarr.forEach(item => {
      sbTpIdList.value.push(item)
      if (imgType.includes(item.type)) {
        let img1 = baseUrl2 + "/mosty-api/mosty-base/minio/image/download/" + item.id;
        let obj1 = {
          url: img1,
          codeId: item.id,
          isImage: true,
          status: "done",
          message: "上传成功",
        };
        fjData.value.push(obj1)
      } else {
        fileBoxs.value.push(item)
      }
    })
    normalForm.value = res;
    setTimeout(() => {
      D_SB_SBLX.value.forEach((element) => {
        if (element.dm == res.sblx) normalForm.value.sblxmc = element.text;
      });
      D_BZ_XFLX.value.forEach((element) => {
        if (element.dm == res.xflx) normalForm.value.xflxmc = element.text;
      });
      D_BZ_RWZT.value.forEach((element) => {
        if (element.dm == res.rwzt) normalForm.value.rwztmc = element.text;
      });
    }, 500)
  });
}

// 删除其他文件
function deletDate(it, idex) {
  fileBoxs.value.splice(idex, 1)
  let index = sbTpIdList.value.findIndex(item => {
    return item.id == it.id
  })
  if (index != -1) sbTpIdList.value.splice(index, 1)
}

// 打开弹窗
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;
    case "sblx":
      columns.value = D_SB_SBLX.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;
    case "sblx":
      normalForm.value.sblx = val.dm;
      normalForm.value.sblxmc = val.zdmc;
      break;
  }
}

// 删除神宝宝附件
const beforeDeletefJ = (url, val) => {
  fjData.value.splice(val.index, 1)
  let index = sbTpIdList.value.findIndex(item => {
    return item.id == url.codeId
  })
  if (index != -1) sbTpIdList.value.splice(index, 1)
}

// 申报附件
async function afterReadFjsb(file) {
  file.message = "上传中...";
  let imgType = ['image/png', 'image/jpeg', 'image/jpg']
  let type = file.file.type;
  const data = new FormData();
  if (imgType.includes(type)) {
    let fileBlob = await _compressImage(file.file);
    let fileData = new File([fileBlob], fileBlob.name, { type: fileBlob.type });
    data.append("file", fileData);
  } else {
    data.append("file", file.file);
  }
  file.status = "uploading";
  upImage(data).then((res) => {
    file.status = "done";
    file.message = "上传成功";
    sbTpIdList.value.push({ id: res, type: type, name: file.file.name });
  });
}

// 删除照片上传
const deleteFj = (url, val) => {
  fileList.value.splice(val.index, 1)
  wpTpIdList.value.splice(val.index, 1)
}

// 文件预览
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),
  }
  params.xfzp = wpTpIdList.value.join(',')
  params.sbfj = JSON.stringify(sbTpIdList.value)
  isLoading.value = true;
  if (title.value == '编辑战果申报') {
    eidtRw(params).then(res => {
      hintToast('编辑成功')
      router.go(-1);
    }).catch(() => {
      isLoading.value = false
    })
  } else {
    addRw(params).then(res => {
      hintToast('新增成功')
      router.go(-1);
    }).catch(() => {
      isLoading.value = false
    })
  }
}
</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;

      .itemlabel {
        height: 30px;
        line-height: 30px;
        font-size: 14px;
        color: #646566;
      }

      .mark {
        margin: 0 10px;
        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;

  .listitem {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4vw;
    font-size: 16px;

    .name {
      color: blue;
    }
  }
}
</style>