<template>
  <div class="branch">
    <el-container>
      <el-header>
        <div class="rect rect-form">
          <el-form
            :inline="true"
            :model="dataForm"
            @keyup.enter.native="getDataList()"
            size="mini">
            <el-form-item style="width: 500px">
              <el-input
                v-model="dataForm.key"
                placeholder="请输入姓名"
                clearable style="width: 500px"></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="name"
              header-align="center"
              align="center"
              label="养殖员姓名">
            </el-table-column>
            <el-table-column
              prop="position"
              header-align="center"
              align="center"
              label="职位">
            </el-table-column>
            <el-table-column
              prop="approachTime"
              header-align="center"
              align="center"
              label="入场时间">
            </el-table-column>
            <el-table-column
              prop="departureTime"
              header-align="center"
              align="center"
              label="离场时间">
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="当前在职">
              <template slot-scope="scope">
                {{scope.row.jobStatus? '是': '否'}}
              </template>
            </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">
            <el-form :model="form" ref="form" @keyup.enter.native="formSubmit()" label-width="80px" size="mini">
              <el-form-item label="姓名">
              <el-input v-model="form.name" placeholder="养殖员姓名"></el-input>
              </el-form-item>
              <el-form-item label="职位">
                <el-input v-model="form.position" placeholder="职位"></el-input>
              </el-form-item>
              <el-form-item label="当前在职">
                <el-select v-model="form.jobStatus" placeholder="请选择当前是否在岗">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="入场时间">
                <el-date-picker
                  v-model="form.approachTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="离场时间">
                <el-date-picker
                  v-model="form.departureTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期时间">
                </el-date-picker>
              </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>
      </el-main>
    </el-container>
  </div>
</template>
<script>
export default {
  data () {
    return {
      dataForm: {
        key: ''
      },
      dataList: [
        {
          buildTime: '',
          id: '',
          location: '',
          manager: '',
          name: '',
        }
      ],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      selectionDataList: [],
      visible: false,
      form: {
        id: '',
        name: '',
        position: '',
        approachTime: '',
        departureTime: '',
        jobStatus: ''
      },
      options: [
        {
          value: true,
          label: '是'
        },
        {
          value: false,
          label: '否'
        }
      ],
      pigs: []
    }
  },
  // created () {
  //   this.getDataList()
  // },
  activated () {
    this.getDataList()
  },
  methods: {
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/management/employee/list'),
        method: 'post',
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          keyword: this.dataForm.key
        })
      }).then(({ data }) => {
        console.log(data);
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
          this.$confirm(`查询养殖员信息失败`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            return
          }).catch(() => {})
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    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) {
        for (let key of Object.keys(this.form)) {
          this.form[key] = row[key]
        }
        this.form.id = row.id
      }
    },
    // 选择n个养殖员
    selectionChangeHandle (val) {
      this.selectionDataList = val
      // val.forEach(item => {
      //   this.selectionDataList.push(item.id)
      // });
    },
    // 删除n个养殖员
    deleteHandle (feeder) {
      console.log(this.selectionDataList);
      let ids = feeder? [feeder.id]: this.selectionDataList.map(item => item.id)
      let names = feeder? [feeder.name]: this.selectionDataList.map(item => item.name)
      this.$confirm(`确定${feeder ? '删除' : '批量删除'}名为${names.join()}的养殖员？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除操作
        if (this.selectionDataList.length < 0) {
          return
        }
        this.$http({
          url: this.$http.adornUrl('/management/employee/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(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('删除养殖员信息失败');
          }
          this.resetForm()
          this.selectionDataList = []
        })
      }).catch(() => {})
    },
    formSubmit () {
      if (this.form.id) {
        // 修改
        if (!this.confirmComplete()) {
          return
        }
        // 检查入场时间、离开场时间
        if (!this.confirmJobStatus()) {
          return
        }
        // 进行修改操作
        this.$http({
          url: this.$http.adornUrl('/management/employee/update'),
          method: 'post',
          data: this.$http.adornData({
            id: this.form.id,
            name: this.form.name,
            position: this.form.position,
            approachTime: this.form.approachTime,
            departureTime: this.form.departureTime,
            jobStatus: this.form.jobStatus,
            farmId: parseInt(this.$cookie.get('formFarmId'))
          })
        }).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.confirmJobStatus()) {
          return
        }
        // 进行新增操作
        this.$http({
          url: this.$http.adornUrl('/management/employee/save'),
          method: 'post',
          data: this.$http.adornData({
            name: this.form.name,
            position: this.form.position,
            approachTime: this.form.approachTime,
            departureTime: this.form.departureTime,
            jobStatus: this.form.jobStatus,
            farmId: parseInt(this.$cookie.get('formFarmId'))
          })
        }).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 {
            this.$message.error('添加养殖员信息失败');
          }
        })
      }
    },
    // 判断新增/修改时是否输入完整
    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
    },
    // 清空form
    resetForm () {
      for (let i in this.form) {
        this.form[i] = ''
      }
      this.getDataList()
    },
    // 取消
    cancel () {
      this.visible = false
      this.resetForm()
    },
    // 判断当前在岗是否正确
    getJobStatus () {
      let start = new Date(this.form.approachTime)
      let end = new Date(this.form.departureTime)
      if (start <= end) {
        return true
      }
      return false
    },
    // 判断当前在岗与入场时间、离场时间是否有冲突
    confirmJobStatus () {
      if (this.getJobStatus()) {
        return true
      }
      this.$confirm(`请检查入场时间与离场时间`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // return false
        console.log('新增养殖员有误');
      }).catch(() => {})
      return false
    },
    // 变色
    tableRowClassName({row, rowIndex}) {
      console.log(row);
      if (rowIndex%2 === 0) {
        return 'warning-row';
      }
      return '';
    }
  }
}
</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>