<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="140px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="网站删除条数" prop="website">
              <el-input-number
                v-model="formData.website"
                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="newMedia">
              <el-input-number
                v-model="formData.newMedia"
                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="quarter">
              <el-select v-model="formData.quarter" placeholder="请选择所属季度" style="width: 100%">
                <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="internalNetwork">
              <el-select v-model="formData.internalNetwork" placeholder="请选择内网/专网" style="width: 100%">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.TRS_INTERNAL_NETWORK)"
                           :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="reporterName">
              <el-input v-model="formData.reporterName" placeholder="请输入报送人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报送人电话" prop="reporterPhone">
              <el-input v-model="formData.reporterPhone" placeholder="请输入报送人电话" />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-show=isSuperAdmin()>
            <el-form-item label="上报人类型" prop="reporterType">
              <el-radio-group v-model="formData.reporterType">
                <el-radio
                  v-for="dict in this.getDictDatas(DICT_TYPE.TRS_REPORTER_TYPE)"
                  :key="dict.value"
                  :label="dict.value"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">
            <el-form-item label="报送时间" prop="reportTime">
              <el-date-picker
                clearable
                v-model="formData.reportTime"
                type="datetime"
                value-format="timestamp"
                placeholder="选择报送时间"
                style="width: 100%" />
            </el-form-item>
          </el-col>-->

<!--          <el-col :span="24">
            <el-form-item label="上报附件" prop="attachment">
              <FileUpload v-model="formData.attachment"
                          :file-size="15"
                          :file-type="['doc', 'docx', 'wps', 'pdf']"
                          :limit="1"
                          :required="true"/>
            </el-form-item>
          </el-col>-->
          <el-col :span="24">
            <el-form-item  prop="attachment">
              <template #label>
                <span>情况说明附件<br/>(加盖公章)</span>
              </template>
              <FileUpload v-model="formData.attachment"
                          :file-size="uploadConfig.fileSize"
                          :file-type="uploadConfig.fileType"
                          :limit="uploadConfig.limit"
                          :required="uploadConfig.required"
                          :show-download-template="true"
                          :show-preview="true"
                          @download-template="downloadTemplate"/>
            </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-item v-show="false" label="总数" prop="totalCount">
          <el-input v-model="formData.totalCount" placeholder="自动计算总删除条数" :disabled="true" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <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 HarmfulInfoReportApi from '@/api/server/harmfulinforeport';
import FileUpload from '@/components/FileUpload';
import {downloadTemplate, getFileForConfigPage} from '@/api/server/fileforconfig'; // 引入文件配置分页API
export default {
  name: "HarmfulInfoReportForm",
  components: {
    FileUpload,
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        website: undefined,
        newMedia: undefined,
        internalNetwork: undefined,
        totalCount: undefined,
        quarter: undefined,
        reporterName: undefined,
        reporterType: '自治区政府部门', // 默认选择部门
        reporterPhone: undefined,
        reportTime: new Date().getTime(), // 默认当前时间
        departmentId: undefined,
        reportStatus: undefined,
        reportRemark: undefined,
        attachment: undefined,
      },
      // 表单校验
      formRules: {
        website: [{ required: true, message: '网站删除条数不能为空', trigger: 'blur' }],
        newMedia: [{ required: true, message: '新媒体删除条数不能为空', trigger: 'blur' }],
        quarter: [{ required: true, message: '所属季度不能为空', trigger: 'blur' }],
        //reporterType: [{ 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 downloadTemplate() {
      try {
        // 显示加载提示
        this.$message.success('模板下载中...');

        // 直接调用后端API
        const response = await downloadTemplate();

        // 方法1: 创建blob对象下载
        const blob = new Blob([response], {
          type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        });

        const downloadUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = '有害信息报送模板.docx';
        link.style.display = 'none';

        document.body.appendChild(link);
        link.click();

        // 清理
        setTimeout(() => {
          window.URL.revokeObjectURL(downloadUrl);
          document.body.removeChild(link);
          this.$message.success('模板下载完成');
        }, 100);

      } catch (error) {
        console.error('下载失败:', error);
        this.$message.error('模板下载失败');
      }
    },
    /** 下载模板 */
/*    downloadTemplate() {
      // 这里调用下载模板的API
      // 例如：HarmfulInfoReportApi.downloadTemplate()
      this.$message.success('模板下载中...');

      // 或者直接下载静态文件
      const templateUrl = '/template/有害信息报送模板.docx'; // 你的模板文件路径
      const link = document.createElement('a');
      link.href = templateUrl;
      link.download = '情况说明模板.docx';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },*/
    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 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 === 'HarmfulInfoReport');
        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);
        // 使用默认配置
      }
    },
    /** 计算总数 */
    calculateTotal() {
      const website = Number(this.formData.website) || 0;
      const newMedia = Number(this.formData.newMedia) || 0;
      this.formData.totalCount = website + newMedia;
    },
    /** 打开弹窗 */
    async open(id) {
      await this.fetchUploadConfig(); // 获取文件上传配置
      this.dialogVisible = true;
      this.reset();
      this.calculateTotal();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await HarmfulInfoReportApi.getHarmfulInfoReport(id);
          this.formData = res.data;
          this.calculateTotal();
          this.dialogTitle = "修改信息上报";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增信息上报";
      }
    },
    /** 提交按钮 */
    async submitForm(isReport = false) {
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        this.calculateTotal();
        const data = this.formData;
        let reportId = data.id;
        if (data.id) {
          await HarmfulInfoReportApi.updateHarmfulInfoReport(data);
          this.$modal.msgSuccess("修改成功");
        } else {
          const res = await HarmfulInfoReportApi.createHarmfulInfoReport(data);
          reportId = res.data;
          this.$modal.msgSuccess("新增成功");
        }

        // 如果需要上报
        if (isReport) {
          // 如果是新增，需要重新获取ID
          //const reportId = data.id || (await this.getLatestId(data));
          await HarmfulInfoReportApi.reportHarmfulInfoReport(reportId);
          this.$modal.msgSuccess("上报成功");
        }

        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },


    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        website: undefined,
        newMedia: undefined,
        internalNetwork: undefined,
        totalCount: undefined,
        quarter: undefined,
        reporterName: undefined,
        reporterType: '自治区政府部门', // 重置时也默认选择部门
        reporterPhone: undefined,
        reportTime: new Date().getTime(), // 重置时也设置为当前时间
        departmentId: undefined,
        reportStatus: undefined,
        reportRemark: undefined,
        attachment: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>

<style scoped>
.el-radio {
  margin-right: 15px;
}
</style>
