<template>
  <div class="app-container">
    <el-card shadow="never" v-loading="loading">
      <div slot="header" class="clearfix">
        <span>{{ tsT("pageTitle") }}</span>
      </div>
      <el-form ref="form" :model="form" label-width="140px" class="tsp-form" size="small">
        <div class="tsp-section-title">{{ tsT("sectionEnvoy") }}</div>
        <el-form-item prop="envoyMaleCount" :rules="countRule">
          <template slot="label">{{ tsT("formEnvoyMale") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.envoyMaleCount"
              :min="0"
              :precision="0"
              controls-position="right"
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ tsT("unitPerson") }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="envoyFemaleCount" :rules="countRule">
          <template slot="label">{{ tsT("formEnvoyFemale") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.envoyFemaleCount"
              :min="0"
              :precision="0"
              controls-position="right"
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ tsT("unitPerson") }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="envoyPartyMemberCount" :rules="countRule">
          <template slot="label">{{ tsT("formEnvoyParty") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.envoyPartyMemberCount"
              :min="0"
              :precision="0"
              controls-position="right"
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ tsT("unitPerson") }}</span>
          </div>
        </el-form-item>
        <el-form-item>
          <template slot="label">{{ tsT("formEnvoyTotal") }}</template>
          <div class="dm-input-with-unit">
            <el-input :value="envoyTotalDisplay" disabled class="dm-input-with-unit__input" />
            <span class="dm-input-with-unit__suffix">{{ tsT("unitPerson") }}</span>
          </div>
        </el-form-item>

        <div class="tsp-section-title">{{ tsT("sectionAgri") }}</div>
         <el-form-item prop="agriClerkCount" :rules="countRule">
          <template slot="label">{{ tsT("formAgriClerk") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.agriClerkCount"
              :min="0"
              :precision="0"
              controls-position="right"
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ tsT("unitPerson") }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="agriJuniorCount" :rules="countRule">
          <template slot="label">{{ tsT("formAgriJunior") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.agriJuniorCount"
              :min="0"
              :precision="0"
              controls-position="right"
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ tsT("unitPerson") }}</span>
          </div>
        </el-form-item>
       
        <el-form-item prop="agriIntermediateCount" :rules="countRule">
          <template slot="label">{{ tsT("formAgriIntermediate") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.agriIntermediateCount"
              :min="0"
              :precision="0"
              controls-position="right"
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ tsT("unitPerson") }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="agriAssociateSeniorCount" :rules="countRule">
          <template slot="label">{{ tsT("formAgriAssociateSenior") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.agriAssociateSeniorCount"
              :min="0"
              :precision="0"
              controls-position="right"
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ tsT("unitPerson") }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="agriManagementCount" :rules="countRule">
          <template slot="label">{{ tsT("formAgriManagement") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.agriManagementCount"
              :min="0"
              :precision="0"
              controls-position="right"
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ tsT("unitPerson") }}</span>
          </div>
        </el-form-item>
        <el-form-item>
          <template slot="label">{{ tsT("formAgriTotal") }}</template>
          <div class="dm-input-with-unit">
            <el-input :value="agriTotalDisplay" disabled class="dm-input-with-unit__input" />
            <span class="dm-input-with-unit__suffix">{{ tsT("unitPerson") }}</span>
          </div>
        </el-form-item>

        <el-form-item v-if="meta.updateTime">
          <span class="tsp-meta">{{ tsT("viewUpdateBy") }}：{{ meta.updateBy || dash }}</span>
          <span class="tsp-meta">{{ tsT("viewUpdateTime") }}：{{ meta.updateTime ? parseTime(meta.updateTime) : dash }}</span>
        </el-form-item>
        <el-form-item>
          <el-button
            v-hasPermi="['techService:techServicePersonnel:edit']"
            type="primary"
            @click="submitForm"
          >{{ tsT("btnSave") }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import techServiceLocaleMixin from "@/mixins/techServiceLocaleMixin"
import { getTechServicePersonnel, updateTechServicePersonnel } from "@/api/techService/techServicePersonnel"

const ENVOY_SUM_KEYS = ["envoyMaleCount", "envoyFemaleCount"]
const AGRI_SUM_KEYS = [
  "agriJuniorCount",
  "agriClerkCount",
  "agriIntermediateCount",
  "agriAssociateSeniorCount",
  "agriManagementCount"
]
const EDITABLE_KEYS = [
  "envoyMaleCount",
  "envoyFemaleCount",
  "envoyPartyMemberCount",
  "agriJuniorCount",
  "agriClerkCount",
  "agriIntermediateCount",
  "agriAssociateSeniorCount",
  "agriManagementCount"
]

function sumNullable(values) {
  let any = false
  let sum = 0
  values.forEach((v) => {
    if (v != null && v !== "") {
      const n = Number(v)
      if (Number.isFinite(n)) {
        any = true
        sum += n
      }
    }
  })
  return any ? sum : null
}

export default {
  name: "TechServicePersonnel",
  mixins: [techServiceLocaleMixin],
  data() {
    return {
      tsNs: "techServicePersonnel",
      loading: false,
      meta: {
        updateBy: undefined,
        updateTime: undefined
      },
      form: this.defaultForm()
    }
  },
  computed: {
    dash() {
      return this.$t("techService.status.dash")
    },
    countRule() {
      return [{ validator: this.validateOptionalCount, trigger: "change" }]
    },
    envoyTotalDisplay() {
      const sum = sumNullable(ENVOY_SUM_KEYS.map((k) => this.form[k]))
      return sum == null ? this.dash : String(sum)
    },
    agriTotalDisplay() {
      const sum = sumNullable(AGRI_SUM_KEYS.map((k) => this.form[k]))
      return sum == null ? this.dash : String(sum)
    }
  },
  created() {
    this.loadConfig()
  },
  methods: {
    defaultForm() {
      const form = {}
      EDITABLE_KEYS.forEach((key) => {
        form[key] = undefined
      })
      return form
    },
    validateOptionalCount(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      if (typeof value !== "number" || Number.isNaN(value) || value < 0 || !Number.isInteger(value)) {
        callback(new Error(this.tsT("ruleCountNonNegative")))
        return
      }
      callback()
    },
    normalizeCount(val) {
      if (val == null || val === "") {
        return undefined
      }
      const n = Number(val)
      return Number.isFinite(n) ? n : undefined
    },
    applyData(data) {
      if (!data) {
        this.form = this.defaultForm()
        this.meta = { updateBy: undefined, updateTime: undefined }
        return
      }
      const form = this.defaultForm()
      EDITABLE_KEYS.forEach((key) => {
        form[key] = this.normalizeCount(data[key])
      })
      this.form = form
      this.meta = {
        updateBy: data.updateBy,
        updateTime: data.updateTime
      }
    },
    loadConfig() {
      this.loading = true
      getTechServicePersonnel()
        .then((res) => {
          this.applyData(res.data)
        })
        .catch(() => {
          this.applyData(null)
        })
        .finally(() => {
          this.loading = false
        })
    },
    buildPayload() {
      const payload = {}
      EDITABLE_KEYS.forEach((key) => {
        const val = this.form[key]
        payload[key] = val == null || val === "" ? null : val
      })
      return payload
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        updateTechServicePersonnel(this.buildPayload()).then(() => {
          this.$modal.msgSuccess(this.tsCommon("msgModOk"))
          this.loadConfig()
        })
      })
    }
  }
}
</script>

<style scoped>
.tsp-form {
  max-width: 560px;
}
.tsp-section-title {
  margin: 4px 0 16px;
  font-weight: 600;
  color: #303133;
}
.tsp-meta {
  display: block;
  color: #909399;
  font-size: 13px;
  line-height: 1.8;
}
.dm-input-with-unit {
  display: flex;
  align-items: center;
  width: 100%;
  max-width: 320px;
}
.dm-input-with-unit__input {
  flex: 1;
  width: 100%;
}
.dm-input-with-unit__suffix {
  margin-left: 8px;
  color: #909399;
  white-space: nowrap;
}
.dm-input-with-unit >>> .el-input-number {
  width: 100%;
}
</style>
