<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="townDeptId">
          <template slot="label">{{ dmT("queryTown") }}</template>
          <el-select v-model="queryParams.townDeptId" :placeholder="dmCommon('pleaseSelect')" clearable filterable style="width: 180px">
            <el-option v-for="item in townOptions" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item prop="villageDeptId">
          <template slot="label">{{ dmT("queryVillage") }}</template>
          <el-select
            v-model="queryParams.villageDeptId"
            :placeholder="dmT('phVillageSearch')"
            clearable
            filterable
            style="width: 220px"
          >
            <el-option
              v-for="item in villageOptions"
              :key="'q-v-' + item.deptId"
              :label="item.label"
              :value="item.deptId"
            />
          </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:ruralThreeAssets: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('colTownName')" prop="townName" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colVillageName')" prop="villageName" align="center" min-width="110" :show-overflow-tooltip="true" />
        <el-table-column :label="dmT('colOperatingFixedAssets')" align="center" min-width="140">
          <template slot-scope="scope">{{ formatMoney(scope.row.operatingFixedAssets) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colNonOperatingFixedAssets')" align="center" min-width="150">
          <template slot-scope="scope">{{ formatMoney(scope.row.nonOperatingFixedAssets) }}</template>
        </el-table-column>
        <el-table-column :label="dmT('colFixedAssets')" align="center" min-width="120">
          <template slot-scope="scope">{{ formatMoney(scope.row.fixedAssets) }}</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:ruralThreeAssets:query']" type="text" size="mini" @click="handleView(scope.row)">{{ dmCommon("view") }}</el-button>
            <el-button v-hasPermi="['dataModel:ruralThreeAssets:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ dmCommon("edit") }}</el-button>
            <el-button v-hasPermi="['dataModel:ruralThreeAssets: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" class="rta-form" label-width="160px" size="small">
        <div class="rta-section-title">{{ dmT("sectionBasic") }}</div>
        <el-form-item prop="villageDeptId" :rules="formRules.villageDeptId">
          <template slot="label">{{ dmT("formVillage") }}</template>
          <el-select
            v-model="form.villageDeptId"
            :placeholder="dmT('phVillageSearch')"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in villageOptions"
              :key="'f-v-' + item.deptId"
              :label="item.label"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>

        <div class="rta-section-title">{{ dmT("sectionAssets") }}</div>
        <el-form-item prop="operatingFixedAssets" :rules="formRules.money">
          <template slot="label">{{ dmT("formOperatingFixedAssets") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.operatingFixedAssets"
              :min="0"
              :precision="2"
              controls-position="right"
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ dmT("unitWanYuan") }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="nonOperatingFixedAssets" :rules="formRules.money">
          <template slot="label">{{ dmT("formNonOperatingFixedAssets") }}</template>
          <div class="dm-input-with-unit">
            <el-input-number
              v-model="form.nonOperatingFixedAssets"
              :min="0"
              :precision="2"
              controls-position="right"
              class="dm-input-with-unit__input"
            />
            <span class="dm-input-with-unit__suffix">{{ dmT("unitWanYuan") }}</span>
          </div>
        </el-form-item>
        <el-form-item>
          <template slot="label">{{ dmT("formFixedAssets") }}</template>
          <div class="dm-input-with-unit">
            <el-input :value="fixedAssetsDisplay" disabled class="dm-input-with-unit__input" />
            <span class="dm-input-with-unit__suffix">{{ dmT("unitWanYuan") }}</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 class="dm-view-form rta-form" label-width="160px" size="small">
        <div class="rta-section-title">{{ dmT("sectionBasic") }}</div>
        <el-form-item :label="dmT('formTown')"><span>{{ viewRow.townName || dash }}</span></el-form-item>
        <el-form-item :label="dmT('formVillage')"><span>{{ viewRow.villageName || dash }}</span></el-form-item>

        <div class="rta-section-title">{{ dmT("sectionAssets") }}</div>
        <el-form-item :label="dmT('formOperatingFixedAssets')">
          <span>{{ formatWithUnit(formatMoney(viewRow.operatingFixedAssets), "unitWanYuan") }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formNonOperatingFixedAssets')">
          <span>{{ formatWithUnit(formatMoney(viewRow.nonOperatingFixedAssets), "unitWanYuan") }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formFixedAssets')">
          <span>{{ formatWithUnit(formatMoney(viewRow.fixedAssets), "unitWanYuan") }}</span>
        </el-form-item>
        <el-form-item :label="dmT('formRemark')">
          <span class="rta-view-text">{{ viewRow.remark || dash }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-hasPermi="['dataModel:ruralThreeAssets: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 {
  listRuralThreeAssets,
  getRuralThreeAssets,
  addRuralThreeAssets,
  updateRuralThreeAssets,
  delRuralThreeAssets,
  listRuralThreeAssetsTownOptions,
  listRuralThreeAssetsVillageTree
} from "@/api/dataModel/ruralThreeAssets"

function createEmptyForm() {
  return {
    id: undefined,
    villageDeptId: undefined,
    operatingFixedAssets: undefined,
    nonOperatingFixedAssets: undefined,
    remark: undefined
  }
}

function normalizeForm(data) {
  const row = Object.assign(createEmptyForm(), data || {})
  ;["operatingFixedAssets", "nonOperatingFixedAssets"].forEach((prop) => {
    const val = row[prop]
    row[prop] = val == null || val === "" ? undefined : Number(val)
  })
  return row
}

function flattenVillageOptions(tree) {
  const list = []
  ;(tree || []).forEach((county) => {
    ;(county.children || []).forEach((town) => {
      ;(town.children || []).forEach((village) => {
        if (village == null || village.id == null) {
          return
        }
        const townName = town.label || ""
        const villageName = village.label || ""
        list.push({
          deptId: village.id,
          label: townName ? `${townName} / ${villageName}` : villageName
        })
      })
    })
  })
  return list
}

function calcFixedAssets(operating, nonOperating) {
  if ((operating == null || operating === "") && (nonOperating == null || nonOperating === "")) {
    return null
  }
  const a = operating == null || operating === "" ? 0 : Number(operating)
  const b = nonOperating == null || nonOperating === "" ? 0 : Number(nonOperating)
  if (!Number.isFinite(a) || !Number.isFinite(b)) {
    return null
  }
  return Math.round((a + b) * 100) / 100
}

export default {
  name: "RuralThreeAssets",
  mixins: [dataModelLocaleMixin],
  data() {
    return {
      dmNs: "ruralThreeAssets",
      loading: false,
      open: false,
      viewOpen: false,
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      townOptions: [],
      villageOptions: [],
      viewRow: {},
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        townDeptId: undefined,
        villageDeptId: undefined
      },
      form: createEmptyForm()
    }
  },
  computed: {
    dash() {
      return this.$t("dataModel.status.dash")
    },
    dialogTitle() {
      return this.dialogEdit ? this.dmT("dialogEdit") : this.dmT("dialogAdd")
    },
    fixedAssetsDisplay() {
      const sum = calcFixedAssets(this.form.operatingFixedAssets, this.form.nonOperatingFixedAssets)
      return sum == null ? this.dash : sum.toFixed(2)
    },
    formRules() {
      return {
        villageDeptId: [{ required: true, message: this.dmT("ruleVillageRequired"), trigger: "change" }],
        money: [{ validator: this.validateOptionalMoney, trigger: "change" }],
        remark: [{ max: 500, message: this.dmCommon("ruleLen500"), trigger: "blur" }]
      }
    }
  },
  created() {
    this.loadOptions()
    this.getList()
  },
  methods: {
    loadOptions() {
      listRuralThreeAssetsTownOptions().then((res) => {
        this.townOptions = Array.isArray(res.data) ? res.data : []
      })
      this.loadVillageTree()
    },
    loadVillageTree() {
      return listRuralThreeAssetsVillageTree()
        .then((res) => {
          const raw = res && res.data !== undefined ? res.data : res
          this.villageOptions = flattenVillageOptions(Array.isArray(raw) ? raw : [])
          if (!this.villageOptions.length) {
            this.$modal.msgWarning(this.dmT("villageTreeEmpty"))
          }
        })
        .catch(() => {
          this.villageOptions = []
        })
    },
    formatMoney(val) {
      if (val == null || val === "") {
        return this.dash
      }
      const n = Number(val)
      if (!Number.isFinite(n)) {
        return this.dash
      }
      return n.toFixed(2)
    },
    validateOptionalMoney(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()
    },
    buildListQuery() {
      const q = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }
      if (this.queryParams.townDeptId != null) {
        q.townDeptId = this.queryParams.townDeptId
      }
      if (this.queryParams.villageDeptId != null) {
        q.villageDeptId = this.queryParams.villageDeptId
      }
      return q
    },
    getList() {
      this.loading = true
      listRuralThreeAssets(this.buildListQuery())
        .then((res) => {
          this.tableList = res.rows || []
          this.total = res.total || 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        townDeptId: undefined,
        villageDeptId: undefined
      }
      this.getList()
    },
    handleAdd() {
      this.dialogEdit = false
      this.formKey += 1
      this.form = createEmptyForm()
      this.open = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      getRuralThreeAssets(row.id).then((res) => {
        this.dialogEdit = true
        this.formKey += 1
        this.form = normalizeForm(res.data)
        this.open = true
        this.viewOpen = false
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getRuralThreeAssets(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleEditFromView() {
      if (!this.viewRow || this.viewRow.id == null) {
        return
      }
      this.handleEdit(this.viewRow)
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.dmT("confirmDelete"))
        .then(() => delRuralThreeAssets(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dmCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    normalizeMoney(val) {
      return val == null || val === "" ? null : val
    },
    buildSubmitPayload() {
      return {
        id: this.form.id,
        villageDeptId: this.form.villageDeptId,
        operatingFixedAssets: this.normalizeMoney(this.form.operatingFixedAssets),
        nonOperatingFixedAssets: this.normalizeMoney(this.form.nonOperatingFixedAssets),
        remark: this.form.remark
      }
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildSubmitPayload()
        if (this.dialogEdit) {
          updateRuralThreeAssets(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addRuralThreeAssets(payload).then(() => {
            this.$modal.msgSuccess(this.dmCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.form = createEmptyForm()
    }
  }
}
</script>

<style scoped>
.rta-section-title {
  margin: 4px 0 12px;
  font-weight: 600;
  color: #303133;
}
.rta-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>
