<template>
  <div class="bpighouse">
    <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
      height="670"
      :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="number"
        header-align="center"
        align="center"
        label="猪舍编号">
      </el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="所属牧场">
      </el-table-column>
      <el-table-column
        prop="feeder"
        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="success"
            size="mini"
            @click="addOrUpdateHandle(scope.row)">
            修改
          </el-button>
          <el-button
            v-if="isAuth('sys:user:delete')"
            type="danger"
            size="mini"
            @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, 12, 15, 20]"
        :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
        :rules="dataRule"
        :model="form"
        ref="form"
        @keyup.enter.native="formSubmit()"
        label-width="80px">
        <el-form-item label="所属牧场" prop="pastureId">
          <el-select v-model="form.pastureId" placeholder="请选择所属牧场" style="width: 100%">
            <el-option
              v-for="item in pastureList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <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 @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: "",
        number: "",
        pastureId: "",
        feederId: "",
      },
      pastureList: [], // 牧场list
      employeeList: [], // 养殖员list
      // TODO: 猪舍编号长度
      dataRule: {
        pastureId: [
          { required: true, message: '所属牧场不能为空', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '猪舍编号不能为空', trigger: ['blur', 'change'] }
        ],
        feederId: [
          { required: true, message: '养殖员不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getDataList();
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/management/pigsty/list"),
        method: "post",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          keywords: this.dataForm.key
        })
      }).then(async ({ data }) => {
        let pastureResult = await this.$http({
          url: this.$http.adornUrl("/management/pasture/findAll"),
          method: "post"
        });
        pastureResult.data.all && (this.pastureList = pastureResult.data.all)
        let employeeResult = await this.$http({
          url: this.$http.adornUrl("/management/employee/findAll"),
          method: "post"
        });
        employeeResult.data.all && (this.employeeList = employeeResult.data.all)
        console.log(this.employeeList);
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
          this.dataList.forEach((item) => {
            for (let pasture of this.pastureList) {
              if (item.pastureId === pasture.id) {
                item["name"] = pasture.name;
                break;
              }
            }
            for (let feeder of this.employeeList) {
              if (parseInt(item.feederId) === feeder.id) {
                item.feederId = parseInt(item.feederId)
                item["feeder"] = feeder.name
                break
              }
            }
          })
        } 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 key of Object.keys(this.form)) {
          this.form[key] = row[key]
        }
      }
    },
    // 选择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/pigsty/delete"),
          method: "post",
          data: this.$http.adornData(this.selectionDataList, 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/pigsty/update"),
          method: "post",
          data: this.$http.adornData({
            id: this.form.id,
            number: this.form.number,
            pastureId: this.form.pastureId,
            feederId: this.form.feederId,
          }),
        }).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('-')
              let pasture = ''
              for (let item of this.pastureList) {
                if (this.form.pastureId === item.id) {
                  pasture = item.name
                  break
                }
              }
              this.$message({
                message: `${pasture}中猪舍编号 <p style="color:#333; display:inline">${msg[0]}</p> 已经存在！`,
                type: "error",
                duration: 1000,
                dangerouslyUseHTMLString: true
              })
              return
            }
            this.$message.error("修改猪舍信息失败");
          }
        })
      } else {
        /** 新增 */
        // 输入是否完整
        if (!this.confirmComplete(1)) {
          return
        }
        // 输入是否合法
        if (!this.confirmInput()) {
          return
        }
        // 进行新增操作
        this.$http({
          url: this.$http.adornUrl("/management/pigsty/save"),
          method: "post",
          data: this.$http.adornData({
            number: this.form.number,
            pastureId: this.form.pastureId,
            feederId: this.form.feederId,
          }),
        }).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 pasture = ''
              for (let item of this.pastureList) {
                if (this.form.pastureId === item.id) {
                  pasture = item.name
                  break
                }
              }
              this.$message({
                message: `${pasture}中猪舍编号 <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);
    }
    // TODO: 猪舍编号的长度校验
  }
}
</script>
<style scoped>
</style>