<template>
  <div class="bpighouse">
    <el-container>
      <el-header>
        <div class="rect rect-form">
          <el-form
            :inline="true"
            :model="dataForm"
            size="mini">
            <el-form-item style="width: 180px">
              <el-input
                v-model="dataForm.key"
                placeholder="猪舍名"
                clearable>
              </el-input>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select v-model="dataForm.feederId" placeholder="养殖员" style="width: 100%">
                <el-option
                  v-for="item in employeeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" @click="getDataList()">查 询</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>
              <el-button 
                icon="el-icon-plus" 
                @click="addOrUpdateHandle()">
                新 增
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-button 
                icon="el-icon-delete" 
                type="danger" 
                @click="deleteHandle()" 
                :disabled="selectionDataList.length <= 0">
                删 除
              </el-button>
            </el-form-item>
          </el-form>
          <el-table
            height="540"
            :data="dataList"
            @selection-change="selectionChangeHandle"
            v-loading="dataListLoading"
            style="width: 100%"
            size="mini"
            border
            stripe
            :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="number"
              header-align="center"
              align="center"
              label="猪舍名">
            </el-table-column>
            <el-table-column
              prop="feederName"
              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="small"
                  @click="addOrUpdateHandle(scope.row)">
                  修改
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="deleteHandle(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination
              @size-change="sizeChangeHandle"
              @current-change="currentChangeHandle"
              :current-page="pageIndex"
              :page-sizes="[10, 20, 30, 50, 100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalPage">
            </el-pagination>
          </div>
          <el-dialog
            :title="!form.id ? '新增' : '修改'"
            :close-on-click-modal="false"
            :visible.sync="visible"
            @close="cancel"
            width="600px">
            <el-form
              :rules="dataRule"
              :model="form"
              ref="form"
              @keyup.enter.native="formSubmit()"
              label-width="80px"
              size="mini"
              style="margin-left: 20px;width: 500px">
              <el-form-item label="猪舍名" prop="number">
                <el-input v-model="form.number" placeholder="猪舍名"></el-input>
              </el-form-item>
              <el-form-item label="养殖员" prop="feederId">
                <el-select v-model="form.feederId" placeholder="请选择养殖员" style="width: 100%">
                  <el-option
                    v-for="item in employeeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button size="mini" @click="cancel">关闭</el-button>
              <el-button size="mini" type="primary" @click="formSubmit()">确定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-main>
    </el-container>
    
    
  </div>
</template>
<script>
export default {
  data() {
    return {
      dataForm: {
        key: "",
        feederId: ''
      },
      dataList: [
        {
          buildTime: "",
          id: "",
          location: "",
          manager: "",
          name: "",
        },
      ],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      selectionDataList: [],
      visible: false,
      form: {
        id: "",
        number: "",
        // farmId: "",
        feederId: "",
      },
      // farmList: [], // 牧场list
      employeeList: [], // 养殖员list
      // TODO: 猪舍编号长度
      dataRule: {
        // farmId: [
        //   { required: true, message: '所属牧场不能为空', trigger: ['blur', 'change'] }
        // ],
        number: [
          { required: true, message: '猪舍名不能为空', trigger: 'blur' }
        ],
        feederId: [
          { required: true, message: '养殖员不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getDataList();
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/management/pigsty/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          keyword: this.dataForm.key || undefined,
          feederId: this.dataForm.feederId || undefined
        })
      }).then(async ({ data }) => {
        // 获取所有养殖员
        let employeeResult = await this.$http({
          url: this.$http.adornUrl("/management/employee/findAll"),
          method: "get",
          params: this.$http.adornParams({})
        });
        employeeResult.data.all && (this.employeeList = employeeResult.data.all)
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 清空查询内容
    clearAll () {
      this.dataForm.key = ''
      this.dataForm.feederId = ''
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 新增 or 修改
    addOrUpdateHandle(row) {
      // 显示猪舍新增 or 修改面板
      this.visible = true;
      if (row) {
        this.form.id = row.id
        for (let key of Object.keys(this.form)) {
          this.form[key] = row[key]
        }
      }
      console.log(row);
      console.log(this.form);
      // 新增时获取养殖员
      this.$http({
        url: this.$http.adornUrl("/management/employee/findAll"),
        method: "get",
        params: this.$http.adornParams({})
      }).then(async ({ data }) => {
        if (data && data.code === 0) {
          this.employeeList = data.all
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    // 选择n个牧场
    selectionChangeHandle(val) {
      this.selectionDataList = val
      // val.forEach((item) => {
      //   this.selectionDataList.push(item.id);
      // });
    },
    // 删除n个牧场
    deleteHandle(pigsty) {
      let ids = pigsty? [pigsty.id]: this.selectionDataList.map(item => item.id)
      let names = pigsty? [pigsty.number]: this.selectionDataList.map(item => item.number)
      console.log(this.selectionDataList);
      this.$confirm(`确定${pigsty ? '删除' : '批量删除'}${names.join()}猪舍？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 删除操作
        if (this.selectionDataList.length <= 0) {
          return;
        }
        this.$http({
          url: this.$http.adornUrl("/management/pigsty/delete"),
          method: "post",
          data: this.$http.adornData(ids, false),
        }).then((result) => {
          console.log(result);
          if (result.data.code === 0) {
            this.$message({
              message: "成功删除猪舍",
              type: "success",
              duration: 1000,
            })
            // pageIndex修正
            this.totalPage -= this.selectionDataList.length
            let pages = Math.ceil(this.totalPage / this.pageSize)
            this.pageIndex = this.pageIndex > pages? pages: this.pageIndex
            this.pageIndex = this.pageIndex < 1? pages: this.pageIndex
          } else {
            // this.$message.error('删除失败：' + result.data.msg)
            this.$confirm(result.data.msg, '删除失败', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              console.log('猪舍编号输入不合法')
            }).catch(() => {})
          }
          this.resetForm();
          this.selectionDataList = [];
        });
      })
      .catch(() => {});
    },
    formSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/management/pigsty/${!this.form.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.form.id || undefined,
              'pigstyId': this.form.pigstyId,
              'feederId': this.form.feederId,
              'farmId': parseInt(this.$cookie.get('formFarmId')),
              'number': this.form.number
            }, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.visible = false
              this.getDataList()
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500
              })
              // this.resetForm()
              this.visible = false
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    // 清空form
    resetForm() {
      for (let i in this.form) {
        this.form[i] = "";
      }
      this.getDataList();
    },
    // 取消
    cancel() {
      this.visible = false
      // 如果修改，则不保留form
      if (this.form.id) {
        this.resetForm()
      }
    },
    // 校验输入是否完整
    validComplete (val) {
      val && (delete this.form.id)
      for (let i in this.form) {
        if (!this.form[i].toString()) {
          return false
        }
      }
      return true
    },
    // 如不完整，则提示
    confirmComplete (val) {
      if (this.validComplete(val)) {
        return true
      }
      this.$confirm(`请输入完整`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('牧场输入不完整')
      }).catch(() => {})
      return false
    }
  }
}
</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>