<!-- 外层新增弹出框 -->
<template>
  <div>
    <el-dialog v-model="props.diaShow" :title="props.title" label-width="120px" :before-close="handleClose"
      width="800px" draggable>
      <el-form ref="ruleFormRef" :model="dialogForm" :rules="rules">
        <el-form-item label="标题" prop="titleName">
          <el-input placeholder="请输入标题" disabled v-model="dialogForm.titleName" clearable></el-input>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-select v-model="dialogForm.year" filterable @change="changeData">
            <el-option v-for="item in filterYear(3)" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="层级" prop="type">
          <el-select v-model="dialogForm.type" filterable @change="changeData">
            <el-option v-for="item in props.dict.D_BZ_WORKTYPE" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="yearType">
          <el-select v-model="dialogForm.yearType" filterable @change="changeData">
            <el-option v-for="item in props.dict.D_BZ_WORD_YEAR_TYPE" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="附件" prop="fileName">
          <el-input placeholder="请上传纯文本docx文件" disabled v-model="dialogForm.fileName" clearable>
            <template #append>
              <el-button @click="clickBtn">上传附件</el-button>
            </template>
          </el-input>
          <input id="inputFile" accept=".docx" type="file" @change="changeFile" ref="inputFile" style="display: none;">
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSave(ruleFormRef)" v-loading="loading">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button type="primary" @click="handleClose">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
// 引入
import { ref, defineProps, defineEmits, reactive, watch, nextTick, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import { uploadfilApi } from "@/api/tobAcco_api.js";
import { getItem } from "@/utils/storage";
import { filterYear } from "@/utils/auth.js";
const { proxy } = getCurrentInstance();
const inputFile = ref(null)
const ruleFormRef = ref()
const fileType = ref('')
const loading = ref(false)
const rules = reactive({
  year: [{ required: true, message: "年份不能为空", trigger: "blur" }],
  titleName: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  type: [{ trigger: "blur", required: true, message: "层级不能为空", }],
  fileName: [{ trigger: "blur", required: true, message: "附件不能为空", }],
  yearType: [{ trigger: "blur", required: true, message: "类型不能为空", }],
});
const emits = defineEmits(["close"]);
// 数据
const dialogForm = ref({
  year: new Date().getFullYear(),
});
const props = defineProps({
  diaShow: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ""
  },
  dict: Array
});
watch(
  () => props.diaShow,
  (val) => {
    if (val) {
      inputFile.value = null;
      dialogForm.value.year = new Date().getFullYear()
      dialogForm.value.fileName = null
      dialogForm.value.orgcode = getItem('deptId').ssdwid
      dialogForm.value.orgname = getItem('deptId').ssdwmc
      dialogForm.value.titleName = `${dialogForm.value.orgname}${dialogForm.value.year}年安全生产工作总结（报告）`
      dialogForm.value.type = ''
      dialogForm.value.yearType = '';
      nextTick(() => {
        if (ruleFormRef.value) ruleFormRef.value.clearValidate()
      })
    }
  }
)
// 切换各种选项
const changeData = () => {
  let yearTypeName = dialogForm.value.yearType == '1' ? '上半年' : '年';
  let typeName = dialogForm.value.type == '1' ? '' : '（本级）';
  dialogForm.value.titleName = `${dialogForm.value.orgname}${typeName}${dialogForm.value.year}${yearTypeName}安全生产工作总结（报告）`
}
// 点击上传文件
const clickBtn = () => {
  document.getElementById("inputFile").click()
}
// 文件切换
const changeFile = (e) => {
  const file = e.target.files[0];
  if (file) {
    dialogForm.value.fileName = file.name;
    fileType.value = file.name.split('.').pop().toLowerCase();
    if (fileType.value != 'docx') {
      ElMessage.warning("请上传 docx 文件!!!");
      e.target.value = '';
    }
  }
  dialogForm.value.file = inputFile.value.files[0]
  ruleFormRef.value.validateField('fileName');
}
// 保存
const handleSave = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      let data = new FormData();
      if (inputFile.value.files && inputFile.value.files[0]) {
        data.append("file", inputFile.value.files[0]);
      }
      data.append("titleName", dialogForm.value.titleName);
      data.append("year", dialogForm.value.year);
      data.append("type", dialogForm.value.type);
      data.append("yearType", dialogForm.value.yearType);
      uploadfilApi(data, '/mosty-jcgl/worksummary/addWorkSummary').then(() => {
        ElMessage.success("上传成功");
        inputFile.value.value = ''
        loading.value = false
        emits("close", false);
      }).catch(() => {
        loading.value = false
      })
    } else {
      ElMessage.warning('请输入必填项！！！')
      loading.value = false
    }
  })
};
// 关闭
const handleClose = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      emits("close", false);
    })
    .catch(() => {
      // catch error
    })

};
</script>

<style lang="scss" scoped>
.el-form-item {
  width: 100%;
}

.el-form {
  flex-wrap: wrap;
}

.el-range-editor.el-input__inner {
  width: 100%;
}

::v-deep .el-dialog__body {
  height: 30vh !important;
}
</style>