<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="案例类型" prop="caseType">
        <el-input
          v-model="queryParams.caseType"
          placeholder="请输入案例类型"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="案例名称" prop="caseName">
        <el-input
          v-model="queryParams.caseName"
          placeholder="请输入案例名称（支持模糊搜索）"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['flood:case:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['flood:case:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['flood:case:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['flood:case:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['flood:case:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="caseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="案例ID" align="center" prop="caseId" width="80" />
      <el-table-column label="案例类型" align="center" prop="caseType" width="120" />
      <el-table-column label="案例名称" align="center" prop="caseName" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="案例时间" align="center" prop="caseTime" width="150" />
      <el-table-column label="案例地点" align="center" prop="caseLocation" :show-overflow-tooltip="true" min-width="180" />
      <el-table-column label="洪峰流量" align="center" prop="peakFlow" width="120" :show-overflow-tooltip="true" v-if="hasPeakFlow" />
      <el-table-column label="经济损失" align="center" prop="economicLoss" width="150" :show-overflow-tooltip="true" v-if="hasEconomicLoss" />
      <el-table-column label="案例描述" align="center" prop="caseDescription" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['flood:case:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['flood:case:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['flood:case:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改洪水案例库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="案例类型" prop="caseType">
          <el-input v-model="form.caseType" placeholder="请输入案例类型" />
        </el-form-item>
        <el-form-item label="案例名称" prop="caseName">
          <el-input v-model="form.caseName" placeholder="请输入案例名称" />
        </el-form-item>
        <el-form-item label="案例时间" prop="caseTime">
          <el-input v-model="form.caseTime" placeholder="请输入案例时间" />
        </el-form-item>
        <el-form-item label="案例地点" prop="caseLocation">
          <el-input v-model="form.caseLocation" placeholder="请输入案例地点" />
        </el-form-item>
        <el-form-item label="案例描述" prop="caseDescription">
          <el-input v-model="form.caseDescription" type="textarea" :rows="4" placeholder="请输入案例描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的案例数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入"xls"或"xlsx"格式文件！每个sheet作为一个案例类型。</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 案例详情对话框 -->
    <el-dialog :title="'案例详情：' + (detailInfo.caseName || '')" :visible.sync="detailOpen" width="1200px" append-to-body>
      <el-descriptions :column="2" border v-if="detailInfo.caseId">
        <el-descriptions-item label="案例ID">{{ detailInfo.caseId }}</el-descriptions-item>
        <el-descriptions-item label="案例类型">{{ detailInfo.caseType }}</el-descriptions-item>
        <el-descriptions-item label="案例名称" :span="2">{{ detailInfo.caseName }}</el-descriptions-item>
        <el-descriptions-item label="案例时间">{{ detailInfo.caseTime || '无' }}</el-descriptions-item>
        <el-descriptions-item label="案例地点">{{ detailInfo.caseLocation || '无' }}</el-descriptions-item>
        <el-descriptions-item label="洪水成因" v-if="detailInfo.floodCause">{{ detailInfo.floodCause }}</el-descriptions-item>
        <el-descriptions-item label="洪峰流量" v-if="detailInfo.peakFlow">{{ detailInfo.peakFlow }}</el-descriptions-item>
        <el-descriptions-item label="降雨量" v-if="detailInfo.rainfall">{{ detailInfo.rainfall }}</el-descriptions-item>
        <el-descriptions-item label="持续时间" v-if="detailInfo.duration">{{ detailInfo.duration }}</el-descriptions-item>
        <el-descriptions-item label="经济损失" v-if="detailInfo.economicLoss" :span="2">
          <div v-html="formatDescription(detailInfo.economicLoss)"></div>
        </el-descriptions-item>
        <el-descriptions-item label="人员伤亡" v-if="detailInfo.casualties" :span="2">
          <div v-html="formatDescription(detailInfo.casualties)"></div>
        </el-descriptions-item>
        <el-descriptions-item label="受灾人口" v-if="detailInfo.affectedPopulation">{{ detailInfo.affectedPopulation }}</el-descriptions-item>
        <el-descriptions-item label="影响范围" v-if="detailInfo.affectedArea">{{ detailInfo.affectedArea }}</el-descriptions-item>
        <el-descriptions-item label="灾害类型" v-if="detailInfo.disasterType">{{ detailInfo.disasterType }}</el-descriptions-item>
        <el-descriptions-item label="流域" v-if="detailInfo.riverBasin">{{ detailInfo.riverBasin }}</el-descriptions-item>
        <el-descriptions-item label="洪水规模" v-if="detailInfo.floodScale">{{ detailInfo.floodScale }}</el-descriptions-item>
        <el-descriptions-item label="受灾人口" v-if="detailInfo.affectedPopulation">{{ detailInfo.affectedPopulation }}</el-descriptions-item>
        <el-descriptions-item label="房屋损毁" v-if="detailInfo.damagedHouses">{{ detailInfo.damagedHouses }}</el-descriptions-item>
        <el-descriptions-item label="农作物受灾" v-if="detailInfo.damagedCrops">{{ detailInfo.damagedCrops }}</el-descriptions-item>
        <el-descriptions-item label="基础设施损毁" v-if="detailInfo.infrastructureDamage" :span="2">
          <div v-html="formatDescription(detailInfo.infrastructureDamage)"></div>
        </el-descriptions-item>
        <el-descriptions-item label="救援情况" v-if="detailInfo.rescueSituation" :span="2">
          <div v-html="formatDescription(detailInfo.rescueSituation)"></div>
        </el-descriptions-item>
        <el-descriptions-item label="应对措施" v-if="detailInfo.responseMeasures" :span="2">
          <div v-html="formatDescription(detailInfo.responseMeasures)"></div>
        </el-descriptions-item>
        <el-descriptions-item label="预防措施" v-if="detailInfo.preventionMeasures" :span="2">
          <div v-html="formatDescription(detailInfo.preventionMeasures)"></div>
        </el-descriptions-item>
        <el-descriptions-item label="经验教训" v-if="detailInfo.lessonsLearned" :span="2">
          <div v-html="formatDescription(detailInfo.lessonsLearned)"></div>
        </el-descriptions-item>
        <el-descriptions-item label="天气情况" v-if="detailInfo.weatherCondition">{{ detailInfo.weatherCondition }}</el-descriptions-item>
        <el-descriptions-item label="预警等级" v-if="detailInfo.warningLevel">{{ detailInfo.warningLevel }}</el-descriptions-item>
        <el-descriptions-item label="转移人数" v-if="detailInfo.evacuationNumber">{{ detailInfo.evacuationNumber }}</el-descriptions-item>
        <el-descriptions-item label="救援队伍" v-if="detailInfo.rescueTeams">{{ detailInfo.rescueTeams }}</el-descriptions-item>
        <el-descriptions-item label="物资支援" v-if="detailInfo.materialSupport" :span="2">
          <div v-html="formatDescription(detailInfo.materialSupport)"></div>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :options="dict.type.sys_normal_disable" :value="detailInfo.status"/>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detailInfo.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="案例描述" :span="2" v-if="detailInfo.caseDescription">
          <div v-html="formatDescription(detailInfo.caseDescription)" style="white-space: pre-wrap;"></div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 案例数据（JSON格式） -->
      <div v-if="detailCaseData && Object.keys(detailCaseData).length > 0" style="margin-top: 20px;">
        <el-divider content-position="left">案例详细数据</el-divider>
        <el-table :data="formatCaseData(detailCaseData)" border max-height="300">
          <el-table-column label="字段名称" prop="key" width="200"></el-table-column>
          <el-table-column label="字段值" prop="value" show-overflow-tooltip></el-table-column>
        </el-table>
      </div>

      <div v-if="detailInfo.remark" style="margin-top: 20px;">
        <el-divider content-position="left">备注</el-divider>
        <p>{{ detailInfo.remark }}</p>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCase, getCase, delCase, addCase, updateCase, exportCase } from "@/api/flood/case";
import { importCase } from "@/api/flood/case";
import { getToken } from "@/utils/auth";

export default {
  name: "FloodCase",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 洪水案例库表格数据
      caseList: [],
      // 是否显示扩展列
      hasPeakFlow: false,
      hasEconomicLoss: false,
      // 详情对话框
      detailOpen: false,
      detailInfo: {},
      detailCaseData: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        caseType: null,
        caseName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        caseType: [
          { required: true, message: "案例类型不能为空", trigger: "blur" }
        ],
        caseName: [
          { required: true, message: "案例名称不能为空", trigger: "blur" }
        ]
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的案例数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/flood/case/importData"
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询洪水案例库列表 */
    getList() {
      this.loading = true;
      listCase(this.queryParams).then(response => {
        this.caseList = response.rows;
        this.total = response.total;
        // 检查是否有扩展字段数据，决定是否显示扩展列
        this.hasPeakFlow = this.caseList.some(item => item.peakFlow);
        this.hasEconomicLoss = this.caseList.some(item => item.economicLoss);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        caseId: null,
        caseType: null,
        caseName: null,
        caseTime: null,
        caseLocation: null,
        caseDescription: null,
        caseData: null,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.caseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加洪水案例库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const caseId = row.caseId || this.ids[0]
      getCase(caseId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改洪水案例库";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const caseId = row.caseId;
      getCase(caseId).then(response => {
        this.detailInfo = response.data;
        // 解析案例数据（JSON格式）
        if (this.detailInfo.caseData) {
          try {
            this.detailCaseData = JSON.parse(this.detailInfo.caseData);
          } catch (e) {
            console.error("解析案例数据失败", e);
            this.detailCaseData = null;
          }
        } else {
          this.detailCaseData = null;
        }
        this.detailOpen = true;
      }).catch(() => {
        this.$modal.msgError("获取案例详情失败");
      });
    },
    /** 格式化描述 */
    formatDescription(desc) {
      if (!desc) return '无';
      return desc.replace(/\n/g, '<br/>');
    },
    /** 格式化案例数据为表格格式 */
    formatCaseData(data) {
      const result = [];
      for (const key in data) {
        if (data.hasOwnProperty(key)) {
          result.push({
            key: key,
            value: data[key] || '无'
          });
        }
      }
      return result;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.caseId != null) {
            updateCase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const caseIds = row.caseId || this.ids;
      this.$modal.confirm('是否确认删除案例编号为"' + caseIds + '"的数据项？').then(function() {
        return delCase(caseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('flood/case/export', {
        ...this.queryParams
      }, `case_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "洪水案例导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('flood/case/importTemplate', {
      }, `case_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
