<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.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><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 v-if="clickType == 'sblx'" :columns="columns" @cancel="isShowCommonPicker = false"
        @confirm="onConfirm" />
    </van-popup>
  </div>
</template>
<script setup>
import { baseUrl2 } from "@/utils/request.js";
import { upImage } from "@/api/common";
import ImageCompressor from "image-compressor.js";
import TopNav from "../../../components/topNav.vue";
import { getDictList, setDict } from "@/utils/dict";
import { timeValidate ,hintToast} from "@/utils/tools.js";
import { zgDetail, editDataZg, addDataZg } from "../../../api/xfgl.js";
import { useRouter, useRoute } from "vue-router";
import { ref, onMounted, reactive, defineProps } from "vue";
const urlImg = `${baseUrl2}/mosty-api/mosty-base/minio/image/download/`;
const { D_SB_SBLX } = getDictList("D_SB_SBLX");
const route = useRoute();
const router = useRouter();
const message = ref("");
const normalForm = ref({
  sbsj:timeValidate(),
  ssbmdm:JSON.parse(window.localStorage.getItem("userInfo")).deptList[0].deptCode
});
const isLoading = ref(false)
const isShowCommonPicker = ref(false);
const clickType = ref('');
const columns = ref([]);
const fileList = ref([])
const wpTpIdList = ref([])
const title = ref('')
onMounted(()=>{
   title.value = route.query.id ? "编辑战果申报" : "新增战果申报";
  if (route.query.id) {
   _getDetailById(); //根据id获取详情
  }
})
//根据id获取详情
function _getDetailById() {
  zgDetail(route.query.id).then((res) => {
    D_SB_SBLX.value.forEach((element) => {
      if (element.dm == res.sblx) res.sblxmc = element.text;
    });
    let ids = res.sbfjid.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 "sblx":
      columns.value = D_SB_SBLX.value;
      break;
  }
  isShowCommonPicker.value = true;
}

// 确定选择
function onConfirm(val) {
  isShowCommonPicker.value = false;
  switch (clickType.value) {
    case "sblx":
      normalForm.value.sblx = val.dm;
      normalForm.value.sblxmc = val.zdmc;
      break;
  }
}

// 提交
function onSubmit(){
  let params = { ...normalForm.value }
  delete params.sblxmc
  let ids1 = fileList.value.filter(item=>{return item.codeId}).map(v=>{return v.codeId})
  let ids2 = wpTpIdList.value.join(',')
  params.sbfjid = (ids1.concat(ids2)).join(',')
  
  isLoading.value = true;
  if(title.value == '编辑战果申报'){
    editDataZg(params).then(res=>{
      hintToast('编辑成功')
      router.go(-1);
    })
  }else{
    addDataZg(params).then(res=>{
      hintToast('新增成功')
      router.go(-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);
      },
    });
  });
};

</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;
      height: 8vw;
      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: 50%;
      transform: translateY(-50%);
      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;
    }
  }
}

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

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