<template>
  <div class="mod-role">
    <el-container>
      <!-- form表单 -->
      <el-header>
        <div class="rect rect-form">
          <el-form :inline="true" :model="form" size="mini" ref="form">
            <el-form-item>
              <el-input v-model="form.eartag" placeholder="耳标" clearable></el-input>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select placeholder="性别" v-model="form.sex">
                <el-option
                  v-for="item in gender"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select placeholder="品种" v-model="form.breed">
                <el-option
                  v-for="item in breedList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select placeholder="健康状态" v-model="form.healthStatus">
                <el-option
                  v-for="item in healthStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select placeholder="养殖状态" v-model="form.outFenceStatus">
                <el-option
                  v-for="item in outFenceStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select placeholder="猪舍" v-model="form.pigstyId" @change="pigstyChange">
                <el-option
                  v-for="item in pigstyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select 
                placeholder="单元" 
                v-model="form.unitId" 
                ref="unit"
                @focus="selectFocus('unit')">
                <el-option
                  v-for="item in unitSelectedList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select 
                placeholder="栏期" 
                v-model="form.periodId" 
                ref="period"
                @focus="selectFocus('period')">
                <el-option
                  v-for="item in periodSelectedList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button @click="getDataList()" icon="el-icon-search">查 询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button 
                icon="el-icon-circle-close"
                @click="clearAll">清 空</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <!-- 猪只基本信息表格 -->
      <el-main>
        <div class="rect rect-table">
          <el-form inline size="mini">
            <el-form-item label="耳标信息的时间区间">
              <el-date-picker
                v-model="time"
                type="datetimerange"
                align="right"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="timeChange"
                ref="timePicker"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-form>
          <el-table
            :data="dataList"
            border
            stripe
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            style="width: 100%;"
            size="mini"
            height="540"
            :header-cell-style="{background:'rgb(245,245,245)',color:'#000',height: '45px',fontSize: '13px',fontWeight: 'normal',borderBottom: '1px solid #ccc'}" 
            :cell-style="{color: '#888',fontSize: '13px'}">
            <el-table-column
              type="selection"
              header-align="center"
              align="center"
              width="50">
            </el-table-column>
            <el-table-column
              prop="id"
              header-align="center"
              align="center"
              label="id"
              width="80">
            </el-table-column>
            <el-table-column
              prop="eartag"
              header-align="center"
              align="center"
              label="耳标">
            </el-table-column>
            <el-table-column
              prop="sex"
              header-align="center"
              align="center"
              label="性别"
              width="80">
            </el-table-column>
            <el-table-column
              prop="birthday"
              header-align="center"
              align="center"
              label="出生日期">
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="健康状态"
              width="100">
              <template slot-scope="scope">
                <span>{{scope.row.healthStatus? '健康': '不健康'}}</span>
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="养殖状态"
              width="100">
              <template slot-scope="scope">
                <span>{{scope.row.outFenceStatus? '出栏': '育肥'}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="breed"
              header-align="center"
              align="center"
              label="品种"
              width="100">
            </el-table-column>
            <el-table-column
              prop="pigstyName"
              header-align="center"
              align="center"
              label="猪舍">
            </el-table-column>
            <el-table-column
              prop="unitName"
              header-align="center"
              align="center"
              label="单元">
            </el-table-column>
            <el-table-column
              prop="periodName"
              header-align="center"
              align="center"
              label="栏期">
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="medium"
                  style="color: rgb(24,144,255)"
                  @click="eartagDialogHandle(scope.row.eartag)">
                  查看耳标信息
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </div>
      </el-main>

      <beartag-dialog v-if="dialogVisible" ref="eartagDialog" :time="time"></beartag-dialog>
      
      
    </el-container>
  </div>
</template>

<script>
  import beartagDialog from './beartag-dialog.vue'
  export default {
    data () {
      return {
        form: {
          eartag: '',
          sex: '',
          breed: '',
          healthStatus: '',
          outFenceStatus: '',
          periodId: '',
          pigstyId: '',
          unitId: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        farmId: undefined,
        gender: [
          {
            value: '公',
            label: '公'
          },
          {
            value: '母',
            label: '母'
          }
        ],
        breedList: [],
        healthStatus: [
          {
            value: 1,
            label: '健康'
          },
          {
            value: 0,
            label: '不健康'
          }
        ],
        outFenceStatus: [
          {
            value: 0,
            label: '育肥'
          },
          {
            value: 1,
            label: '出栏'
          }
        ],
        periodList: [], // 所有栏期
        periodSelectedList: [], // 根据栋舍限制的栏期
        pigstyList: [], // 所有栋舍
        unitList: [], // 所有单元
        unitSelectedList: [], // 根据栋舍限制的单元
        labelPosition: 'right',
        dialogVisible: false, // 控制 耳标信息dialog 的显示
        time: [new Date((new Date()).getTime() - 7*24*3600*1000), new Date()] // 查看耳标信息时要传入的值，默认七天之内的数据
      }
    },
    components: {
      beartagDialog
    },
    activated () {
      this.getDataList()
    },
    methods: {
      timeFormat (date) {
        let y = date.getFullYear();  
        let m = date.getMonth() + 1;  
        m = m < 10 ? ('0' + m) : m;  
        let d = date.getDate();  
        d = d < 10 ? ('0' + d) : d;  
        let h = date.getHours();  
        h=h < 10 ? ('0' + h) : h;  
        let minute = date.getMinutes();  
        minute = minute < 10 ? ('0' + minute) : minute;  
        let second=date.getSeconds();  
        second=second < 10 ? ('0' + second) : second;  
        return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
      },
      // 获取数据列表
      getDataList (val) {
        // Date.prototype.format = function(fmt) { 
        //   var o = { 
        //     "M+" : this.getMonth()+1,                 //月份 
        //     "d+" : this.getDate(),                    //日 
        //     "h+" : this.getHours(),                   //小时 
        //     "m+" : this.getMinutes(),                 //分 
        //     "s+" : this.getSeconds(),                 //秒 
        //     "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        //     "S" : this.getMilliseconds()             //毫秒 
        //   }; 
        //   if(/(y+)/.test(fmt)) {
        //     fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
        //   }
        //   for(var k in o) {
        //     if(new RegExp("("+ k +")").test(fmt)){
        //       fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        //     }
        //   }
        //   return fmt; 
        // }
        // let now = new Date()
        // this.time[0] = new Date(now.getTime() - 7*24*3600*1000).format('yyyy-MM-dd hh:mm:ss')
        // this.time[1] = now.format('yyyy-MM-dd hh:mm:ss')
        
        // 默认时间设置
        let now = new Date()
        this.time[0] = this.timeFormat(new Date(now.getTime() - 7*24*3600*1000))
        this.time[1] = this.timeFormat(new Date())
        console.log(this.time);

        this.dataListLoading = true
        
        // 对 新增or删除 操作，当前页为最后一页
        if (val) {
          let valArr = val.split('-')
          let total = 0
          if (valArr[0] === 'add') {
            total = this.totalPage + parseInt(valArr[1])
          } else if (valArr[0] === 'del') {
            total = this.totalPage - parseInt(valArr[1])
          }
          this.pageIndex = Math.ceil(total / this.pageSize)
        }
        this.$http({
          url: this.$http.adornUrl('/management/yearpigbase/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'eartag': this.form.eartag || undefined,
            'sex': this.form.sex || undefined,
            'breed': this.form.breed || undefined,
            'healthStatus': this.form.healthStatus || (this.form.healthStatus === 0?this.form.healthStatus: undefined),
            'outFenceStatus': this.form.outFenceStatus || (this.form.outFenceStatus === 0?this.form.outFenceStatus: undefined),
            'periodId': this.form.periodId || undefined,
            'pigstyId': this.form.pigstyId || undefined,
            'unitId': this.form.unitId || undefined
          })
        }).then(async({data}) => {
          // 猪舍List
          this.pigstyList = []
          let pigstyList = []
          let pigstyR = await this.$http({
            url: this.$http.adornUrl("/management/pigsty/findAll"),
            method: "get",
            params: this.$http.adornParams({})
          })
          pigstyR.data.all && (pigstyList = pigstyR.data.all)
          pigstyList.forEach(pigsty => {
            let item = {
              value: pigsty.id,
              label: pigsty.number
            }
            this.pigstyList.push(item)
          })
          // 单元List
          this.unitList = []
          let unitList = []
          let unitR = await this.$http({
            url: this.$http.adornUrl("/management/unit/findAll"),
            method: "get",
            params: this.$http.adornParams({})
          })
          unitR.data.all && (unitList = unitR.data.all)
          unitList.forEach(unit => {
            let item = {
              value: unit.id,
              label: unit.number,
              pigstyId: unit.pigstyId
            }
            this.unitList.push(item)
          })
          this.unitSelectedList = this.unitList
          // 栏期List
          this.periodList = []
          let periodList = []
          let periodR = await this.$http({
            url: this.$http.adornUrl("/management/period/findAll"),
            method: "get",
            params: this.$http.adornParams({})
          })
          periodR.data.all && (periodList = periodR.data.all)
          periodList.forEach(period => {
            let item = {
              value: period.id,
              label: period.number,
              pigstyId: period.pigstyId
            }
            this.periodList.push(item)
          })
          // 点击查询后，保留单元和栏期的下拉框符合猪舍的选择
          this.form.pigstyId? this.periodSelectedList = this.periodList.filter(item => item.pigstyId === this.form.pigstyId): this.periodSelectedList = this.periodList
          this.form.pigstyId? this.unitSelectedList = this.unitList.filter(item => item.pigstyId === this.form.pigstyId): this.unitSelectedList = this.unitList
          // 品种List
          this.breedList = []
          let breedList = []
          let breedR = await this.$http({
            url: this.$http.adornUrl("/management/basebloodline/findAll"),
            method: "get",
            params: this.$http.adornParams({})
          })
          breedR.data.all && (breedList = breedR.data.all)
          breedList.forEach(breed => {
            let item = {
              value: breed.name,
              label: breed.name
            }
            this.breedList.push(item)
          })
          // 获取猪只List
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
            this.$message.error(data.msg)
          }
          this.dataListLoading = false
        })
      },
      // 根据栋舍选择限制单元和栏期
      pigstyChange (val) {
        this.unitSelectedList = this.unitList.filter(item => item.pigstyId === val)
        this.periodSelectedList = this.periodList.filter(item => item.pigstyId === val)
      },
      // 点击 单元or栏期的选择框
      selectFocus (val) {
        if (!this.form.pigstyId) {
          this.$message.error('请先选择猪舍')
          this.form[val + 'Id'] = ''
          setTimeout(() => {
            this.$refs[val].blur()
          }, 10)
        }
      },
      // form表单清空，单元SelectedList 和 栏期SelectedList重置
      clearAll () {
        for (let i in this.form) {
          this.form[i] = ''
        }
        this.unitSelectedList = this.unitList
        this.periodSelectedList = this.periodList
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      timeChange (val) {
        let start = new Date(val[0])
        let end = new Date(val[1])
        let now = new Date()
        // if (start > now || end > now) {
        //   this.time = []
        //   this.$message.error('请勿选择超出现在的时刻')
        // }
      },
      // 点击 “查看耳标信息” 按钮
      eartagDialogHandle (eartag) {
        if (this.time.length < 1) {
          this.$message.error('请先选择耳标信息的时间区间')
          return
        }
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.eartagDialog.init(eartag)
        })
        console.log(this.time);
      }
    },
    watch: {
      'form.pigstyId': {
        handler(newValue, oldValue) {
          if (oldValue) {
            this.form.unitId = ''
            this.form.periodId = ''
            this.unitSelectedList = this.unitList.filter(item => item.pigstyId === newValue)
            this.periodSelectedList = this.periodList.filter(item => item.pigstyId === newValue)
          }
        }
      }
    }
  }
</script>
<style scoped>
.rect {
  background-color: #fff;
  padding: 30px 15px;
  border-radius: 5px;
  border: 1px solid #e8e8e8;
}
.rect-form {
  padding-bottom: 10px;
}
.rect-table {
  margin-top: 20px;
}
.demo-table-expand {
  font-size: 0;
  margin-left: 40px;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 80%;
}
.el-table .height {
  background: rgba(254, 254, 254, 0.5);
}
/deep/ .el-table--mini td, .el-table--mini th {
  padding: 3px 0 !important;
  height: 20px !important;
}
/deep/ .el-checkbox__input.is-checked+.el-checkbox__label {
  color: rgb(24,144,255);
  background-color: rgb(24,144,255);
  border-color: rgb(24,144,255);
}
/deep/.el-table .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: rgb(24,144,255);
  border-color: rgb(24,144,255);
}
/deep/.el-table .el-checkbox__inner:hover {
  border-color: rgb(24,144,255);
}
/deep/.el-table .el-checkbox__input.is-focus .el-checkbox__inner {
  border-color: rgb(24,144,255);
}
/deep/.el-table #select .cell .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: rgb(24,144,255);
  border-color: rgb(24,144,255);
}
</style>
