<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="160px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="约谈数量" prop="interviewCount" class="long-label-item">
              <el-input-number v-model="formData.interviewCount" placeholder="请输入约谈数量"
                        controls-position="right"
                        :min="0"
                        :max="999999"
                        :step="1"
                        style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="书面检查数量" prop="writtenExaminationCount" class="long-label-item">
              <el-input-number v-model="formData.writtenExaminationCount" placeholder="请输入书面检查数量"
                               controls-position="right"
                        :min="0"
                        :max="999999"
                        :step="1"
                        style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="通报批评数量" prop="criticismCount" class="long-label-item">
              <el-input-number v-model="formData.criticismCount" placeholder="请输入通报批评数量"
                               controls-position="right"
                        :min="0"
                        :max="999999"
                        :step="1"
                        style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="警告或记过处分数量" prop="warningCount" class="long-label-item">
              <el-input-number v-model="formData.warningCount" placeholder="请输入警告或记过处分数量"
                               controls-position="right"
                        :min="0"
                        :max="999999"
                        :step="1"
                        style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="调离岗位或免职数量" prop="dismissalCount" class="long-label-item">
              <el-input-number v-model="formData.dismissalCount" placeholder="请输入调离岗位或免职数量"
                               controls-position="right"
                        :min="0"
                        :max="999999"
                        :step="1"
                        style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他数量" prop="otherCount" class="long-label-item">
              <el-input-number v-model="formData.otherCount" placeholder="请输入其他数量"
                               controls-position="right"
                        :min="0"
                        :max="999999"
                        :step="1"
                        style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上报人" prop="reporterName" class="long-label-item">
              <el-input v-model="formData.reporterName" placeholder="请输入上报人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上报人电话" prop="reporterPhone" class="long-label-item">
              <el-input v-model="formData.reporterPhone" placeholder="请输入上报人电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属季度" prop="quarter" class="long-label-item">
              <el-select v-model="formData.quarter" placeholder="请选择所属季度">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.TRS_QUARTER)"
                           :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">
            <el-form-item label="上报时间" prop="reportTime" class="long-label-item">
              <el-date-picker clearable v-model="formData.reportTime" type="datetime"
                              value-format="timestamp" placeholder="选择上报时间" />
            </el-form-item>
          </el-col>-->
        </el-row>



        <el-col :span="24">
          <el-form-item label="整改报告" prop="attachment">
            <FileUpload v-model="formData.attachment"
                        :file-size="uploadConfig.fileSize"
                        :file-type="uploadConfig.fileType"
                        :limit="uploadConfig.limit"
                        :required="uploadConfig.required"/>
<!--            <FileUpload v-model="formData.attachment"
                        :file-size="15"
                        :file-type="['doc', 'docx', 'wps']"
                        :limit="1"
                        :required="true"/>-->
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注信息" prop="reportRemark">
            <el-input
              v-model="formData.reportRemark"
              placeholder="请输入备注信息"
              type="textarea"
              :rows="3" />
          </el-form-item>
        </el-col>
        </el-row>
      </el-form>
              <div slot="footer" class="dialog-footer">
<!--        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>-->
        <el-button type="primary" @click="submitForm(false)" :disabled="formLoading">保 存</el-button>
        <el-button type="success" @click="submitForm(true)" :disabled="formLoading">保存并上报</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as RectifyInfoReportApi from '@/api/server/rectifyinforeport';
  import FileUpload from '@/components/FileUpload';
  import {getFileForConfigPage} from "@/api/server/fileforconfig";
      export default {
    name: "RectifyInfoReportForm",
    components: {
          FileUpload,
                    },
    data() {
      return {
        // 弹出层标题
        dialogTitle: "",
        // 是否显示弹出层
        dialogVisible: false,
        // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
        formLoading: false,
        // 表单参数
        formData: {
                            id: undefined,
                            interviewCount: undefined,
                            writtenExaminationCount: undefined,
                            criticismCount: undefined,
                            warningCount: undefined,
                            dismissalCount: undefined,
                            otherCount: undefined,
                            quarter: undefined,
                            reporterName: undefined,
                            reporterPhone: undefined,
                            reportTime: new Date().getTime(), // 默认当前时间
                            departmentId: undefined,
                            reportStatus: undefined,
                            reportRemark: undefined,
                            attachment: undefined,
        },
        // 表单校验
        formRules: {
          interviewCount: [{ required: true, message: '约谈数量不能为空', trigger: 'blur' }],
          writtenExaminationCount: [{ required: true, message: '书面检查数量不能为空', trigger: 'blur' }],
          criticismCount: [{ required: true, message: '通报批评数量不能为空', trigger: 'blur' }],
          warningCount: [{ required: true, message: '警告或记过处分数量不能为空', trigger: 'blur' }],
          dismissalCount: [{ required: true, message: '调离岗位或免职数量不能为空', trigger: 'blur' }],
          otherCount: [{ required: true, message: '其他数量不能为空', trigger: 'blur' }],
          quarter: [{ required: true, message: '所属季度不能为空', trigger: 'blur' }],
          reporterName: [{ required: true, message: '上报人不能为空', trigger: 'blur' }],
          reporterPhone: [{ required: true, message: '上报人电话不能为空', trigger: 'blur' }],
          reportTime: [{ required: true, message: '上报时间不能为空', trigger: 'blur' }],
          attachment: [{required: true, message: '附件不能为空', trigger: 'blur'}]

        },
        // 文件上传配置
        uploadConfig: {
          fileSize: 1, // 默认值，单位MB
          fileType: ['doc', 'docx', 'wps', 'pdf'], // 默认文件类型
          limit: 1, // 默认限制数量
          required: true // 默认必填
        }
                        };
    },
    methods: {
      /** 获取文件上传配置 */
      async fetchUploadConfig() {
        try {
          // 假设通过分页接口获取所有配置，然后根据配置键筛选
          const params = {
            pageNo: 1,
            pageSize: 100 // 获取足够多的配置
          };
          const res = await getFileForConfigPage(params);
          const configs = res.data.list;
          // 假设配置键为 'harmful_info_report_upload'
          const config = configs.find(item => item.configKey === 'RectifyInfoReport');
          if (config) {
            // 假设配置值是一个JSON字符串，包含fileSize, fileType, limit, required等属性
            this.uploadConfig = {
              fileSize: config.fileMaxSize || 15, // 使用 fileMaxSize
              fileType: config.fileTypes ? config.fileTypes.split(',') : ['doc', 'docx', 'wps', 'pdf'], // 将字符串转换为数组
              limit: config.fileMaxCount || 1, // 使用 fileMaxCount
              required: config.fileOther=='true' || true // 默认true
            };
          }
        } catch (error) {
          console.error('获取文件上传配置失败', error);
          // 使用默认配置
        }
      },
      isSuperAdmin() {
        // 获取当前用户角色信息
        const userInfo = this.$store.state.user;
        const roles = userInfo.roles || []; // 假设角色信息存储在roles数组中
        // 如果用户有超管角色（id是1），则返回true
        if (roles.includes("super_admin") ) {
          return true;
        }else{
          return false;
        }
      },
      /** 打开弹窗 */
     async open(id) {
        await this.fetchUploadConfig(); // 获取文件上传配置
        this.dialogVisible = true;
        this.reset();
        // 修改时，设置数据
        if (id) {
          this.formLoading = true;
          try {
            const res = await RectifyInfoReportApi.getRectifyInfoReport(id);
            this.formData = res.data;
            this.title = "修改整改结果";
          } finally {
            this.formLoading = false;
          }
        }
        this.title = "新增整改结果";
              },
      /** 提交按钮 */
      /** 提交按钮 */
      async submitForm(isReport = false) {
        await this.$refs["formRef"].validate();
        this.formLoading = true;

        try {
          const data = this.formData;
          let reportId = data.id;

          // 保存数据
          if (data.id) {
            await RectifyInfoReportApi.updateRectifyInfoReport(data);
            this.$modal.msgSuccess("修改成功");
          } else {
            const res = await RectifyInfoReportApi.createRectifyInfoReport(data);
            reportId = res.data;
            this.$modal.msgSuccess("新增成功");
          }

          // 如果需要上报
          if (isReport) {
            try {
              await RectifyInfoReportApi.reportRectifyInfoReport(reportId);
              this.$modal.msgSuccess("上报成功");
            } catch (error) {
              console.error('上报失败:', error);
              this.$modal.msgError("上报失败");
            }
          }

          this.dialogVisible = false;
          this.$emit('success');

        } catch (error) {
          console.error('保存失败:', error);
          this.$modal.msgError("保存失败");
        } finally {
          this.formLoading = false;
        }
      },
                      /** 表单重置 */
      reset() {
        this.formData = {
                            id: undefined,
                            interviewCount: undefined,
                            writtenExaminationCount: undefined,
                            criticismCount: undefined,
                            warningCount: undefined,
                            dismissalCount: undefined,
                            otherCount: undefined,
                            quarter: undefined,
                            reporterName: undefined,
                            reporterPhone: undefined,
                            reportTime: new Date().getTime(), // 默认当前时间
                            departmentId: undefined,
                            reportStatus: undefined,
                            reportRemark: undefined,
                            attachment: undefined,
        };
        this.resetForm("formRef");
      }
    }
  };
</script>
<style scoped>
.long-label-item >>> .el-form-item__content {
  display: flex;
}
.long-label-item >>> .el-input-number {
  flex: 1;
  min-width: 180px;
}
</style>
