<template>
  <div class="app-container">
    <el-card shadow="never" v-loading="loading">
      <div slot="header" class="clearfix">
        <span>{{ ddT("pageTitle") }}</span>
      </div>
      <el-form ref="form" :model="form" label-width="140px" class="rfw-form">
        <el-form-item
          v-for="item in weightFieldList"
          :key="item.key"
          :prop="item.key"
          :rules="weightRules[item.key]"
        >
          <template slot="label">{{ ddT(item.labelKey) }}</template>
          <div class="rfw-form-row">
            <el-input-number
              v-model="form[item.key]"
              :min="0"
              :precision="2"
              :step="0.01"
              controls-position="right"
              class="rfw-input"
              :placeholder="ddT('phWeight')"
            />
            <!-- <span class="rfw-hint">{{ ddT("hintPositive") }}</span> -->
          </div>
        </el-form-item>
        <el-form-item>
          <div class="rfw-sum">
            <span>{{ ddT("weightSumLabel") }}：<strong>{{ weightSumText }}</strong></span>
            <span class="rfw-sum-rule" :class="{ 'is-error': !sumValid }">{{ ddT("sumEqualOne") }}</span>
            <span v-if="!sumValid" class="rfw-sum-warn">{{ ddT("sumRuleHint") }}</span>
          </div>
        </el-form-item>
        <el-form-item v-if="meta.updateTime">
          <span class="rfw-meta">{{ ddT("viewUpdateBy") }}：{{ meta.updateBy || $t("diseaseDetection.status.dash") }}</span>
          <span class="rfw-meta">{{ ddT("viewUpdateTime") }}：{{ meta.updateTime ? parseTime(meta.updateTime) : $t("diseaseDetection.status.dash") }}</span>
        </el-form-item>
        <el-form-item>
          <el-button
            v-hasPermi="['diseaseDetection:riskFactorWeight:edit']"
            type="primary"
            :disabled="!sumValid"
            @click="submitForm"
          >{{ ddT("btnSave") }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import diseaseDetectionLocaleMixin from "@/mixins/diseaseDetectionLocaleMixin"
import { getRiskFactorWeight, updateRiskFactorWeight } from "@/api/diseaseDetection/riskFactorWeight"

const SUM_TOLERANCE = 0.0001

const WEIGHT_KEYS = [
  "breedingDensityWeight",
  "trafficMobilityWeight",
  "quarantineIntensityWeight",
  "meteorologicalSuitabilityWeight",
  "pastDiseaseLevelWeight"
]

export default {
  name: "RiskFactorWeight",
  mixins: [diseaseDetectionLocaleMixin],
  data() {
    return {
      ddNs: "riskFactorWeight",
      loading: false,
      meta: {
        updateBy: undefined,
        updateTime: undefined
      },
      form: this.defaultForm()
    }
  },
  computed: {
    weightFieldList() {
      return [
        { key: "breedingDensityWeight", labelKey: "factorBreedingDensity" },
        { key: "trafficMobilityWeight", labelKey: "factorTrafficMobility" },
        { key: "quarantineIntensityWeight", labelKey: "factorQuarantineIntensity" },
        { key: "meteorologicalSuitabilityWeight", labelKey: "factorMeteorologicalSuitability" },
        { key: "pastDiseaseLevelWeight", labelKey: "factorPastDiseaseLevel" }
      ]
    },
    weightRules() {
      const rules = {}
      WEIGHT_KEYS.forEach((key) => {
        rules[key] = [
          { required: true, message: this.ddT("ruleWeightRequired"), trigger: "blur" },
          { validator: this.validatePositiveWeight, trigger: "blur" }
        ]
      })
      return rules
    },
    weightSum() {
      let sum = 0
      let valid = true
      WEIGHT_KEYS.forEach((key) => {
        const n = Number(this.form[key])
        if (isNaN(n)) {
          valid = false
          return
        }
        sum += n
      })
      if (!valid) {
        return NaN
      }
      return sum
    },
    weightSumText() {
      if (isNaN(this.weightSum)) {
        return this.$t("diseaseDetection.status.dash")
      }
      return this.weightSum.toFixed(4)
    },
    sumValid() {
      if (isNaN(this.weightSum)) {
        return false
      }
      return Math.abs(this.weightSum - 1) <= SUM_TOLERANCE
    }
  },
  created() {
    this.loadConfig()
  },
  methods: {
    defaultForm() {
      return {
        breedingDensityWeight: 0.2,
        trafficMobilityWeight: 0.2,
        quarantineIntensityWeight: 0.2,
        meteorologicalSuitabilityWeight: 0.2,
        pastDiseaseLevelWeight: 0.2
      }
    },
    validatePositiveWeight(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      const n = Number(value)
      if (isNaN(n) || n <= 0) {
        callback(new Error(this.ddT("ruleWeightPositive")))
        return
      }
      callback()
    },
    applyData(data) {
      if (!data) {
        this.form = this.defaultForm()
        this.meta = { updateBy: undefined, updateTime: undefined }
        return
      }
      this.form = {
        breedingDensityWeight: data.breedingDensityWeight != null ? Number(data.breedingDensityWeight) : 0.2,
        trafficMobilityWeight: data.trafficMobilityWeight != null ? Number(data.trafficMobilityWeight) : 0.2,
        quarantineIntensityWeight: data.quarantineIntensityWeight != null ? Number(data.quarantineIntensityWeight) : 0.2,
        meteorologicalSuitabilityWeight:
          data.meteorologicalSuitabilityWeight != null ? Number(data.meteorologicalSuitabilityWeight) : 0.2,
        pastDiseaseLevelWeight: data.pastDiseaseLevelWeight != null ? Number(data.pastDiseaseLevelWeight) : 0.2
      }
      this.meta = {
        updateBy: data.updateBy,
        updateTime: data.updateTime
      }
    },
    loadConfig() {
      this.loading = true
      getRiskFactorWeight()
        .then((res) => {
          this.applyData(res.data)
        })
        .catch(() => {
          this.applyData(null)
        })
        .finally(() => {
          this.loading = false
        })
    },
    buildPayload() {
      return {
        breedingDensityWeight: this.form.breedingDensityWeight,
        trafficMobilityWeight: this.form.trafficMobilityWeight,
        quarantineIntensityWeight: this.form.quarantineIntensityWeight,
        meteorologicalSuitabilityWeight: this.form.meteorologicalSuitabilityWeight,
        pastDiseaseLevelWeight: this.form.pastDiseaseLevelWeight
      }
    },
    submitForm() {
      if (!this.sumValid) {
        this.$modal.msgError(this.ddT("ruleSumNotOne"))
        return
      }
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        updateRiskFactorWeight(this.buildPayload()).then(() => {
          this.$modal.msgSuccess(this.ddCommon("msgModOk"))
          this.loadConfig()
        })
      })
    }
  }
}
</script>

<style scoped>
.rfw-form {
  max-width: 640px;
}
.rfw-form-row {
  display: flex;
  align-items: center;
  width: 100%;
}
.rfw-input {
  flex: 1;
  max-width: 280px;
}
.rfw-input ::v-deep.el-input-number {
  width: 100%;
}
.rfw-hint {
  margin-left: 12px;
  color: #909399;
  font-size: 14px;
  white-space: nowrap;
}
.rfw-sum {
  font-size: 14px;
  color: #606266;
}
.rfw-sum-rule {
  margin-left: 16px;
  color: #67c23a;
}
.rfw-sum-rule.is-error {
  color: #f56c6c;
}
.rfw-sum-warn {
  display: block;
  margin-top: 6px;
  color: #f56c6c;
  font-size: 13px;
}
.rfw-meta {
  display: block;
  color: #909399;
  font-size: 13px;
  line-height: 1.8;
}
</style>
