<template>
  <div class="bunit">
    <el-container>
      <el-header>
        <div class="rect rect-form">
          <el-form
            :inline="true"
            :model="dataForm"
            size="mini">
            <el-form-item style="width: 140px">
              <el-select 
                v-model="dataForm.pigstyId" 
                placeholder="猪舍" 
                style="width: 100%">
                <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 style="width: 140px">
              <el-select 
                v-model="dataForm.unitId" 
                placeholder="单元" 
                style="width: 100%"
                ref="unit"
                @focus="selectFocus('unit')">
                <el-option
                  v-for="item in unitSelectedList"
                  :key="item.id"
                  :label="item.number"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 180px">
              <el-input
                v-model="dataForm.key"
                placeholder="栏期编号"
                clearable>
              </el-input>
            </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="unitName"
              header-align="center"
              align="center"
              label="单元">
            </el-table-column>
            <el-table-column
              prop="pigstyName"
              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
                  type="text"
                  size="small"
                  @click="addOrUpdateHandle(scope.row)">
                  修改
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="deleteHandle(scope.row.id)">
                  删除
                </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 
              :model="form" 
              ref="form" 
              @keyup.enter.native="formSubmit()" 
              label-width="80px" 
              :rules="dataRule"
              size="mini"
              style="margin-left: 20px;width: 500px">
              <!-- <el-form-item label="所属牧场" prop="farmId">
                <el-select v-model="form.farmId" placeholder="请选择所属牧场" @change="getPasture" style="width: 100%">
                  <el-option
                    v-for="item in farmList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item label="猪舍" prop="pigstyId">
                <el-select 
                  v-model="form.pigstyId" 
                  placeholder="请选择所属猪舍" 
                  style="width: 100%">
                  <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="单元" prop="unitId">
                <el-select 
                  v-model="form.unitId" 
                  placeholder="单元" 
                  style="width: 100%"
                  ref="unitDialog"
                  @focus="selectFocus()">
                  <el-option
                    v-for="item in unitSelectedList"
                    :key="item.id"
                    :label="item.number"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item v-if="this.form.id" label="栏期" prop="number">
                <el-input v-model="form.number"></el-input>
              </el-form-item> -->
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button size="small" @click="cancel">关闭</el-button>
              <el-button size="small" type="primary" @click="formSubmit()">确定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script>
export default {
  data () {
    return {
      dataForm: {
        key: ''
      },
      dataList: [
        {
          id: '',
          number: '',
          phNumber: '',
          name: ''
        }
      ],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      selectionDataList: [],
      visible: false,
      form: {
        id: '',
        pigstyId: '',
        number: '',
        unitId: ''
      },
      pigstyList: [], // 猪舍list
      pighouseList: [], // 猪舍list
      phSelectedList: [], // 选择过牧场后的猪舍list
      unitList: [],
      unitSelectedList: [],
      dataRule: {
        pigstyId: [
          { required: true, message: '所属猪舍不能为空', trigger: 'blur' }
        ],
        // number: [
        //   { required: true, message: '栏期编号不能为空', trigger: ['blur', 'change'] },
        //   { type: 'string' , message: '只允许输入中英文、数字、-与_', pattern: /[\w\u4E00-\u9FA5\-]+$/g },
        //   { min: 1, max: 20, message: '长度在 1 到 20 个字符之间', trigger: ['blur', 'change'] }
        // ],
        unitId: [
          { required: true, message: '单元编号不能为空', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  activated () {
    this.getDataList()
  },
  methods: {
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/management/period/list'),
        method: 'get',
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: 10,
          keyword: this.dataForm.key || undefined,
          pigstyId: this.dataForm.pigstyId || undefined,
          unitId: this.dataForm.unitId || undefined
        })
      }).then(async ({ data }) => {
        // 获取所有猪舍
        let pighouseResult = await this.$http({
          url: this.$http.adornUrl('/management/pigsty/findAll'),
          method: 'get',
          params: this.$http.adornParams({})
        })
        pighouseResult.data.all && (this.pigstyList = pighouseResult.data.all)
        this.phSelectedList = this.pigstyList
        // 获取所有单元
        let unitResult = await this.$http({
          url: this.$http.adornUrl('/management/unit/findAll'),
          method: 'get',
          params: this.$http.adornParams({})
        })
        unitResult.data.all && (this.unitList = unitResult.data.all)
        this.unitSelectedList = this.unitList
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 点击 单元or栏期的选择框
    selectFocus (val) {
      let form = val === 'unit'? 'dataForm': 'form'
      let unit = val === 'unit'? 'unit': 'unitDialog'
      if (!this[form].pigstyId) {
        this.$message.error('请先选择猪舍')
        setTimeout(() => {
          this.$refs[unit].blur()
        }, 10)
      }
    },
    // 清空查询内容
    clearAll () {
      this.dataForm.key = ''
      this.dataForm.pigstyId = ''
      this.dataForm.unitId = ''
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // // 根据栋舍选择限制栏期
    // pigstyChange (val) {
    //   this.unitSelectedList = this.unitList.filter(item => item.pigstyId === val)
    //   console.log(this.unitSelectedList);
    //   // this.periodSelectedList = this.periodList.filter(item => item.pigstyId === val)
    // },
    // // 需要先选择猪舍，才能选择单元或栏期
    // ifPigsty () {
    //   if (!this.dataForm.pigstyId) {
    //     this.$message.error('请先选择猪舍')
    //     this.dataForm.unitId = ''
    //   }
    // },
    // // 新增时，需要先选择猪舍，才能选择单元或栏期
    // ifUnit() {
    //   if (!this.form.pigstyId) {
    //     this.$message.error('请先选择猪舍')
    //     this.form.unitId = ''
    //   }
    // },
    // // 获取到了牧场 → 限制猪舍
    // getPasture (val) {
    //   this.phSelectedList = []
    //   this.pighouseList.forEach(item => {
    //     if (item.farmId === 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 = ''
    //   }
    // },
    // // 获取到猪舍
    // getPigsty (val) {
    //   //  → 反向确定牧场
    //   for (let item of this.pighouseList) {
    //     if (item.id === val) {
    //       this.form.farmId = item.farmId
    //       break
    //     }
    //   }
    //   // → 先获取猪舍，没有确定牧场的情况下，限制猪舍
    //   this.phSelectedList = []
    //   this.pighouseList.forEach(item => {
    //     if (item.farmId === this.form.farmId) {
    //       this.phSelectedList.push(item)
    //     }
    //   });
    // },
    // 新增 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]
        }
      }
      this.phSelectedList = this.pigstyList
      this.unitSelectedList = this.unitList
      // 解决猪舍、牧场已删除，但该页面仍不变问题
      // this.$http({
      //   url: this.$http.adornUrl("/management/farm/findAll"),
      //   method: "get",
      //   params: this.$http.adornParams({})
      // }).then(async ({ data }) => {
      //   if (data && data.code === 0) {
      //     this.farmList = data.all
      //     // 获取猪舍
      //     let pighouseResult = await this.$http({
      //       url: this.$http.adornUrl('/management/pigsty/findAll'),
      //       method: 'get',
      //       params: this.$http.adornParams({})
      //     })
      //     pighouseResult.data.all && (this.pighouseList = pighouseResult.data.all)
      //     this.phSelectedList = this.pighouseList
      //     console.log(this.pighouseList);
      //   }
      // })
    },
    // 选择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/period/delete'),
          method: 'post',
          data: this.$http.adornData(this.selectionDataList, false)
        }).then(result => {
          console.log(result);
          if (result.data.code === 0) {
            this.resetForm()
            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('删除栏期失败');
          }
          this.selectionDataList = []
        })
      }).catch(() => {})
    },
    formSubmit () {
      if (this.form.id) {
        /** 修改 */
        this.$refs['form'].validate((valid) => {
          if (valid) {
            // 进行修改操作
            this.$http({
              url: this.$http.adornUrl('/management/period/update'),
              method: 'post',
              data: this.$http.adornData({
                id: this.form.id,
                farmId: parseInt(this.$cookie.get('formFarmId')),
                pigstyId: this.form.pigstyId,
                unitId: this.form.unitId,
                number: this.form.number
              }, false)
            }).then(result => {
              if (result.data.code === 0) {
                this.resetForm();
                this.visible = false;
                this.$message({
                  message: '成功修改栏期信息',
                  type: 'success',
                  duration: 1000
                })
              } else {
                if (result.data.code === 600) {
                  let msg = result.data.msg.split('-')
                  this.$message({
                    message: `栏期编号 <p style="color:#333; display:inline">${msg[0]}</p> 已经存在！`,
                    type: "error",
                    duration: 1000,
                    dangerouslyUseHTMLString: true
                  })
                  return
                }
                this.$message.error(result.datanmsg);
              }
            })
          }
        })
      } else {
        /** 新增 */
        this.$refs['form'].validate((valid) => {
          if (valid) {
            // 进行新增操作
            this.$http({
              url: this.$http.adornUrl('/management/period/save'),
              method: 'post',
              data: this.$http.adornData({
                farmId:parseInt(this.$cookie.get('formFarmId')),
                unitId: this.form.unitId,
                pigstyId: this.form.pigstyId
              }, false)
            }).then(result => {
              if (result.data.code === 0) {
                // 新增pageIndex的修正
                this.totalPage++
                let pages = Math.ceil(this.totalPage / this.pageSize)
                this.pageIndex = this.pageIndex < pages? pages: this.pageIndex
                this.resetForm();
                this.visible = false;
                this.$message({
                  message: '成功添加栏期',
                  type: 'success',
                  duration: 1000
                })
              } else {
                if (result.data.code === 600) {
                  let msg = result.data.msg.split('-')
                  this.$message({
                    message: `栏期编号 <p style="color:#333; display:inline">${msg[0]}</p> 已经存在！`,
                    type: "error",
                    duration: 1000,
                    dangerouslyUseHTMLString: true
                  })
                  return
                }
                this.$message.error(result.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)
      console.log(this.form);
      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
    },
    // 校验输入是否合法，此处只校验单元序号
    validInput () {
      // 只允许中文、英文、数字、-、_的输入，取反
      const reg = /[^\a-\z\A-\Z0-9\u4E00-\u9FA5\_\-]/g
      if (reg.test(this.form.number)) {
        return false
      }
      return true
    },
    // 如不合法，则提示
    confirmInput () {
      if (this.validInput()) {
        return true
      }
      this.$confirm(`只允许输入中英文、数字、-与_`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('单元序号输入不合法')
      }).catch(() => {})
      return false
    },
    getchange (val) {
      console.log(val);
    }
  },
  watch: {
    'dataForm.pigstyId': {
      handler(newValue, oldValue) {
        if (oldValue) {
          this.dataForm.unitId = ''
        }
        this.unitSelectedList = this.unitList.filter(item => item.pigstyId === newValue)
      }
    },
    'form.pigstyId': {
      handler (newValue, oldValue) {
        if (oldValue) {
          this.form.unitId = ''
        }
        this.unitSelectedList = this.unitList.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>