<template>
  <div class="bpighouse">
    <div class="rect rect-form">
      <el-form size="mini" :inline="true" :model="dataForm">
        <el-form-item style="width: 200px">
          <el-input v-model="dataForm.keyword" placeholder="品种" style="width: 200px" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button 
            icon="el-icon-search"
            @click="getDataList()">
            查 询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <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="620"
        :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="name"
          header-align="center"
          align="center"
          label="品种">
        </el-table-column>
        <!-- <el-table-column
          prop="origin"
          header-align="center"
          align="center"
          label="产地">
        </el-table-column> -->
        <el-table-column
          prop="remark"
          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"
          size="mini"
          ref="form"
          @keyup.enter.native="formSubmit()"
          label-width="80px"
          style="margin-left: 20px;width: 500px">
          <el-form-item label="品种" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="产地" prop="origin">
            <el-input v-model="form.origin"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark"></el-input>
          </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>
  </div>
</template>
<script>
export default {
  data() {
    return {
      dataForm: {
        keyword: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      selectionDataList: [],
      visible: false,
      form: {
        id: "",
        name: "",
        origin: "",
        remark: ''
      },
      // TODO: 猪舍编号长度
      dataRule: {
        name: [
          { required: true, message: '品种不能为空', trigger: 'blur' }
        ],
        origin: [
          { required: true, message: '产地不能为空', trigger: ['blur'] }
        ]
      }
    }
  },
  mounted() {
    this.getDataList();
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/management/basebloodline/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          keyword: this.dataForm.keyword || undefined
        })
      }).then( ({ data }) => {
        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 = ''
    },
    // 每页数
    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);
    },
    // 选择n个牧场
    selectionChangeHandle(val) {
      this.selectionDataList = val
      // val.forEach((item) => {
      //   this.selectionDataList.push(item.id);
      // });
    },
    // 删除n个牧场
    deleteHandle(breed) {
      let ids = breed? [breed.id]: this.selectionDataList.map(item => item.id)
      let names = breed? [breed.name]: this.selectionDataList.map(item => item.name)
      this.$confirm(`确定${breed ? '删除' : '批量删除'}品种${names.join()}？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        // 删除操作
        if (this.selectionDataList.length < 0) {
          return;
        }
        this.$http({
          url: this.$http.adornUrl("/management/basebloodline/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() {
      if (this.form.id) {
        /** 修改 */
        // 输入是否完整
        // if (!this.confirmComplete()) {
        //   return
        // }
        // 输入是否合法
        // if (!this.confirmInput()) {
        //   return
        // }
          // 进行修改操作
        this.$http({
          url: this.$http.adornUrl("/management/basebloodline/update"),
          method: "post",
          data: this.$http.adornData({
            id: this.form.id,
            name: this.form.name,
            origin: this.form.origin,
            remark: this.form.remark,
          }),
        }).then((result) => {
          if (result.data.code === 0) {
            this.resetForm();
            this.visible = false;
            this.$message({
              message: "成功修改猪舍信息",
              type: "success",
              duration: 1000,
            })
          } else {
            this.$message.error("修改猪舍信息失败");
          }
        })
      } else {
        /** 新增 */
        // 输入是否完整
        // if (!this.confirmComplete(1)) {
        //   return
        // }
        // 输入是否合法
        // if (!this.confirmInput()) {
        //   return
        // }
        // 进行新增操作
        this.$http({
          url: this.$http.adornUrl("/management/basebloodline/save"),
          method: "post",
          data: this.$http.adornData({
            name: this.form.name,
            origin: this.form.origin,
            remark: this.form.remark,
          }),
        }).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('-')
              let farm = ''
              for (let item of this.farmList) {
                if (this.form.farmId === item.id) {
                  farm = item.name
                  break
                }
              }
              this.$message({
                message: `${farm}中猪舍编号 <p style="color:#333; display:inline">${msg[0]}</p> 已经存在！`,
                type: "error",
                duration: 1000,
                dangerouslyUseHTMLString: true
              })
              return
            }
            this.$message.error("添加猪舍失败");
          }
        })
      }
    },
    // 清空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
    },
    // 校验输入是否合法，此处只校验猪舍编号
    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);
    },
    // 变色
    tableRowClassName({row, rowIndex}) {
      console.log(row);
      if (rowIndex%2 === 0) {
        return 'warning-row';
      }
      return '';
    }
    // TODO: 猪舍编号的长度校验
  }
}
</script>
<style scoped>
.rect {
  background-color: #fff;
  padding: 30px 15px;
  border-radius: 5px;
  border: 1px solid #e8e8e8;
  margin-left: 20px;
}
.rect-form {
  padding-bottom: 10px;
}
.rect-table {
  margin-top: 10px;
}
.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>