<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="statYear">
          <template slot="label">{{ dmT("queryStatYear") }}</template>
          <el-select v-model="queryParams.statYear" :placeholder="dmCommon('pleaseSelect')" clearable style="width: 140px">
            <el-option v-for="y in yearOptions" :key="y" :label="String(y)" :value="y" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ dmCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ dmCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:disposableIncome:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ dmCommon("add") }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border>
        <template slot="empty">
          <span>{{ dmT("emptyList") }}</span>
        </template>
        <el-table-column :label="dmT('colStatYear')" prop="statYear" align="center" width="120" />
        <el-table-column :label="dmT('colRuralDisposableIncome')" align="center" min-width="180">
          <template slot-scope="scope">{{ formatMoney(scope.row.ruralDisposableIncome) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colIncomeIncrease')" align="center" min-width="120">
          <template slot-scope="scope">{{ formatIncrease(scope.row.incomeIncrease) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colIncomeGrowthRate')" align="center" min-width="120">
          <template slot-scope="scope">{{ formatGrowthRate(scope.row.incomeGrowthRate) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colPovertyNetIncome')" align="center" min-width="180">
          <template slot-scope="scope">{{ formatMoney(scope.row.povertyNetIncome) }}</template>
        </el-table-column>
        <el-table-column :label="dmCommon('colOp')" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['dataModel:disposableIncome:query']" type="text" size="mini" @click="handleView(scope.row)">{{ dmCommon("view") }}</el-button>
            <el-button v-hasPermi="['dataModel:disposableIncome:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ dmCommon("edit") }}</el-button>
            <el-button v-hasPermi="['dataModel:disposableIncome:remove']" type="text" size="mini" @click="handleDelete(scope.row)">{{ dmCommon("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="180px" size="small">
        <el-form-item prop="statYear" :rules="formRules.statYear">
          <template slot="label">{{ dmT("formStatYear") }}</template>
          <el-select v-model="form.statYear" :placeholder="dmCommon('pleaseSelect')" style="width: 100%" @change="onStatYearOrIncomeChange">
            <el-option v-for="y in yearOptions" :key="'f-' + y" :label="String(y)" :value="y" />
          </el-select>
        </el-form-item>
        <el-form-item prop="ruralDisposableIncome" :rules="formRules.ruralDisposableIncome">
          <template slot="label">{{ dmT("formRuralDisposableIncome") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.ruralDisposableIncome"
              :min="0"
              :precision="2"
              :controls="true"
              controls-position="right"
              class="dm-input-with-unit__input"
              @change="onStatYearOrIncomeChange"
            />
            <span class="dm-input-with-unit__suffix">{{ dmT("unitYuan") }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="incomeIncrease" :rules="formRules.optionalNumber">
          <template slot="label">{{ dmT("formIncomeIncrease") }}</template>
          <div class="dm-input-with-unit">
            <el-input
              v-model="form.incomeIncrease"
              :placeholder="dmT('phIncomeIncrease')"
              clearable
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ dmT("unitYuan") }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="incomeGrowthRate" :rules="formRules.optionalNumber">
          <template slot="label">{{ dmT("formIncomeGrowthRate") }}</template>
          <el-input
            v-model="form.incomeGrowthRate"
            :placeholder="dmT('phIncomeGrowthRate')"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="povertyNetIncome" :rules="formRules.povertyNetIncome">
          <template slot="label">{{ dmT("formPovertyNetIncome") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.povertyNetIncome"
              :min="0"
              :precision="2"
              :controls="true"
              controls-position="right"
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ dmT("unitYuan") }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="remark" :rules="formRules.remark">
          <template slot="label">{{ dmT("formRemark") }}</template>
          <el-input v-model="form.remark" type="textarea" :rows="2" :placeholder="dmT('phRemark')" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ dmCommon("ok") }}</el-button>
        <el-button @click="cancel">{{ dmCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dmCommon('viewTitle')" :visible.sync="viewOpen" width="640px" append-to-body>
      <el-form label-width="180px" size="small">
        <el-form-item :label="dmT('formStatYear')">
          <span>{{ viewRow.statYear || dash }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formRuralDisposableIncome')">
          <span>{{ formatWithUnit(formatMoney(viewRow.ruralDisposableIncome), "unitYuan") }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formIncomeIncrease')">
          <span>{{ formatWithUnit(formatIncrease(viewRow.incomeIncrease), "unitYuan") }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formIncomeGrowthRate')">
          <span>{{ formatGrowthRate(viewRow.incomeGrowthRate) }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formPovertyNetIncome')">
          <span>{{ formatWithUnit(formatMoney(viewRow.povertyNetIncome), "unitYuan") }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formRemark')">
          <span class="di-view-text">{{ viewRow.remark || dash }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-hasPermi="['dataModel:disposableIncome:edit']"
          type="primary"
          @click="handleEditFromView"
        >{{ dmCommon("edit") }}</el-button>
        <el-button @click="viewOpen = false">{{ dmCommon("close") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dataModelLocaleMixin from "@/mixins/dataModelLocaleMixin"
import {
  listDisposableIncome,
  getDisposableIncome,
  addDisposableIncome,
  updateDisposableIncome,
  delDisposableIncome,
  listDisposableIncomeYearOptions
} from "@/api/dataModel/disposableIncome"

function createEmptyForm() {
  return {
    id: undefined,
    statYear: undefined,
    ruralDisposableIncome: undefined,
    incomeIncrease: undefined,
    incomeGrowthRate: undefined,
    povertyNetIncome: undefined,
    remark: undefined
  }
}

function optionalFieldToInput(val) {
  if (val == null || val === "") {
    return undefined
  }
  return String(val)
}

function parseOptionalNumber(val) {
  if (val == null || val === "") {
    return undefined
  }
  const n = Number(val)
  return Number.isFinite(n) ? n : NaN
}

function normalizeForm(data) {
  const row = Object.assign(createEmptyForm(), data || {})
  if (row.ruralDisposableIncome != null && row.ruralDisposableIncome !== "") {
    row.ruralDisposableIncome = Number(row.ruralDisposableIncome)
  } else {
    row.ruralDisposableIncome = undefined
  }
  if (row.povertyNetIncome != null && row.povertyNetIncome !== "") {
    row.povertyNetIncome = Number(row.povertyNetIncome)
  } else {
    row.povertyNetIncome = undefined
  }
  row.incomeIncrease = optionalFieldToInput(row.incomeIncrease)
  row.incomeGrowthRate = optionalFieldToInput(row.incomeGrowthRate)
  return row
}

export default {
  name: "DisposableIncome",
  mixins: [dataModelLocaleMixin],
  data() {
    return {
      dmNs: "disposableIncome",
      loading: false,
      open: false,
      viewOpen: false,
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      yearOptions: [],
      viewRow: {},
      /** 编辑时用于判断年份/可支配收入是否变更，以便清空增幅增速 */
      baselineStatYear: undefined,
      baselineRuralDisposableIncome: undefined,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        statYear: undefined
      },
      form: createEmptyForm()
    }
  },
  computed: {
    dash() {
      return this.$t("dataModel.status.dash")
    },
    dialogTitle() {
      return this.dialogEdit ? this.dmT("dialogEdit") : this.dmT("dialogAdd")
    },
    formRules() {
      return {
        statYear: [{ required: true, message: this.dmT("ruleStatYearRequired"), trigger: "change" }],
        ruralDisposableIncome: [
          { required: true, message: this.dmT("ruleRuralIncomeRequired"), trigger: "change" },
          { validator: this.validateNonNegativeMoney, trigger: "change" }
        ],
        povertyNetIncome: [
          { required: true, message: this.dmT("rulePovertyIncomeRequired"), trigger: "change" },
          { validator: this.validateNonNegativeMoney, trigger: "change" }
        ],
        optionalNumber: [{ validator: this.validateOptionalNumber, trigger: "blur" }],
        remark: [{ max: 500, message: this.dmCommon("ruleLen500"), trigger: "blur" }]
      }
    }
  },
  created() {
    this.loadOptions()
    this.getList()
  },
  methods: {
    loadOptions() {
      listDisposableIncomeYearOptions().then((res) => {
        this.yearOptions = Array.isArray(res.data) ? res.data : []
      })
    },
    formatMoney(val) {
      if (val == null || val === "") {
        return this.dash
      }
      const n = Number(val)
      if (!Number.isFinite(n)) {
        return this.dash
      }
      return n.toFixed(2)
    },
    /** 列表/详情：库中 null 显示为 0.00 */
    formatIncrease(val) {
      if (val == null || val === "") {
        return "0.00"
      }
      const n = Number(val)
      if (!Number.isFinite(n)) {
        return "0.00"
      }
      return n.toFixed(2)
    },
    /** 列表/详情：库中 null 显示为 0.00%；小数转百分比 */
    formatGrowthRate(val) {
      if (val == null || val === "") {
        return "0.00%"
      }
      const n = Number(val)
      if (!Number.isFinite(n)) {
        return "0.00%"
      }
      return (n * 100).toFixed(2) + "%"
    },
    validateNonNegativeMoney(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      if (typeof value !== "number" || Number.isNaN(value) || value < 0) {
        callback(new Error(this.dmT("ruleMoneyNonNegative")))
        return
      }
      callback()
    },
    validateOptionalNumber(rule, value, callback) {
      if (value == null || value === "") {
        callback()
        return
      }
      const n = Number(value)
      if (!Number.isFinite(n)) {
        callback(new Error(this.dmT("ruleNumberInvalid")))
        return
      }
      callback()
    },
    clearGrowthFields() {
      this.form.incomeIncrease = undefined
      this.form.incomeGrowthRate = undefined
    },
    onStatYearOrIncomeChange() {
      if (!this.dialogEdit || !this.open) {
        return
      }
      const yearChanged = this.form.statYear !== this.baselineStatYear
      const incomeChanged = !this.sameDecimal(this.form.ruralDisposableIncome, this.baselineRuralDisposableIncome)
      if (yearChanged || incomeChanged) {
        this.clearGrowthFields()
      }
    },
    sameDecimal(a, b) {
      if (a == null && b == null) {
        return true
      }
      if (a == null || b == null) {
        return false
      }
      return Number(a) === Number(b)
    },
    buildListQuery() {
      const q = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }
      if (this.queryParams.statYear != null) {
        q.statYear = this.queryParams.statYear
      }
      return q
    },
    buildPayload() {
      const remarkText = this.form.remark != null ? String(this.form.remark).trim() : ""
      const incomeIncrease = parseOptionalNumber(this.form.incomeIncrease)
      const incomeGrowthRate = parseOptionalNumber(this.form.incomeGrowthRate)
      return {
        statYear: this.form.statYear,
        ruralDisposableIncome: this.form.ruralDisposableIncome,
        povertyNetIncome: this.form.povertyNetIncome,
        incomeIncrease: incomeIncrease === undefined ? undefined : incomeIncrease,
        incomeGrowthRate: incomeGrowthRate === undefined ? undefined : incomeGrowthRate,
        remark: remarkText !== "" ? remarkText : undefined
      }
    },
    getList() {
      this.loading = true
      listDisposableIncome(this.buildListQuery())
        .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.statYear = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleAdd() {
      this.formKey += 1
      this.form = createEmptyForm()
      this.form.statYear = new Date().getFullYear()
      this.baselineStatYear = undefined
      this.baselineRuralDisposableIncome = undefined
      this.dialogEdit = false
      this.open = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      getDisposableIncome(row.id).then((res) => {
        this.formKey += 1
        this.dialogEdit = true
        this.form = normalizeForm(res.data || {})
        this.baselineStatYear = this.form.statYear
        this.baselineRuralDisposableIncome = this.form.ruralDisposableIncome
        this.open = true
        this.viewOpen = false
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleEditFromView() {
      this.handleEdit(this.viewRow)
    },
    handleView(row) {
      getDisposableIncome(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.dmT("confirmDelete"))
        .then(() => delDisposableIncome(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dmCommon("msgDelOk"))
          this.viewOpen = false
          this.getList()
        })
        .catch(() => {})
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (Number.isNaN(payload.incomeIncrease) || Number.isNaN(payload.incomeGrowthRate)) {
          this.$modal.msgError(this.dmT("ruleNumberInvalid"))
          return
        }
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateDisposableIncome(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addDisposableIncome(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.form = createEmptyForm()
    }
  }
}
</script>

<style scoped>
.di-view-text {
  white-space: pre-wrap;
  word-break: break-all;
}
.dm-input-with-unit {
  display: flex;
  align-items: center;
  width: 100%;
}
.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>
