<template>
  <div class="pbbasic">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input
          v-model="dataForm.key"
          placeholder="牧场关键字"
          clearable>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-if="isAuth('sys:role:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-if="isAuth('sys:role:delete')" type="danger" @click="deleteHandle()" :disabled="selectionDataList.length <= 0">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      @selection-change="selectionChangeHandle"
      v-loading="dataListLoading"
      style="width: 100%">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="耳标">
              <span>{{ props.row.eartag }}</span>
            </el-form-item>
            <el-form-item label="年龄">
              <span>{{ props.row.dayAge }}天</span>
            </el-form-item>
            <el-form-item label="健康状况">
              <span>{{ props.row.healthStatus? '健康': '不健康' }}</span>
            </el-form-item>
            <el-form-item label="体重">
              <span>{{ props.row.weight }}千克</span>
            </el-form-item>
            <el-form-item label="品种">
              <span>{{ props.row.variety }}</span>
            </el-form-item>
            <el-form-item label="去向">
              <span>{{ props.row.whereDidYouGo }}</span>
            </el-form-item>
            <el-form-item label="所属单元">
              <span>{{ props.row.number }}</span>
            </el-form-item>
            <el-form-item label="所属猪舍">
              <span>{{ props.row.phNumber }}</span>
            </el-form-item>
            <el-form-item label="所属牧场">
              <span>{{ props.row.name }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        prop="eartag"
        header-align="center"
        align="center"
        label="年猪耳标">
      </el-table-column>
      <el-table-column
        prop="number"
        header-align="center"
        align="center"
        label="所属单元">
      </el-table-column>
      <el-table-column
        prop="phNumber"
        header-align="center"
        align="center"
        label="所属猪舍">
      </el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="所属牧场">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('sys:user:update')" type="text" size="small" @click="addOrUpdateHandle(scope.row)">修改</el-button>
          <el-button v-if="isAuth('sys:user:delete')" type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :title="!form.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="cancel">
      <el-form :model="form" ref="form" @keyup.enter.native="formSubmit()" label-width="80px">
        <el-form-item label="所属牧场">
          <el-select v-model="form.pastureId" placeholder="请选择所属牧场" @change="getPasture" ref="pasture">
            <el-option
              v-for="item in pastureList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属猪舍">
          <el-select v-model="form.pigstyId" placeholder="请选择所属猪舍" @change="getPigsty">
            <el-option
              v-for="item in phSelectedList"
              :key="item.id"
              :label="item.number"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单元序号">
          <!-- <el-input v-model="form.number" placeholder="请输入单元序号"></el-input> -->
          <el-select v-model="form.unitId" placeholder="请选择所属单元" @change="getUnit">
            <el-option
              v-for="item in unSelectedList"
              :key="item.id"
              :label="item.number"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="耳标">
          <el-input v-model="form.eartag" placeholder="请输入耳标"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="form.dayAge" placeholder="请输入年龄（天）"></el-input>
        </el-form-item>
        <el-form-item label="健康状况">
          <el-select v-model="form.healthStatus" placeholder="请输入健康状况">
            <el-option
              v-for="item in health"
              :key="item.label"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="体重">
          <el-input v-model="form.weight" placeholder="请输入体重（千克）"></el-input>
        </el-form-item>
        <el-form-item label="品种">
          <el-input v-model="form.variety" placeholder="请输入去向"></el-input>
        </el-form-item>
        <el-form-item label="去向">
          <el-input v-model="form.whereDidYouGo" placeholder="请输入去向"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="formSubmit()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      dataForm: {
        key: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      selectionDataList: [],
      visible: false,
      form: {
        id: '',
        unitId: '',
        weight: '',
        whereDidYouGo: '',
        dayAge: '',
        eartag: '',
        healthStatus: '',
        variety: ''
      },
      pastureList: [], // 牧场list
      pighouseList: [], // 猪舍list
      phSelectedList: [], // 选择过牧场后的猪舍list
      unitList: [], // 单元list
      unSelectedList: [], // 选择过后的单元list
      health: [
        {
          value: true,
          label: '健康'
        },
        {
          value: false,
          label: '不健康'
        }
      ]
    }
  },
  mounted () {
    this.getDataList()
  },
  methods: {
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/management/yearpigbase/list'),
        method: 'post'
      }).then(async ({ data }) => {
        // 获取所有牧场
        let pastureResult = await this.$http({
          url: this.$http.adornUrl('/management/pasture/list'),
          method: 'post'
        })
        this.pastureList = pastureResult.data.page.list
        // 获取所有猪舍
        let pighouseResult = await this.$http({
          url: this.$http.adornUrl('/management/pigsty/list'),
          method: 'post'
        })
        this.pighouseList = pighouseResult.data.page.list
        // 获取所有单元
        let unitResult = await this.$http({
          url: this.$http.adornUrl('/management/unit/list'),
          method: 'post'
        })
        this.unitList = unitResult.data.page.list
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
          // 单元对应
          this.dataList.forEach(item => {
            for (let unit of this.unitList) {
              if (item.unitId === unit.id) {
                item.number = unit.number
                item.pastureId = unit.pastureId
                item.pigstyId = unit.pigstyId
                break
              }
            }
          });
          // 牧场对应
          this.dataList.forEach(item => {
            for (let pasture of this.pastureList) {
              if (item.pastureId === pasture.id) {
                item.name = pasture.name
                break
              }
            }
          });
          // 猪舍对应
          this.dataList.forEach(item => {
            for (let pighouse of this.pighouseList) {
              if (item.pigstyId === pighouse.id) {
                item.phNumber = pighouse.number
                break
              }
            }
          });
          // 初始化时，选择后的与未选择的list相同
          this.phSelectedList = this.pighouseList
          this.unSelectedList = this.unitList
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 获取到了牧场 → 猪舍 + 单元处理
    getPasture (val) {
      /** 关于猪舍 */
      //  → 限制猪舍
      this.phSelectedList = []
      this.pighouseList.forEach(item => {
        if (item.pastureId === val) {
          this.phSelectedList.push(item)
        }
      });
      // 如果已有选中的猪舍，且该猪舍不属于该牧场，则清空猪舍选择
      let i;
      for (i = 0; i < this.phSelectedList.length; i++) {
        let item = this.phSelectedList[i];
        if (item.id === this.form.pigstyId) {
          break
        }
      }
      if (i === this.phSelectedList.length) {
        this.form.pigstyId = ''
      }
      /** 关于单元 */
      //  → 限制单元
      this.unSelectedList = []
      this.unitList.forEach(item => {
        if (item.pastureId === val) {
          this.unSelectedList.push(item)
        }
      });
      // 如果已有选中的单元，且该猪舍不属于该牧场，则清空单元选择
      let j;
      for (j = 0; j < this.unSelectedList.length; j++) {
        let item = this.unSelectedList[j];
        if (item.id === this.form.pastureId) {
          break
        }
      }
      if (j === this.unSelectedList.length) {
        this.form.unitId = ''
      }
    },
    // 获取到猪舍 → 牧场 + 猪舍自身 + 单元处理
    getPigsty (val) {
      //  → 反向确定牧场
      for (let item of this.pighouseList) {
        if (item.id === val) {
          this.form.pastureId = item.pastureId
          break
        }
      }
      // → 先获取猪舍，没有确定牧场的情况下，限制猪舍自身
      this.phSelectedList = []
      this.pighouseList.forEach(item => {
        if (item.pastureId === this.form.pastureId) {
          this.phSelectedList.push(item)
        }
      });
      /** 关于单元 */
      // → 限制单元
      this.unSelectedList = []
      this.unitList.forEach(item => {
        if (item.pigstyId === val) {
          this.unSelectedList.push(item)
        }
      });
      // 如果已有选中的单元，且该猪舍不属于该牧场，则清空单元选择
      let j;
      for (j = 0; j < this.unSelectedList.length; j++) {
        let item = this.unSelectedList[j];
        if (item.id === this.form.pastureId) {
          break
        }
      }
      if (j === this.unSelectedList.length) {
        this.form.unitId = ''
      }
    },
    // 获取到了单元 → 牧场 + 猪舍 + 单元自身处理
    getUnit (val) {
      // → 反向确定牧场 + 牧场
      for (let item of this.unSelectedList) {
        if (item.id === val) {
          this.form.pastureId = item.pastureId
          this.form.pigstyId = item.pigstyId
        }
      }
      // → 先获取单元，在没有确定牧场+猪舍的情况下，限制猪舍
      this.phSelectedList = []
      this.pighouseList.forEach(item => {
        if (item.pastureId === this.form.pastureId) {
          this.phSelectedList.push(item)
        }
      });
      // → 先获取单元，在没有确定牧场+猪舍的情况下，限制单元自身
      this.unSelectedList = []
      this.unitList.forEach(item => {
        if (item.pigstyId === this.form.pigstyId) {
          this.unSelectedList.push(item)
        }
      });
    },
    // 新增 or 修改单元
    addOrUpdateHandle (row) {
      // 显示牧场新增 or 修改面板
      this.visible = true
      if (row) {
        this.form = row
        console.log(row);
      }
    },
    // 选择n个牧场
    selectionChangeHandle (val) {
      this.selectionDataList = []
      val.forEach(item => {
        this.selectionDataList.push(item.id)
      });
    },
    // 删除n个牧场
    deleteHandle (id) {
      this.$confirm(`确定删除年猪？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除操作
        if (id) {
          this.selectionDataList.push(id)
        }
        if (this.selectionDataList.length <= 0) {
          return
        }
        this.$http({
          url: this.$http.adornUrl('/management/yearpigbase/delete'),
          method: 'post',
          data: this.$http.adornData(this.selectionDataList, false)
        }).then(result => {
          if (result.data.code === 0) {
            this.getDataList()
            this.resetForm()
            this.$message({
              message: '成功删除年猪',
              type: 'success',
              duration: 1000
            })
          } else {
            this.$message.error('删除年猪失败');
          }
          this.selectionDataList = []
        })
      }).catch(() => {})
    },
    formSubmit () {
      if (this.form.id) {
        // 修改
        if (this.confirmInput()) {
          // 进行修改操作
          this.$http({
            url: this.$http.adornUrl('/management/yearpigbase/update'),
            method: 'post',
            data: this.$http.adornData({
              id: this.form.id,
              unitId: this.form.unitId,
              dayAge: parseInt(this.form.dayAge),
              eartag: this.form.eartag,
              healthStatus: this.form.healthStatus,
              weight: parseInt(this.form.weight),
              whereDidYouGo: this.form.whereDidYouGo,
              variety: this.form.variety
            })
          }).then(result => {
            if (result.data.code === 0) {
              this.resetForm();
              this.visible = false;
              this.$message({
                message: '成功修改年猪信息',
                type: 'success',
                duration: 1000
              })
            } else {
              this.$message.error('修改年猪信息失败');
            }
          })
        } else {
          // 请输入完整
          this.$confirm(`请输入完整`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            return
          }).catch(() => {})
        }
      } else {
        // 新增
        if (this.confirmInput(1)) {
          // 进行新增操作
          console.log('进行新增操作');
          this.$http({
            url: this.$http.adornUrl('/management/yearpigbase/save'),
            method: 'post',
            data: this.$http.adornData({
              unitId: this.form.unitId,
              dayAge: parseInt(this.form.dayAge),
              eartag: this.form.eartag,
              healthStatus: this.form.healthStatus,
              weight: parseInt(this.form.weight),
              whereDidYouGo: this.form.whereDidYouGo,
              variety: this.form.variety
            })
          }).then(result => {
            console.log(result);
            if (result.data.code === 0) {
              this.resetForm();
              this.visible = false;
              this.$message({
                message: '成功添加年猪',
                type: 'success',
                duration: 1000
              })
            } else {
              this.$message.error('添加年猪失败');
            }
          })
        } else {
          // 请输入完整
          this.$confirm(`请输入完整`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            return
          }).catch(() => {})
        }
      }
    },
    // 判断新增/修改时是否输入完整
    confirmInput (val) {
      console.log('判断是否输入完整');
      console.log(val);
      val && (delete this.form.id, delete this.form.deleted, delete this.form.fosterStatus, delete this.form.gmtCreate, delete this.form.gmtModified, delete this.form.name, delete this.form.number, delete this.form.phNumber)
      console.log(this.form);
      for (let i in this.form) {
        if (!this.form[i].toString()) {
          return false
        }
      }
      return true
    },
    // 清空form
    resetForm () {
      for (let i in this.form) {
        this.form[i] = ''
      }
      this.getDataList()
    },
    // 取消
    cancel () {
      this.visible = false
      this.resetForm()
    }
  }
}
</script>
<style>
.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%;
}
</style>