<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-form-item label="汇报主题" prop="reportTopic">
          <el-input v-model="formData.reportTopic" placeholder="请输入汇报主题"/>
        </el-form-item>
        <el-form-item label="汇报时间" prop="reportTime">
          <el-date-picker
              v-model="formData.reportTime"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="汇报给" prop="reportTos">
          <el-select v-model="formData.reportTos" multiple placeholder="请选择">
            <el-option
                v-for="item in reportTo"
                :key="item.id"
                :label="item.nickname"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="汇报内容" prop="reportContent">
          <el-input type="textarea" v-model="formData.reportContent" :autosize="{ minRows: 6, maxRows: 10 }"/>
        </el-form-item>
        <el-form-item label="汇报附件" prop="reportFiles">
          <insp-file-upload
              :fileSize="30"
              :fileType="['doc', 'xls', 'ppt', 'txt', 'pdf','png','jpg','jpeg','gif','docx','xlsx','pptx','wps']"
              v-model="formData.filePath"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as ReportApi from '@/views/inspection/workReport/api/index';
import Editor from '@/components/Editor';
import {getReportTo} from "@/views/inspection/workReport/api/index";
import {formatDate} from "@/utils";
import inspFileUpload from "@/components/FileUpload/index.vue";

export default {
  name: "ReportForm",
  components: {
    inspFileUpload,
    Editor,
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 汇报对象
      reportTo: [],
      // 表单参数
      formData: {
        id: undefined,
        reportTopic: undefined,
        reportTime: undefined,
        reportContent: undefined,
        servicePackageId: undefined,
        reportTos: [],
      },
      // 表单校验
      formRules: {
        reportTopic: [{required: true, message: '汇报主题不能为空', trigger: 'blur'}],
        reportTime: [{required: true, message: '汇报时间不能为空', trigger: 'blur'}],
        reportContent: [{required: true, message: '汇报内容不能为空', trigger: 'blur'}],
        reportTos: [{required: true, message: '汇报给不能为空', trigger: 'blur'}],
      },
    };
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      this.getReportTo()
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await ReportApi.getReport(id);
          this.formData = res.data;
          this.dialogTitle = "修改工作汇报";
          //将字符串转为数组
          this.formData.filePath = this.formData.filePath.split(",");
          console.log(this.formData)
          console.log(this.formData.filePath)
        } finally {
          this.formLoading = false;
        }
      }else {
        this.setDefaultData();
        this.dialogTitle = "新增工作汇报";
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await ReportApi.updateReport(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        data.reportTime = this.formData.reportTime.getTime();
        await ReportApi.createReport(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        reportTopic: undefined,
        reportTime: undefined,
        reportContent: undefined,
      };
      this.resetForm("formRef");
    },
    /** 设置默认数据 */
    setDefaultData() {
      this.formData.reportTime = new Date();
      this.formData.servicePackageId = "jiance";
    },
    /** 获取汇报对象 */
    getReportTo() {
      const data = {
        dictType: "ins_report_role"
      }
      getReportTo(data).then(response => {
        this.reportTo = response.data;
      });
    },
    /** 格式化时间（yyyy-MM-dd HH:mm:ss） */
    formatDateTime(date) {
      if (!date) return null;
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      const seconds = String(d.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  }
};
</script>
