<template>
  <div class="branch">
    <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
        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
        prop="jobStauts"
        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="小猪耳标">
          <!-- <div class="block">
            <el-cascader
              v-model="form.pigletEartag"
              :options="options"
              :props="{ expandTrigger: 'hover' }"
              @change="handleChange"></el-cascader>
          </div> -->
          <el-cascader :options="options" :show-all-levels="false" v-model="form.pigletEartag" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="母亲耳标">
          <!-- <div class="block">
            <el-cascader
              v-model="form.sowEartag"
              :options="options"
              :props="{ expandTrigger: 'hover' }"
              @change="handleChange"></el-cascader>
          </div> -->
          <el-cascader :options="options" :show-all-levels="false" v-model="form.sowEartag" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="父亲耳标">
          <!-- <div class="block">
            <el-cascader
              v-model="form.boarEartag"
              :options="options"
              :props="{ expandTrigger: 'hover' }"
              @change="handleChange"></el-cascader>
          </div> -->
          <el-cascader :options="options" :show-all-levels="false" v-model="form.boarEartag" clearable></el-cascader>
        </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: [
        {
          buildTime: '',
          id: '',
          location: '',
          manager: '',
          name: '',
        }
      ],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      selectionDataList: [],
      visible: false,
      form: {
        id: '',
        pigletEartag: [],
        sowEartag: [],
        boarEartag: []
      },
      options: [],
      pigs: []
    }
  },
  created () {
    this.getDataList()
  },
  mounted () {
    this.getCascader()
  },
  methods: {
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/management/yearpigpedigree/list'),
        method: 'post'
      }).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
      })
    },
    // 每页数
    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 item of this.pigs) {
          if (item.value === row.pigletEartag) {
            this.form.pigletEartag = item.cascader
            break
          }
        }
        // 获取母亲耳标
        for (let item of this.pigs) {
          if (item.value === row.sowEartag) {
            this.form.sowEartag = item.cascader
            break
          }
        }
        // 获取父亲耳标
        for (let item of this.pigs) {
          if (item.value === row.boarEartag) {
            this.form.boarEartag = item.cascader
            break
          }
        }
      }
    },
    // 获取级联选择器
    getCascader () {
      // 获取所有年猪信息
      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'
        })
        let pastures = []
        pastureResult.data.page.list.forEach(pasture => {
          let item = {
            label: pasture.name,
            value: pasture.id,
            children: []
          }
          pastures.push(item)
        });
        // 获取所有猪舍信息
        let pigstyResult = await this.$http({
          url: this.$http.adornUrl('/management/pigsty/list'),
          method: 'post'
        })
        let pigstys = []
        pigstyResult.data.page.list.forEach(pigsty => {
          let item = {
            label: pigsty.number,
            value: pigsty.id,
            pastureId: pigsty.pastureId,
            children: []
          }
          pigstys.push(item)
        });
        // 获取所有单元信息
        let unitResult = await this.$http({
          url: this.$http.adornUrl('/management/unit/list'),
          method: 'post'
        })
        let units = []
        unitResult.data.page.list.forEach(unit => {
          let item = {
            label: unit.number,
            value: unit.id,
            pigstyId: unit.pigstyId,
            pastureId: unit.pastureId,
            children: []
          }
          units.push(item)
        });
        if (data && data.code === 0) {
          let pigs = data.page.list
          // 将所有猪放进单元中
          pigs.forEach(pig => {
            for (let item of units) {
              if (pig.unitId === item.value) {
                let p = {
                  label: pig.eartag,
                  value: pig.eartag,
                  cascader: [item.pastureId, item.pigstyId, item.value, pig.eartag]
                }
                item.children.push(p)
                this.pigs.push(p)
                break
              }
            }
          });
          // 将所有单元放进猪舍里面
          units.forEach(unit => {
            for (let item of pigstys) {
              if (unit.pigstyId === item.value) {
                item.children.push(unit)
                break
              }
            }
          });
          // 将所有猪舍放进牧场里
          pigstys.forEach(pigsty => {
            for (let item of pastures) {
              if (pigsty.pastureId === item.value) {
                item.children.push(pigsty)
                break
              }
            }
          });
        }
        this.options = pastures
      })
    },
    // 选择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/yearpigpedigree/delete'),
          method: 'post',
          data: this.$http.adornData(this.selectionDataList, false)
        }).then(result => {
          if (result.data.code === 0) {
            this.$message({
              message: '成功删除小猪谱系信息',
              type: 'success',
              duration: 1000
            })
          } else {
            this.$message.error('删除小猪谱系信息失败');
          }
          this.resetForm()
          this.selectionDataList = []
        })
      }).catch(() => {})
    },
    formSubmit () {
      if (this.form.pigletEartag[3] === this.form.sowEartag[3] || this.form.pigletEartag[3] === this.form.boarEartag[3] || this.form.sowEartag[3] === this.form.boarEartag[3]) {
        // 请勿选择相同猪
        this.$confirm(`请勿选择相同猪`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            return
          }).catch(() => {})
          return
      }
      // 正常操作
      if (this.form.id) {
        // 修改
        if (this.confirmInput()) {
          // 进行修改操作
          this.$http({
            url: this.$http.adornUrl('/management/yearpigpedigree/update'),
            method: 'post',
            data: this.$http.adornData({
              id: this.form.id,
              pigletEartag: this.form.pigletEartag[3],
              sowEartag: this.form.sowEartag[3],
              boarEartag: this.form.boarEartag[3]
            })
          }).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)) {
          // 进行新增操作
          this.$http({
            url: this.$http.adornUrl('/management/yearpigpedigree/save'),
            method: 'post',
            data: this.$http.adornData({
              pigletEartag: this.form.pigletEartag[3],
              sowEartag: this.form.sowEartag[3],
              boarEartag: this.form.boarEartag[3]
            })
          }).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(() => {})
        }
      }
    },
    // 判断新增/修改时是否输入完整
    confirmInput (val) {
      console.log('判断是否输入完整');
      console.log(val);
      val && (delete this.form.id, delete this.form.deleted, delete this.form.gmtCreate, delete this.form.gmtModified)
      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.form.id = ''
      this.getDataList()
    },
    // 取消
    cancel () {
      this.visible = false
      this.resetForm()
    }
  }
}
</script>
<style scoped>
</style>