<template>
  <div style="padding: 20px">
    <template v-if="userItem.type === 0 && type === 1">
      <new-table v-loading="loading" :title="'牧场信息'" :table-items="tableItems1" :list-data="tableData1">
        <template #farmName="scope">
          <span class="fontColor" @click="goFarm(2, scope.row)">{{scope.row.farmName}}</span>
        </template>
        <template #location="scope">
          <span>{{locationText(scope.row.location)}}</span>
        </template>
      </new-table>
    </template>
    <template v-if="type === 2">
      <el-button v-if="userItem.type === 0" type="primary" icon="el-icon-arrow-left" @click="back(1)">返回上一级</el-button>
      <new-table v-loading="loading" :title="'栋舍信息'" :table-items="tableItems2" :list-data="tableData2">
        <template #pigpenName="scope">
          <span class="fontColor" @click="next(3, scope.row)">
            {{scope.row.pigpenName}}
          </span>
        </template>
      </new-table>
    </template>
    <template v-if="type === 3">
      <el-button type="primary" icon="el-icon-arrow-left" @click="back(2)">返回上一级</el-button>
      <new-table v-loading="loading" :title="'单元信息'" :table-items="tableItems3" :list-data="tableData3">
        <template #pigpenName="scope">
           <span class="fontColor" @click="next(4, scope.row)">
            {{scope.row.pigpenName}}
          </span>
        </template>
      </new-table>
    </template>
    <template v-if="type === 4">
      <el-button type="primary" icon="el-icon-arrow-left" @click="back(3)">返回上一级</el-button>
      <new-table v-loading="loading" :title="'耳标信息'" :table-items="tableItems4" :list-data="tableData4">
        <template #earTemp="scope">
          <el-tag style="width: 65px;">{{ scope.row.earTemp }}℃</el-tag>
        </template>
        <template #envTemp="scope">
          <span>{{ scope.row.envTemp }}℃</span>
        </template>
        <template #rssi="scope">
          <span>-{{ scope.row.rssi }}db</span>
        </template>
        <template #stage="scope">
          <span>{{ stageList[scope.row.stage - 1].label }}</span>
        </template>
        <template #dong="scope">
          <span>{{ scope.row.penName }}{{ scope.row.unitName }}</span>
        </template>
        <template #hander="scope">
          <el-button size="mini" type="text" @click="jump(scope.row)"
          >查看详情</el-button
          >
        </template>
      </new-table>
      <table-footer
        :totals="total"
        :size="pageSize"
        @sizeChange="sizeChange"
        @pageChange="pageChange"></table-footer>
    </template>
  </div>
</template>

<script>
import {
  getEarFarmList,
  listFarmPigpen,
  listFarmUnit,
  listFarmUnitEartagData
} from "../../../utils/apis/eartag-data/eartagData";
import NewTable from "../../../components/newTable/NewTable";
import TableFooter from "../../../components/TableFooter";
import {mapState} from "vuex";
import { CodeToText } from "element-china-area-data";

export default {
  name: "FarmData",
  components: {
    NewTable,
    TableFooter
  },
  computed: {
    ...mapState(['stageList'])
  },
  data() {
    return {
      userItem: null,
      // 1 牧场级， 2 栋舍级， 3单元级， 4耳标级
      type: null,
      farmId: null,
      tableData1: [],
      tableItems1: [
        {
          label: '牧场名称',
          prop: 'farmName',
          slotName: 'farmName'
        },
        {
          label: '位置',
          prop: 'location',
          slotName: 'location'
        },
      ],
      tableData2: [],
      tableItems2: [
        {
          label: '栋舍',
          slotName: 'pigpenName'
        }
      ],
      tableData3: [],
      tableItems3: [
        {
          slotName: 'pigpenName',
          label: '单元'
        }
      ],
      tableData4: [],
      tableItems4: [
        {
          prop: 'time',
          label: '采集时间',
          slotName: 'time'
        },
        {
          prop: 'eartagNo',
          label: '耳标号',
          slotName: 'eartagNo'
        },
        {
          label: "耳根温度",
          minWidth: "50",
          slotName: "earTemp",
        },
        {
          label: "环境温度",
          minWidth: "50",
          slotName: "envTemp",
        },
        {
          prop: "exercise",
          label: "运动量",
          minWidth: "50",
          slotName: "exercise",
        },
        {
          prop: "bat",
          label: "电池电量",
          minWidth: "50",
          slotName: "bat",
        },
        {
          label: "信号强度",
          minWidth: "50",
          slotName: "rssi",
        },
        {
          label: "阶段",
          minWidth: "50",
          slotName: "stage",
        },
        {
          label: "栋舍",
          minWidth: "100",
          slotName: "dong",
        },
        {
          prop: "deviceCode",
          label: "采集器编码",
          minWidth: "100",
          slotName: "deviceCode",
        },
        {
          label: "操作",
          minWidth: "50",
          slotName: "hander",
        },
      ],
      loading: false,
      rowId: '',
      // 必须为true 才能请求接口（watch）
      must: true,
      pageNum: 1,
      pageSize: 20,
      total: 0,
    }
  },
  watch: {
    type(newVal) {
      if(newVal === 1 && this.must) {
        this.pageNum = 1;
        this.initFarm();
      } else if(newVal === 2  && this.must) {
        this.init();
      } else if(newVal === 3  && this.must) {
        this.initUnit();
      } else if(newVal === 4  && this.must) {
        this.pageNum = 1;
        this.initEar();
      }
    }
  },
  methods: {
    // 修改size
    sizeChange(val) {
      this.pageSize = val;
      this.initEar();
    },
    // 修改页数
    pageChange(val) {
      this.pageNum = val;
      this.initEar();
    },
    // 拿到牧场列表
    initFarm() {
      this.loading = true;
      let params = {
        type: 2
      }
      getEarFarmList(params).then(res => {
        if(res.code === 10000) {
          this.tableData1 = res.data;
        } else {
          this.$message.error(res.msg)
        }
      }).finally(() => {
        this.loading = false;
      })
    },
    // 获取栋舍
    init() {
      this.loading = true;
      let params = {
        farmId: parseInt(this.farmId)
      }
      listFarmPigpen(params).then(res => {
        if(res.code === 10000) {
          this.tableData2 = res.data;
        } else {
          this.$message.error(res.msg)
        }
      }).finally(() => {
        this.loading = false;
      })
    },
    goFarm(num, row) {
      this.must = true;
      this.type = num;
      this.farmId = row.id;
    },
    // 下一级
    next(num, row) {
      this.must = true;
      this.type = num;
      this.rowId = row.id;
    },
    // 上一级
    back(num) {
      this.must = false;
      this.type = num;
    },
    // 获取单元
    initUnit() {
      this.loading = true
      let params = {
        penId: this.rowId
      }
      listFarmUnit(params).then(res => {
        if(res.code === 10000) {
          this.tableData3 = res.data;
        } else {
          this.$message.error(res.msg)
        }
      }).finally(() => {
        this.loading = false;
      })
    },
    // 获取耳标
    initEar(){
      this.loading = true;
      let params = {
        unitid: this.rowId,
        pageNo: this.pageNum,
        pageSize: this.pageSize
      }
      listFarmUnitEartagData(params).then(res => {
        if(res.code === 10000) {
          this.tableData4 = res.data.records;
          this.total = res.data.total;
        } else {
          this.$message.error(res.msg)
        }
      }).finally(() => {
        this.loading = false;
      })
    },
    locationText(text) {
      const arr = text.split(',');
      let str = '';
      arr.forEach(item => {
        str += CodeToText[item];
      })
      return str
    },
    jump(item) {
      this.$store.commit('SET_KEEPALIVE', ['FarmData'])
      this.$router.push({
        path: "/earTagDetail",
        query: {
          id: item.eartagNo,
        },
      });
    },
  },
  created() {
    this.userItem = JSON.parse(localStorage.getItem('gold_UserItem'));
  },
  mounted() {
    if(this.userItem.type === 0) {
      this.type = 1;
    } else {
      this.farmId = localStorage.getItem('gold_lastFarmId');
      this.type = 2;
      // this.init()
    }
  },
  beforeRouteLeave(to, from, next) {
    if(to.path.indexOf('/earTagDetail') > -1) {
      this.$store.commit('SET_KEEPALIVE', ['FarmData'])
    } else {
      this.$store.commit('SET_KEEPALIVE', [''])
    }
    next()
  }
}
</script>

<style scoped>
  .fontColor {
    cursor: pointer;
    color: #009cff;
  }
</style>
