<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="quarantineStationId">
          <template slot="label">{{ ddT("queryQuarantineStation") }}</template>
          <el-select v-model="queryParams.quarantineStationId" :placeholder="ddCommon('pleaseSelect')" clearable filterable style="width: 200px">
            <el-option v-for="item in quarantineStationOptions" :key="item.id" :label="item.stationName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="sampleSource">
          <template slot="label">{{ ddT("querySampleSource") }}</template>
          <el-select v-model="queryParams.sampleSource" :placeholder="ddCommon('pleaseSelect')" clearable style="width: 160px">
            <el-option v-for="item in sampleSourceOptions" :key="item.value" :label="item.label" :value="item.value" />
          </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:labDetection:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ ddCommon("add") }}</el-button>
          <el-button
            v-hasPermi="['diseaseDetection:labDetection: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('colTestDate')" prop="testDate" align="center" width="110" />
        <el-table-column :label="ddT('colQuarantineStation')" prop="quarantineStationName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="ddT('colSampleSource')" align="center" width="120">
          <template slot-scope="scope">
            <span>{{ sampleSourceLabel(scope.row.sampleSource) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ddT('colTestQuantity')" align="center" >
          <template slot-scope="scope">
            <span>{{ formatQuantity(scope.row.testQuantity) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ddT('colPositiveCount')" align="center">
          <template slot-scope="scope">
            <span>{{ formatQuantity(scope.row.positiveCount) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ddT('colDetectionRate')" align="center" >
          <template slot-scope="scope">
            <span>{{ formatDetectionRate(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="ddCommon('colCreate')" align="center" >
          <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="180" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['diseaseDetection:labDetection:query']" type="text" size="mini" @click="handleView(scope.row)">{{ ddCommon("view") }}</el-button>
            <el-button v-hasPermi="['diseaseDetection:labDetection:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ ddCommon("edit") }}</el-button>
            <el-button v-hasPermi="['diseaseDetection:labDetection: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="640px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="120px">
        <el-form-item prop="testDate" :rules="formRules.testDate">
          <template slot="label">{{ ddT("formTestDate") }}</template>
          <el-date-picker v-model="form.testDate" type="date" value-format="yyyy-MM-dd" :placeholder="ddCommon('pleaseSelect')" style="width: 100%" />
        </el-form-item>
        <el-form-item prop="quarantineStationId" :rules="formRules.quarantineStationId">
          <template slot="label">{{ ddT("formQuarantineStation") }}</template>
          <el-select v-model="form.quarantineStationId" :placeholder="ddCommon('pleaseSelect')" filterable style="width: 100%">
            <el-option v-for="item in quarantineStationOptions" :key="item.id" :label="item.stationName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="sampleSource" :rules="formRules.sampleSource">
          <template slot="label">{{ ddT("formSampleSource") }}</template>
          <el-select v-model="form.sampleSource" :placeholder="ddCommon('pleaseSelect')" style="width: 100%">
            <el-option v-for="item in sampleSourceOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="testQuantity" :rules="formRules.testQuantity">
          <template slot="label">{{ ddT("formTestQuantity") }}</template>
          <div class="dd-input-with-unit">
            <el-input-number
              v-model="form.testQuantity"
              :min="0"
              :precision="0"
              :step="1"
              controls-position="right"
              class="dd-input-with-unit__input"
            />
            <span class="dd-input-with-unit__suffix">{{ ddT("unitFen") }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="positiveCount" :rules="formRules.positiveCount">
          <template slot="label">{{ ddT("formPositiveCount") }}</template>
          <div class="dd-input-with-unit">
            <el-input-number
              v-model="form.positiveCount"
              :min="0"
              :precision="0"
              :step="1"
              controls-position="right"
              class="dd-input-with-unit__input"
            />
            <span class="dd-input-with-unit__suffix">{{ ddT("unitFen") }}</span>
          </div>
        </el-form-item>
        <el-form-item>
          <template slot="label">{{ ddT("formDetectionRate") }}</template>
          <el-input :value="formDetectionRateDisplay" disabled />
        </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="ddCommon('viewTitle')" :visible.sync="viewOpen" width="640px" append-to-body>
      <el-form label-width="120px" size="small">
        <el-form-item :label="ddT('formTestDate')">
          <span>{{ viewRow.testDate || $t("diseaseDetection.status.dash") }}</span>
        </el-form-item>
        <el-form-item :label="ddT('formQuarantineStation')">
          <span>{{ viewRow.quarantineStationName || $t("diseaseDetection.status.dash") }}</span>
        </el-form-item>
        <el-form-item :label="ddT('formSampleSource')">
          <span>{{ sampleSourceLabel(viewRow.sampleSource) }}</span>
        </el-form-item>
        <el-form-item :label="ddT('formTestQuantity')">
          <span>{{ formatQuantity(viewRow.testQuantity) }}</span>
        </el-form-item>
        <el-form-item :label="ddT('formPositiveCount')">
          <span>{{ formatQuantity(viewRow.positiveCount) }}</span>
        </el-form-item>
        <el-form-item :label="ddT('formDetectionRate')">
          <span>{{ formatDetectionRate(viewRow) }}</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 {
  listLabDetection,
  listLabDetectionQuarantineStationOptions,
  getLabDetection,
  addLabDetection,
  updateLabDetection,
  delLabDetection
} from "@/api/diseaseDetection/labDetection"

export default {
  name: "LabDetection",
  mixins: [diseaseDetectionLocaleMixin],
  data() {
    return {
      ddNs: "labDetection",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      ids: [],
      quarantineStationOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        quarantineStationId: undefined,
        sampleSource: undefined
      },
      form: {}
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogEdit ? this.ddT("dialogEdit") : this.ddT("dialogAdd")
    },
    sampleSourceOptions() {
      return [1, 2, 3, 4].map((v) => ({ value: v, label: this.ddT("sampleSource" + v) }))
    },
    formDetectionRateDisplay() {
      return this.formatDetectionRate({
        testQuantity: this.form.testQuantity,
        positiveCount: this.form.positiveCount,
        detectionRate: null
      })
    },
    formRules() {
      return {
        testDate: [{ required: true, message: this.ddT("ruleTestDateRequired"), trigger: "change" }],
        quarantineStationId: [{ required: true, message: this.ddT("ruleQuarantineStationRequired"), trigger: "change" }],
        sampleSource: [{ required: true, message: this.ddT("ruleSampleSourceRequired"), trigger: "change" }],
        testQuantity: [
          { required: true, message: this.ddT("ruleTestQuantityRequired"), trigger: "blur" },
          { validator: this.validateTestQuantity, trigger: "blur" }
        ],
        positiveCount: [
          { required: true, message: this.ddT("rulePositiveCountRequired"), trigger: "blur" },
          { validator: this.validatePositiveCount, trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.loadQuarantineStationOptions()
    this.getList()
  },
  methods: {
    loadQuarantineStationOptions() {
      listLabDetectionQuarantineStationOptions().then((res) => {
        this.quarantineStationOptions = res.data || []
      })
    },
    sampleSourceLabel(v) {
      if (v == null || v === "") {
        return this.$t("diseaseDetection.status.dash")
      }
      return this.ddT("sampleSource" + v) || v
    },
    formatQuantity(n) {
      if (n == null || n === "") {
        return this.$t("diseaseDetection.status.dash")
      }
      return `${n}${this.ddT("unitFen")}`
    },
    calcRateRatio(testQuantity, positiveCount) {
      const tq = Number(testQuantity)
      const pc = Number(positiveCount)
      if (isNaN(tq) || isNaN(pc)) {
        return null
      }
      if (tq <= 0) {
        return 0
      }
      return pc / tq
    },
    formatDetectionRate(row) {
      if (!row) {
        return this.$t("diseaseDetection.status.dash")
      }
      let ratio = row.detectionRate
      if (ratio != null && ratio !== "") {
        ratio = Number(ratio)
      } else {
        ratio = this.calcRateRatio(row.testQuantity, row.positiveCount)
      }
      if (ratio == null || isNaN(ratio)) {
        return this.$t("diseaseDetection.status.dash")
      }
      return `${(ratio * 100).toFixed(2)}%`
    },
    validateTestQuantity(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      const n = Number(value)
      if (!Number.isInteger(n) || n < 0) {
        callback(new Error(this.ddT("ruleTestQuantityRequired")))
        return
      }
      callback()
    },
    validatePositiveCount(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      const pc = Number(value)
      const tq = Number(this.form.testQuantity)
      if (!Number.isInteger(pc) || pc < 0) {
        callback(new Error(this.ddT("rulePositiveCountRequired")))
        return
      }
      if (tq === 0 && pc !== 0) {
        callback(new Error(this.ddT("ruleZeroTestPositive")))
        return
      }
      if (!isNaN(tq) && pc > tq) {
        callback(new Error(this.ddT("rulePositiveExceedTest")))
        return
      }
      callback()
    },
    getList() {
      this.loading = true
      listLabDetection(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.quarantineStationId = undefined
      this.queryParams.sampleSource = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
    },
    resetFormModel() {
      this.form = {
        id: undefined,
        testDate: undefined,
        quarantineStationId: undefined,
        sampleSource: undefined,
        testQuantity: 0,
        positiveCount: 0
      }
    },
    handleAdd() {
      this.formKey += 1
      this.resetFormModel()
      this.dialogEdit = false
      this.open = true
      this.$nextTick(() => this.resetForm("form"))
    },
    handleEdit(row) {
      getLabDetection(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.form = {
          id: data.id,
          testDate: data.testDate,
          quarantineStationId: data.quarantineStationId,
          sampleSource: data.sampleSource,
          testQuantity: data.testQuantity != null ? Number(data.testQuantity) : 0,
          positiveCount: data.positiveCount != null ? Number(data.positiveCount) : 0
        }
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getLabDetection(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.$t("diseaseDetection.labDetection.confirmDelete", { id: row.id }))
        .then(() => delLabDetection(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(() => delLabDetection(this.ids.join(",")))
        .then(() => {
          this.$modal.msgSuccess(this.ddCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    buildPayload() {
      return {
        testDate: this.form.testDate,
        quarantineStationId: this.form.quarantineStationId,
        sampleSource: this.form.sampleSource,
        testQuantity: this.form.testQuantity,
        positiveCount: this.form.positiveCount
      }
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateLabDetection(payload).then(() => {
            this.$modal.msgSuccess(this.ddCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addLabDetection(payload).then(() => {
            this.$modal.msgSuccess(this.ddCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.resetFormModel()
    }
  }
}
</script>

<style scoped>
.dd-input-with-unit {
  display: flex;
  align-items: center;
  width: 100%;
}
.dd-input-with-unit__input {
  flex: 1;
  width: 0;
}
.dd-input-with-unit__input ::v-deep.el-input-number {
  width: 100%;
}
.dd-input-with-unit__suffix {
  flex-shrink: 0;
  margin-left: 8px;
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}
</style>
