<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="keyword">
          <template slot="label">{{ lfT("queryYakNo") }}</template>
          <el-input
            v-model="queryParams.keyword"
            :placeholder="lfT('queryYakNoPh')"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="assetStatus">
          <template slot="label">{{ lfT("queryAssetStatus") }}</template>
          <el-select v-model="queryParams.assetStatus" :placeholder="lfCommon('pleaseSelect')" clearable style="width: 140px">
            <el-option v-for="item in assetStatusOptions" :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">{{ lfCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ lfCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['dataModel:yakAsset:sync']"
            type="warning"
            plain
            icon="el-icon-refresh"
            size="mini"
            :loading="syncing"
            @click="handleSync"
          >{{ lfT("btnSync") }}</el-button>
        </el-form-item>
      </el-form>
      <div v-if="lastSyncHint" class="yak-list__sync-hint">{{ lastSyncHint }}</div>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border>
        <el-table-column :label="lfT('colYakNo')" prop="yakNo" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="lfT('colPastureName')" prop="pastureName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="lfT('colGender')" prop="gender" align="center" width="70" />
        <el-table-column :label="lfT('colAgeMonths')" align="center" width="80">
          <template slot-scope="scope">{{ formatAgeMonths(scope.row.ageMonths) }}</template>
        </el-table-column>
        <el-table-column :label="lfT('colRealtimeTemp')" align="center" width="100">
          <template slot-scope="scope">{{ formatWithUnit(scope.row.realtimeTemp, lfCommon('unitCelsius')) }}</template>
        </el-table-column>
        <el-table-column :label="lfT('colRealtimeSteps')" align="center" width="100">
          <template slot-scope="scope">{{ formatWithUnit(scope.row.realtimeSteps, lfCommon('unitStep')) }}</template>
        </el-table-column>
        <el-table-column :label="lfT('colAssetStatus')" align="center" width="90">
          <template slot-scope="scope">
            <el-tag :type="assetStatusTagType(scope.row.assetStatus)" size="small">{{ assetStatusLabel(scope.row.assetStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="lfT('colStatusChangeDate')" prop="statusChangeDate" align="center" width="110" />
        <el-table-column :label="lfCommon('colOp')" align="center" width="80" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['dataModel:yakAsset:query']" type="text" size="mini" @click="handleView(scope.row)">{{ lfCommon("view") }}</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>

    <yak-asset-detail-drawer :visible.sync="detailOpen" :asset-id="detailAssetId" />
  </div>
</template>

<script>
import livestockFinanceLocaleMixin from "@/mixins/livestockFinanceLocaleMixin"
import { listYakAsset, syncYakAsset } from "@/api/livestockFinance/yakAsset"
import YakAssetDetailDrawer from "./detailDrawer"

export default {
  name: "YakAsset",
  components: { YakAssetDetailDrawer },
  mixins: [livestockFinanceLocaleMixin],
  data() {
    return {
      lfNs: "yakAsset",
      loading: false,
      syncing: false,
      total: 0,
      tableList: [],
      lastSyncHint: "",
      detailOpen: false,
      detailAssetId: undefined,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        keyword: undefined,
        assetStatus: undefined
      }
    }
  },
  computed: {
    assetStatusOptions() {
      return [1, 2, 3, 4].map((value) => ({
        value,
        label: this.lfT("status" + value)
      }))
    }
  },
  created() {
    this.getList()
  },
  methods: {
    assetStatusLabel(status) {
      if (status == null || status < 1 || status > 4) {
        return this.lfCommon("dash")
      }
      return this.lfT("status" + status)
    },
    assetStatusTagType(status) {
      if (status === 2 || status === 3) {
        return "danger"
      }
      if (status === 4) {
        return "warning"
      }
      if (status === 1) {
        return "success"
      }
      return "info"
    },
    syncStepCounts(step) {
      const s = step || {}
      return {
        insert: s.insertCount != null ? s.insertCount : 0,
        update: s.updateCount != null ? s.updateCount : 0,
        fail: s.failCount != null ? s.failCount : 0
      }
    },
    collectSyncFailMessages(data) {
      const steps = ["pasture", "enclosure", "plan", "batch", "yakAsset"]
      const labels = {
        pasture: this.lfT("syncStepPasture"),
        enclosure: this.lfT("syncStepEnclosure"),
        plan: this.lfT("syncStepPlan"),
        batch: this.lfT("syncStepBatch"),
        yakAsset: this.lfT("syncStepYakAsset")
      }
      const messages = []
      steps.forEach((key) => {
        const step = data[key]
        if (step && step.failMessages && step.failMessages.length) {
          step.failMessages.forEach((msg) => {
            messages.push(`${labels[key]}: ${msg}`)
          })
        }
      })
      return messages
    },
    formatAgeMonths(val) {
      if (val == null || val === "") {
        return this.lfCommon("dash")
      }
      return `${val}${this.lfCommon("unitMonth")}`
    },
    formatWithUnit(val, unit) {
      if (val == null || val === "") {
        return this.lfCommon("dash")
      }
      return `${val}${unit}`
    },
    getList() {
      this.loading = true
      listYakAsset(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.keyword = undefined
      this.queryParams.assetStatus = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleView(row) {
      this.detailAssetId = row.id
      this.detailOpen = true
    },
    handleSync() {
      this.runSyncWithLoading(() => syncYakAsset())
        .then((res) => {
          const data = res.data || {}
          const pasture = this.syncStepCounts(data.pasture)
          const enclosure = this.syncStepCounts(data.enclosure)
          const plan = this.syncStepCounts(data.plan)
          const batch = this.syncStepCounts(data.batch)
          const yakAsset = this.syncStepCounts(data.yakAsset)
          this.$modal.msgSuccess(
            this.lfT("syncMasterSummary", {
              pInsert: pasture.insert,
              pUpdate: pasture.update,
              pFail: pasture.fail,
              eInsert: enclosure.insert,
              eUpdate: enclosure.update,
              eFail: enclosure.fail,
              plInsert: plan.insert,
              plUpdate: plan.update,
              plFail: plan.fail,
              bInsert: batch.insert,
              bUpdate: batch.update,
              bFail: batch.fail,
              yInsert: yakAsset.insert,
              yUpdate: yakAsset.update,
              yFail: yakAsset.fail
            })
          )
          const failMessages = this.collectSyncFailMessages(data)
          if (failMessages.length) {
            this.$modal.msgWarning(failMessages.join("；"))
          }
          if (data.syncTime) {
            this.lastSyncHint = this.lfT("syncTimeHint", { time: this.parseTime(data.syncTime) })
          }
          this.getList()
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped>
.yak-list__sync-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}
</style>
