<template>
  <div class="app-container">
    <el-form
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      label-width="90px"
      size="small"
      v-show="showSearch"
    >
      <el-form-item label="案例标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入案例标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="事件类型" prop="eventType">
        <el-select v-model="queryParams.eventType" placeholder="全部" clearable>
          <el-option
            v-for="item in eventTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="事件级别" prop="eventLevel">
        <el-select v-model="queryParams.eventLevel" placeholder="全部" clearable>
          <el-option
            v-for="item in levelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-input
          v-model="queryParams.tags"
          placeholder="请输入标签（逗号分隔）"
          clearable
        />
      </el-form-item>
      <el-form-item label="典型案例" prop="isTypical">
        <el-select v-model="queryParams.isTypical" placeholder="全部" clearable>
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="发生时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px"
          clearable
        />
      </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="['case:case:add']"
        >
          新增
        </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="['case: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="['case:case:remove']"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-star-on"
          size="mini"
          :disabled="single"
          @click="handleMarkTypical"
          v-hasPermi="['case:case:markTypical']"
        >
          标记典型案例
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </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="序号" type="index" width="50" align="center" />
      <el-table-column label="案例编号" prop="caseNo" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="案例标题" prop="title" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="事件类型" prop="eventType" width="120" align="center">
        <template slot-scope="scope">
          {{ renderEventType(scope.row.eventType) }}
        </template>
      </el-table-column>
      <el-table-column label="事件级别" prop="eventLevel" width="110" align="center">
        <template slot-scope="scope">
          <el-tag size="mini">{{ renderEventLevel(scope.row.eventLevel) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发生时间" prop="occurredTime" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.occurredTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发生地点" prop="location" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="标签" prop="tags" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="典型案例" prop="isTypical" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isTypical ? 'success' : 'info'" size="mini">
            {{ scope.row.isTypical ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="查看次数" prop="viewCount" width="100" align="center" />
      <el-table-column label="创建时间" prop="createTime" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['case:case:query']"
          >
            查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['case:case:edit']"
          >
            修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['case: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 :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="案例编号" prop="caseNo">
              <el-input v-model="form.caseNo" placeholder="请输入案例编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="案例标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入案例标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="事件类型" prop="eventType">
              <el-select v-model="form.eventType" placeholder="请选择事件类型" clearable style="width: 100%">
                <el-option
                  v-for="item in eventTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事件级别" prop="eventLevel">
              <el-select v-model="form.eventLevel" placeholder="请选择事件级别" clearable style="width: 100%">
                <el-option
                  v-for="item in levelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发生时间" prop="occurredTime">
              <el-date-picker
                v-model="form.occurredTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择发生时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发生地点" prop="location">
              <el-input v-model="form.location" placeholder="请输入发生地点" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="案例描述" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                :rows="3"
                placeholder="请输入案例描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="处置摘要" prop="disposalSummary">
              <el-input
                v-model="form.disposalSummary"
                type="textarea"
                :rows="3"
                placeholder="请输入处置摘要"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标签" prop="tags">
              <el-input v-model="form.tags" placeholder="请输入标签（逗号分隔）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="典型案例" prop="isTypical">
              <el-switch v-model="form.isTypical" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </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="案例详情" :visible.sync="viewOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="案例编号">{{ viewData.caseNo }}</el-descriptions-item>
        <el-descriptions-item label="案例标题">{{ viewData.title }}</el-descriptions-item>
        <el-descriptions-item label="事件类型">{{ renderEventType(viewData.eventType) }}</el-descriptions-item>
        <el-descriptions-item label="事件级别">
          <el-tag size="mini">{{ renderEventLevel(viewData.eventLevel) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发生时间">
          {{ parseTime(viewData.occurredTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
        </el-descriptions-item>
        <el-descriptions-item label="发生地点">{{ viewData.location }}</el-descriptions-item>
        <el-descriptions-item label="标签">{{ viewData.tags }}</el-descriptions-item>
        <el-descriptions-item label="典型案例">
          <el-tag :type="viewData.isTypical ? 'success' : 'info'" size="mini">
            {{ viewData.isTypical ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="查看次数">{{ viewData.viewCount }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ parseTime(viewData.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
        </el-descriptions-item>
        <el-descriptions-item label="案例描述" :span="2">{{ viewData.description }}</el-descriptions-item>
        <el-descriptions-item label="处置摘要" :span="2">{{ viewData.disposalSummary }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ viewData.remark }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCases,
  getCase,
  addCase,
  updateCase,
  deleteCase,
  markTypical,
  unmarkTypical
} from '@/api/case'
import { getDicts } from '@/api/system/dict/data'

export default {
  name: 'CaseManagement',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 案例表格数据
      caseList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示查看弹出层
      viewOpen: false,
      // 查看数据
      viewData: {},
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        eventType: undefined,
        eventLevel: undefined,
        tags: undefined,
        isTypical: undefined,
        beginTime: undefined,
        endTime: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [{ required: true, message: '案例标题不能为空', trigger: 'blur' }]
      },
      // 事件类型选项
      eventTypeOptions: [],
      // 事件级别选项
      levelOptions: [
        { label: 'I级', value: 'I' },
        { label: 'II级', value: 'II' },
        { label: 'III级', value: 'III' },
        { label: 'IV级', value: 'IV' }
      ]
    }
  },
  created() {
    this.getList()
    this.getDicts()
  },
  methods: {
    /** 查询案例列表 */
    getList() {
      this.loading = true
      // 处理日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginTime = this.dateRange[0] + ' 00:00:00'
        this.queryParams.endTime = this.dateRange[1] + ' 23:59:59'
      } else {
        this.queryParams.beginTime = undefined
        this.queryParams.endTime = undefined
      }
      listCases(this.queryParams).then(response => {
        this.caseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取字典数据 */
    getDicts() {
      getDicts('event_type').then(response => {
        this.eventTypeOptions = response.data.map(item => ({
          label: item.dictLabel,
          value: item.dictValue
        }))
      })
    },
    /** 渲染事件类型 */
    renderEventType(eventType) {
      const option = this.eventTypeOptions.find(item => item.value === eventType)
      return option ? option.label : eventType || '-'
    },
    /** 渲染事件级别 */
    renderEventLevel(level) {
      const option = this.levelOptions.find(item => item.value === level)
      return option ? option.label : level || '-'
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        caseNo: undefined,
        title: undefined,
        eventType: undefined,
        eventLevel: undefined,
        location: undefined,
        occurredTime: undefined,
        description: undefined,
        disposalSummary: undefined,
        tags: undefined,
        isTypical: false,
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加案例'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getCase(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改案例'
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      const id = row.id
      getCase(id).then(response => {
        this.viewData = response.data
        this.viewOpen = true
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateCase(this.form.id, 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 ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除案例编号为"' + (row.caseNo || ids) + '"的数据项？')
        .then(function() {
          return deleteCase(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 标记典型案例按钮操作 */
    handleMarkTypical() {
      const id = this.ids[0]
      const row = this.caseList.find(item => item.id === id)
      if (!row) {
        this.$modal.msgWarning('请选择要操作的案例')
        return
      }
      const action = row.isTypical ? '取消标记' : '标记'
      this.$modal
        .confirm('是否确认' + action + '案例"' + row.title + '"为典型案例？')
        .then(() => {
          if (row.isTypical) {
            return unmarkTypical(id)
          } else {
            return markTypical(id)
          }
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(action + '成功')
        })
        .catch(() => {})
    }
  }
}
</script>

