<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="transmissionRoute">
          <template slot="label">{{ ddT("queryTransmissionRoute") }}</template>
          <el-select v-model="queryParams.transmissionRoute" :placeholder="ddCommon('pleaseSelect')" clearable style="width: 140px">
            <el-option v-for="item in transmissionRouteOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="riskLevel">
          <template slot="label">{{ ddT("queryRiskLevel") }}</template>
          <el-select v-model="queryParams.riskLevel" :placeholder="ddCommon('pleaseSelect')" clearable style="width: 120px">
            <el-option v-for="item in riskLevelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="relieveStatus">
          <template slot="label">{{ ddT("queryRelieveStatus") }}</template>
          <el-select v-model="queryParams.relieveStatus" :placeholder="ddCommon('pleaseSelect')" clearable style="width: 120px">
            <el-option :label="ddT('relieveStatus0')" :value="0" />
            <el-option :label="ddT('relieveStatus1')" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ ddCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ ddCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['diseaseDetection:epidemicReport:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ ddCommon("add") }}</el-button>
          <el-button
            v-hasPermi="['diseaseDetection:epidemicReport:remove']"
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="!ids.length"
            @click="handleDeleteBatch"
          >{{ ddCommon("delete") }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column :label="ddT('colReportDate')" prop="reportDate" align="center" width="110" />
        <el-table-column :label="ddT('colTransmissionRoute')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ transmissionLabel(scope.row.transmissionRoute) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ddT('colEpidemicType')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ epidemicTypeLabel(scope.row.epidemicType) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ddT('colEpidemicName')" prop="epidemicName" align="center" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="ddT('colRiskLevel')" align="center" width="80">
          <template slot-scope="scope">
            <span>{{ riskLevelLabel(scope.row.riskLevel) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ddT('colLocationTrack')" prop="affectedLocationTrack" align="center" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column :label="ddT('colRelieveStatus')" align="center" width="90">
          <template slot-scope="scope">
            <span>{{ relieveStatusText(scope.row.relieveStatus != null ? scope.row.relieveStatus : (isReleased(scope.row) ? 1 : 0)) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ddT('colReleaseDate')" align="center" width="110">
          <template slot-scope="scope">
            <span>{{ scope.row.releaseDate || $t("diseaseDetection.status.dash") }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ddCommon('colCreate')" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime ? parseTime(scope.row.createTime) : $t("diseaseDetection.status.dash") }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ddCommon('colOp')" align="center" class-name="small-padding fixed-width" width="240" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['diseaseDetection:epidemicReport:query']" type="text" size="mini" @click="handleView(scope.row)">{{ ddCommon("view") }}</el-button>
            <el-button
              v-hasPermi="['diseaseDetection:epidemicReport:edit']"
              v-if="!isReleased(scope.row)"
              type="text"
              size="mini"
              @click="handleEdit(scope.row)"
            >{{ ddCommon("edit") }}</el-button>
            <el-button
              v-hasPermi="['diseaseDetection:epidemicReport:relieve']"
              v-if="!isReleased(scope.row)"
              type="text"
              size="mini"
              @click="handleRelieve(scope.row)"
            >{{ ddCommon("relieve") }}</el-button>
            <el-button v-hasPermi="['diseaseDetection:epidemicReport:remove']" type="text" size="mini" @click="handleDelete(scope.row)">{{ ddCommon("delete") }}</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-card>

    <el-dialog :title="dialogTitle" :visible.sync="open" width="720px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="120px">
        <el-form-item prop="reportDate" :rules="formRules.reportDate">
          <template slot="label">{{ ddT("formReportDate") }}</template>
          <el-date-picker v-model="form.reportDate" type="date" value-format="yyyy-MM-dd" :placeholder="ddCommon('pleaseSelect')" style="width: 100%" />
        </el-form-item>
        <el-form-item prop="transmissionRoute" :rules="formRules.transmissionRoute">
          <template slot="label">{{ ddT("formTransmissionRoute") }}</template>
          <el-select v-model="form.transmissionRoute" :placeholder="ddCommon('pleaseSelect')" style="width: 100%">
            <el-option v-for="item in transmissionRouteOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="affectedLocationTrack" :rules="formRules.affectedLocationTrack">
          <template slot="label">{{ ddT("formLocationTrack") }}</template>
          <el-input v-model="form.affectedLocationTrack" type="textarea" :rows="3" :placeholder="ddT('phLocationTrack')" maxlength="500" show-word-limit />
        </el-form-item>
        <el-form-item prop="epidemicType" :rules="formRules.epidemicType">
          <template slot="label">{{ ddT("formEpidemicType") }}</template>
          <el-select v-model="form.epidemicType" :placeholder="ddCommon('pleaseSelect')" style="width: 100%">
            <el-option v-for="item in epidemicTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="epidemicName" :rules="formRules.epidemicName">
          <template slot="label">{{ ddT("formEpidemicName") }}</template>
          <el-input v-model="form.epidemicName" :placeholder="ddT('phEpidemicName')" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item prop="riskLevel" :rules="formRules.riskLevel">
          <template slot="label">{{ ddT("formRiskLevel") }}</template>
          <el-select v-model="form.riskLevel" :placeholder="ddCommon('pleaseSelect')" style="width: 100%">
            <el-option v-for="item in riskLevelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ ddCommon("ok") }}</el-button>
        <el-button @click="cancel">{{ ddCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="ddT('dialogRelieve')" :visible.sync="relieveOpen" width="480px" append-to-body @close="cancelRelieve">
      <el-form ref="relieveForm" :model="relieveForm" label-width="100px">
        <el-form-item prop="releaseDate" :rules="relieveRules.releaseDate">
          <template slot="label">{{ ddT("formReleaseDate") }}</template>
          <el-date-picker
            v-model="relieveForm.releaseDate"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="ddCommon('pleaseSelect')"
            :picker-options="relieveDatePickerOptions"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRelieve">{{ ddCommon("ok") }}</el-button>
        <el-button @click="cancelRelieve">{{ ddCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="ddCommon('viewTitle')" :visible.sync="viewOpen" width="720px" append-to-body>
      <el-form label-width="120px" size="small">
        <el-form-item :label="ddT('formReportDate')">
          <span>{{ viewRow.reportDate || $t("diseaseDetection.status.dash") }}</span>
        </el-form-item>
        <el-form-item :label="ddT('formTransmissionRoute')">
          <span>{{ transmissionLabel(viewRow.transmissionRoute) }}</span>
        </el-form-item>
        <el-form-item :label="ddT('formLocationTrack')">
          <span>{{ viewRow.affectedLocationTrack || $t("diseaseDetection.status.dash") }}</span>
        </el-form-item>
        <el-form-item :label="ddT('formEpidemicType')">
          <span>{{ epidemicTypeLabel(viewRow.epidemicType) }}</span>
        </el-form-item>
        <el-form-item :label="ddT('formEpidemicName')">
          <span>{{ viewRow.epidemicName || $t("diseaseDetection.status.dash") }}</span>
        </el-form-item>
        <el-form-item :label="ddT('formRiskLevel')">
          <span>{{ riskLevelLabel(viewRow.riskLevel) }}</span>
        </el-form-item>
        <el-form-item :label="ddT('colRelieveStatus')">
          <span>{{ relieveStatusText(viewRow.relieveStatus != null ? viewRow.relieveStatus : (isReleased(viewRow) ? 1 : 0)) }}</span>
        </el-form-item>
        <el-form-item :label="ddT('formReleaseDate')">
          <span>{{ viewRow.releaseDate || $t("diseaseDetection.status.dash") }}</span>
        </el-form-item>
        <el-form-item :label="ddT('viewCreateBy')">
          <span>{{ viewRow.createBy || $t("diseaseDetection.status.dash") }}</span>
        </el-form-item>
        <el-form-item :label="ddCommon('colCreate')">
          <span>{{ viewRow.createTime ? parseTime(viewRow.createTime) : $t("diseaseDetection.status.dash") }}</span>
        </el-form-item>
        <el-form-item :label="ddT('viewUpdateBy')">
          <span>{{ viewRow.updateBy || $t("diseaseDetection.status.dash") }}</span>
        </el-form-item>
        <el-form-item :label="ddT('viewUpdateTime')">
          <span>{{ viewRow.updateTime ? parseTime(viewRow.updateTime) : $t("diseaseDetection.status.dash") }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">{{ ddCommon("close") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import diseaseDetectionLocaleMixin from "@/mixins/diseaseDetectionLocaleMixin"
import {
  listEpidemicReport,
  getEpidemicReport,
  addEpidemicReport,
  updateEpidemicReport,
  delEpidemicReport,
  relieveEpidemicReport
} from "@/api/diseaseDetection/epidemicReport"

export default {
  name: "EpidemicReport",
  mixins: [diseaseDetectionLocaleMixin],
  data() {
    return {
      ddNs: "epidemicReport",
      loading: false,
      open: false,
      viewOpen: false,
      relieveOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      ids: [],
      relieveReportDate: undefined,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        transmissionRoute: undefined,
        riskLevel: undefined,
        relieveStatus: undefined
      },
      form: {},
      relieveForm: {
        id: undefined,
        releaseDate: undefined
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogEdit ? this.ddT("dialogEdit") : this.ddT("dialogAdd")
    },
    transmissionRouteOptions() {
      return [1, 2, 3, 4].map((v) => ({ value: v, label: this.ddT("transmission" + v) }))
    },
    epidemicTypeOptions() {
      return [1, 2, 3, 4].map((v) => ({ value: v, label: this.ddT("epidemicType" + v) }))
    },
    riskLevelOptions() {
      return [1, 2, 3].map((v) => ({ value: v, label: this.ddT("risk" + v) }))
    },
    formRules() {
      return {
        reportDate: [{ required: true, message: this.ddT("ruleReportDateRequired"), trigger: "change" }],
        transmissionRoute: [{ required: true, message: this.ddT("ruleTransmissionRequired"), trigger: "change" }],
        affectedLocationTrack: [
          { required: true, message: this.ddT("ruleLocationRequired"), trigger: "blur" },
          { min: 1, max: 500, message: this.ddCommon("ruleLen500"), trigger: "blur" }
        ],
        epidemicType: [{ required: true, message: this.ddT("ruleEpidemicTypeRequired"), trigger: "change" }],
        epidemicName: [
          { required: true, message: this.ddT("ruleEpidemicNameRequired"), trigger: "blur" },
          { min: 1, max: 50, message: this.ddCommon("ruleLen50"), trigger: "blur" }
        ],
        riskLevel: [{ required: true, message: this.ddT("ruleRiskLevelRequired"), trigger: "change" }]
      }
    },
    relieveRules() {
      return {
        releaseDate: [
          { required: true, message: this.ddT("ruleReleaseDateRequired"), trigger: "change" },
          { validator: this.validateReleaseDate, trigger: "change" }
        ]
      }
    },
    relieveDatePickerOptions() {
      const minDay = this.relieveReportDateMin
      return {
        disabledDate: (time) => {
          if (!minDay) {
            return false
          }
          const day = this.parseTime(time, "{y}-{m}-{d}")
          return day < minDay
        }
      }
    },
    relieveReportDateMin() {
      return this.normalizeReportDateYmd(this.relieveReportDate)
    }
  },
  created() {
    this.getList()
  },
  methods: {
    transmissionLabel(v) {
      if (v == null || v === "") {
        return this.$t("diseaseDetection.status.dash")
      }
      return this.ddT("transmission" + v) || v
    },
    epidemicTypeLabel(v) {
      if (v == null || v === "") {
        return this.$t("diseaseDetection.status.dash")
      }
      return this.ddT("epidemicType" + v) || v
    },
    riskLevelLabel(v) {
      if (v == null || v === "") {
        return this.$t("diseaseDetection.status.dash")
      }
      return this.ddT("risk" + v) || v
    },
    normalizeReportDateYmd(val) {
      if (val == null || val === "") {
        return undefined
      }
      if (typeof val === "string") {
        const m = val.match(/^(\d{4}-\d{2}-\d{2})/)
        if (m) {
          return m[1]
        }
      }
      const parsed = this.parseTime(val, "{y}-{m}-{d}")
      return parsed || undefined
    },
    validateReleaseDate(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      const minDay = this.normalizeReportDateYmd(this.relieveReportDate)
      if (minDay && String(value) < minDay) {
        callback(new Error(this.ddCommon("ruleReleaseBeforeReport")))
        return
      }
      callback()
    },
    getList() {
      this.loading = true
      listEpidemicReport(this.queryParams)
        .then((res) => {
          this.tableList = res.rows || []
          this.total = res.total != null ? res.total : 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.transmissionRoute = undefined
      this.queryParams.riskLevel = undefined
      this.queryParams.relieveStatus = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
    },
    resetFormModel() {
      this.form = {
        id: undefined,
        reportDate: undefined,
        transmissionRoute: undefined,
        affectedLocationTrack: undefined,
        epidemicType: undefined,
        epidemicName: undefined,
        riskLevel: undefined
      }
    },
    handleAdd() {
      this.formKey += 1
      this.resetFormModel()
      this.dialogEdit = false
      this.open = true
      this.$nextTick(() => this.resetForm("form"))
    },
    handleEdit(row) {
      if (this.isReleased(row)) {
        this.$modal.msgError(this.ddCommon("ruleReleasedNoEdit"))
        return
      }
      getEpidemicReport(row.id).then((res) => {
        const data = res.data || {}
        if (this.isReleased(data)) {
          this.$modal.msgError(this.ddCommon("ruleReleasedNoEdit"))
          return
        }
        this.formKey += 1
        this.dialogEdit = true
        this.form = {
          id: data.id,
          reportDate: data.reportDate,
          transmissionRoute: data.transmissionRoute,
          affectedLocationTrack: data.affectedLocationTrack,
          epidemicType: data.epidemicType,
          epidemicName: data.epidemicName,
          riskLevel: data.riskLevel
        }
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getEpidemicReport(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleRelieve(row) {
      if (this.isReleased(row)) {
        this.$modal.msgError(this.ddCommon("ruleReleasedNoRelieve"))
        return
      }
      this.relieveReportDate = this.normalizeReportDateYmd(row.reportDate)
      this.relieveForm = {
        id: row.id,
        releaseDate: undefined
      }
      this.relieveOpen = true
      this.$nextTick(() => {
        if (this.$refs.relieveForm) {
          this.$refs.relieveForm.clearValidate()
        }
      })
    },
    cancelRelieve() {
      this.relieveOpen = false
      this.relieveReportDate = undefined
    },
    submitRelieve() {
      this.$refs.relieveForm.validate((valid) => {
        if (!valid) {
          return
        }
        this.$modal
          .confirm(this.ddT("confirmRelieve"))
          .then(() =>
            relieveEpidemicReport({
              id: this.relieveForm.id,
              releaseDate: this.relieveForm.releaseDate
            })
          )
          .then(() => {
            this.$modal.msgSuccess(this.ddCommon("msgRelieveOk"))
            this.relieveOpen = false
            this.getList()
          })
          .catch(() => {})
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.$t("diseaseDetection.epidemicReport.confirmDelete", { id: row.id }))
        .then(() => delEpidemicReport(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.ddCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleDeleteBatch() {
      if (!this.ids.length) {
        return
      }
      this.$modal
        .confirm(this.ddT("confirmDeleteBatch"))
        .then(() => delEpidemicReport(this.ids.join(",")))
        .then(() => {
          this.$modal.msgSuccess(this.ddCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    buildPayload() {
      return {
        reportDate: this.form.reportDate,
        transmissionRoute: this.form.transmissionRoute,
        affectedLocationTrack: this.form.affectedLocationTrack,
        epidemicType: this.form.epidemicType,
        epidemicName: this.form.epidemicName,
        riskLevel: this.form.riskLevel
      }
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateEpidemicReport(payload).then(() => {
            this.$modal.msgSuccess(this.ddCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addEpidemicReport(payload).then(() => {
            this.$modal.msgSuccess(this.ddCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.resetFormModel()
    }
  }
}
</script>
