
<template>
  <BaseDialog
    :dialogVisible="props.visible"
    @close="onclone"
    :titleName="'新增' + tabsTitle"
    width="50%"
    @onSubmit="handleSubmit"
    :footerclosed="true"
    :diafooter="true"
    :footerkeepnaem="props.readonly ? false : true"
  >
    <div class="detailForm-content">
      <el-form
        ref="formRef"
        label-position="right"
        label-width="150px"
        :rules="ruleForm"
        :model="form"
      >
      <el-form-item label="动态标题：" prop="title" style="width: 100%;">
          <el-input
            placeholder="请输入动态标题"
            v-model="form.title"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="动态内容：" prop="detail" style="width: 100%;">
          <el-input
            placeholder="请输入动态内容"
            v-model="form.detail"
            :rows="3"
            type="textarea"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="时间：" prop="time">
          <el-date-picker
            v-model="form.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            size="default"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="类型：" prop="typeId">
          <el-select
            v-model="form.typeId"
            placeholder="请选择类型"
            style="width: 240px;"
          >
            <el-option
              v-for="item in option"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作附件：" style="width: 100%;">
          <el-upload
            class="avatar-uploader"
            ref="uploadAfter"
            action="#"
            list-type="upload-demo"
            :file-list="afterList"
            :http-request="handleUploadAfter"
          >
            <el-icon class="avatar-uploader-icon" :size="40">
              <Plus />
            </el-icon>
            <template #file="{ file }">
              <div>
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview">
                    <el-icon>
                      <Document />
                    </el-icon>
                    <span>{{ file.realfilename }}</span>
                  </span>
                  <span
                    class="el-upload-list__item-preview"
                    @click="handleInfo(file)"
                  >
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span
                    class="el-upload-list__item-preview"
                    @click="handleDownload(file)"
                  >
                    <el-icon>
                      <Download />
                    </el-icon>
                  </span>
                  <span
                    class="el-upload-list__item-preview"
                    @click="handleRemove(file)"
                  >
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-dialog v-model="upVisible">
        <img w-full :src="upImageUrl" alt="Preview Image" />
      </el-dialog>
    </div>
  </BaseDialog>
</template>
<script setup lang="ts" >
import { reactive, ref, onMounted, watch, getCurrentInstance } from "vue";
import useUserStore from "@/store/modules/user";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import type { UploadUserFile } from "element-plus";
import { getYears, getUUID, FileType } from "@/utils/common";
import { uploadFile, getFile, delFile } from "@/api/file";
import { getListperformTree } from "@/api/Sys";
import { wkDynamicsAdd,wkTypes } from "@/api/Work";

const formRef = ref<FormInstance>();
const userStore = useUserStore();
const user = ref(JSON.parse(userStore.userInfo));
const userId = ref(user.value.userId);
const uuid = ref(getUUID());
const ruleForm = reactive<FormRules>({
  detail: [
    {
      required: true,
      message: "请输入动态内容",
      trigger: "blur",
    },
  ],
  processedBy: [
    {
      required: true,
      message: "请输入处理人",
      trigger: "blur",
    },
  ],
  time: [
    {
      required: true,
      message: "请选择时间",
      trigger: "blur",
    },
  ],
  title:[
  {
      required: true,
      message: "请输入动态标题",
      trigger: "blur",
    },
  ],
  typeId:[
    {
      required: true,
      message: "请选择动态类型",
      trigger: "change",
    }
  ]
});
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  form: Object,
  readonly: {
    type: Boolean,
    default: false,
  },
  id: {
    type: String,
  }
});
const form = ref(<any>{});
  const tabsTitle = ref('工作动态')
const emits = defineEmits(["close", "onSubmit"]);
//保存并退出
const handleSubmit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      let params = {
        dynamicsId:uuid.value,
        detail: form.value.detail,
        title: form.value.title,
        typeId: form.value.typeId,
        userId: userId.value,
        startTime: form.value.time[0],
        endTime: form.value.time[1],
        targetId:props.id,
      };
      wkDynamicsAdd(params).then((res: any) => {
        if (res.code == 1) {
          ElMessage.success({
            message: "保存成功",
            type: "success",
          });
          onclone();
        } else {
          ElMessage.error({
            message: res.message,
            type: "error",
          });
        }
      });
    }
    return false;
  });
};
// 文件上传
const afterList = ref<UploadUserFile[]>([]);
const handleUploadAfter = (file: any) => {
    const newFile = new FormData();
    newFile.append("file", file.file);
    uploadFile(userId.value,uuid.value, FileType.resumptionAcs, newFile).then((res) => {
    	if (res) {
    		ElMessage.success("上传成功！");
    		getCheckDangers(uuid.value)
    	}
    })
  
};
//文件显示
const baseImgUrl = ref(import.meta.env.VITE_UPLOAD_URL);
const getCheckDangers = (id) => {
  getFile(
  	id,
  	FileType.resumptionAcs
  ).then((res: any) => {
  	afterList.value = res.data.map(item => {
  		let arr = item;
  		let index = item.filepath.indexOf(".");//获取第一个"_"的位置
  		let after1 = item.filepath.substring(index + 1);
  		switch (after1) {
  			case 'xlsx':
  				arr.url = 'src/assets/images/exl.png';
  				break;
  			case 'exl':
  				arr.url = 'src/assets/images/exl.png';
  				break;
  			case 'pdf':
  				arr.url = 'src/assets/images/pdf.png';
  				break;
  			case 'word':
  				arr.url = 'src/assets/images/word.png';
  				break;
  			default:
  				arr.url = baseImgUrl.value + item.filepath;
  				break;
  		}
  		return arr;
  	});
  })
};
//删除附件
const handleRemove = (file) => {
  delFile(file.sysdocumentid).then((res: any) => {
    if (res) {
    		ElMessage.success("删除成功！");
    	}
  	getCheckDangers(uuid.value);
  })
};
//下载附件
const handleDownload = (file) => {
  function text() {
    const x = new XMLHttpRequest();
    x.open("GET", baseImgUrl.value + file.filepath, true);
    x.responseType = "blob";
    x.onload = function () {
      const url = window.URL.createObjectURL(x.response);
      const a = document.createElement("a");
      a.href = url;
      a.download = file.name;
      a.click();
    };
    x.send();
  }
  let index = file.filepath.indexOf("."); //获取第一个"_"的位置
  let after1 = file.filepath.substring(index + 1);
  switch (after1) {
    case "xlsx":
      text();
      break;
    case "exl":
      text();
      break;
    case "pdf":
      text();
      break;
    case "word":
      text();
      break;
    default:
      window.open(baseImgUrl.value + file.filepath, "_blank");
      break;
  }
};
const upVisible = ref(false);
const upImageUrl = ref("");
//查看附件
const handleInfo = (file) => {
  upImageUrl.value = file.url!;
  upVisible.value = true;
};
//关闭弹窗
const onclone = () => {
  afterList.value = [];
  form.value = {};
  emits("close");
};
//获取类型
const option = ref([])
const getWkTypes = () => {
  let params = {
    classify: 2,
  };
  wkTypes(params).then((res: any) => {
    option.value = res.data;
  });
};


onMounted(() => {});
watch(
  () => props.id,
  (val) => {
    uuid.value = getUUID();
    getWkTypes();
  }
);
</script>

<style lang="scss" scoped>
.detailForm-content {
    margin-right: 30px;
}
:deep(.el-form) {
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-around;
    justify-content: space-between;
}
:deep(.el-form-item) {
    width: 47%;
}
::v-deep(.el-upload-list__item-actions) {
    display: flex;
    > span:nth-child(2) {
        margin-left: 10px;
    }
}
::v-deep(.el-upload-list__item-preview) {
    margin-right: 10px;
    display: flex;
    align-items: center;
    > span {
        margin-left: 10px;
    }
}
::v-deep(.avatar-uploader-icon) {
    width: 100px;
    height: 100px;
}
</style>