<!--  -->
<template>
  <div class="cropbox">
    <div class="baselistbox_top">
      <div class="baselistbox_top_title">
        <p>地块管理</p>
      </div>
      <p class="baselistbox_top_line"></p>
      <div class="baselistbox_top_search">
        <div class="left_search">
          <div class="firstsearch">
            <el-select
              v-model="basevalue"
              size="mini"
              filterable
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in baseoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <div class="firstsearch">
            <el-input
              v-model="massif_name"
              size="mini"
              placeholder="请输入地块名称"
            ></el-input>
          </div>
          <div
            class="btnbox"
            @click="
              ((page = 1), (pagekey = Math.random() * 10 + 1)), getmassiflist()
            "
          >
            查询
          </div>
        </div>
      </div>
    </div>
    <div class="baselistbox_table">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        height="560px"
      >
        <el-table-column prop="base_name" label="基地名称"> </el-table-column>
        <el-table-column prop="massif_name" label="地块名称"> </el-table-column>
        <el-table-column prop="crop_name" label="农作物名称"> </el-table-column>
        <el-table-column prop="terrain" label="地形"> </el-table-column>
        <el-table-column prop="slope" label="坡度"> </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <span
              style="color: #4f71ff; margin-right: 15px; cursor: pointer"
              @click="opendata(scope.row.massif_id)"
              >数据列表</span
            >
            <span
              style="color: #4f71ff; margin-right: 15px; cursor: pointer"
              @click="adddata(scope.row.massif_id)"
              >录入数据</span
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next,sizes,jumper"
          :total="totalNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="page_size"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-size.sync="page"
          :key="pagekey"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog title="录入数据" :visible.sync="dialogVisible" width="500px">
      <div class="datainfobox">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="年份" prop="plant_year">
            <el-date-picker
              v-model="ruleForm.plant_year"
              size="mini"
              type="year"
              placeholder="选择年份"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="作物" prop="crop_name">
            <el-select
              v-model="ruleForm.crop_name"
              filterable
              placeholder="请选择作物"
              size="mini"
            >
              <el-option
                v-for="item in cropoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产量" prop="harvest">
            <el-input
              size="mini"
              v-model="ruleForm.harvest"
              placeholder="请输入内容"
            ></el-input>
            <span>斤</span>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="ruleForm.remarks"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="addinfof">取 消</el-button>
        <el-button type="primary" size="mini" @click="addinfot"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog title="录入数据" :visible.sync="dialogVisible2" width="1000px">
      <div class="datalistbox">
        <el-select
          v-model="ysersel"
          filterable
          placeholder="请选择年份"
          size="mini"
          clearable
          @change="yearchange"
        >
          <el-option
            v-for="item in yearlist"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-table :data="tabledatadia" style="width: 100%" class="tablebox">
          <el-table-column prop="plant_year" label="年份" width="100">
          </el-table-column>
          <el-table-column prop="crop_name" label="种植作物" width="180">
          </el-table-column>
          <el-table-column prop="harvest" label="产量" width="180">
          </el-table-column>
          <el-table-column prop="remarks" label="备注"> </el-table-column>
          <el-table-column prop="address" label="操作" width="100">
            <template slot-scope="scope">
              <span
                style="color: #4f71ff; margin-right: 15px; cursor: pointer"
                @click="deldata(scope.row.record_id)"
                >删除</span
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            layout="prev, pager, next,jumper"
            :total="totalNum"
            :page-size="10"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入产量"));
      } else {
        if (isNaN(value)) {
          callback(new Error("请输入数值"));
        } else {
          if (value < 0) {
            callback(new Error("请输入正确格式"));
          } else {
            callback();
          }
        }
      }
    };
    return {
      massif_name: "",
      totalNum: 10,
      page: 1,
      page_size: 10,
      pagekey: 1,
      tableData: [],
      loading: false,
      basevalue: "",
      baseoptions: [],
      dialogVisible: false,
      ruleForm: {
        massif_id: "", //        必传      地块id
        plant_year: "", //       必须      年份   2022
        crop_name: "", //        必须      作物   xxxxx
        harvest: "", //          必须      产量   100
        remarks: "", //         非必须     备注
      },
      rules: {
        plant_year: [
          { required: true, message: "请选择年份", trigger: "change" },
        ],
        crop_name: [
          { required: true, message: "请选择作物", trigger: "change" },
        ],
        harvest: [{ required: true, validator: validatePass, trigger: "blur" }],
      },
      cropoptions: [],
      dialogVisible2: false,
      yearlist: [],
      ysersel: "",
      tablepage: 1,
      tabledatadia: [],
      massif_id: "",
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    handleSizeChange(e) {
      this.page = 1;
      this.pagekey = Math.random() * 10 + 1;
      this.page_size = e;
      this.getmassiflist();
    },
    handleCurrentChange(e) {
      this.page = e;
      this.getmassiflist();
    },
    getbaselist() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=basemanager.baseinfo.list_land_base",
        data: this.qs.stringify({
          page: 1, //            非必须     页码，默认1
          page_size: 999999, //       非必须     每页条目数，默认10
        }),
      }).then((res) => {
        if (res.data.data) {
          console.log(res.data.data);
          var data = res.data.data.data;
          for (var i = 0; i < data.length; i++) {
            var obj = {
              value: data[i].base_id,
              label: data[i].base_name,
            };
            this.baseoptions.push(obj);
          }
        }
      });
    },
    getmassiflist() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=basemanager.baseinfo.get_massif_list",
        data: this.qs.stringify({
          base_id: this.basevalue,
          massif_name: this.massif_name, //       非必须     农作物名称
          page: this.page, //            非必须     页码，默认1
          page_size: this.page_size, //       非必须     每页条目数，默认10
        }),
      }).then((res) => {
        if (res.data.data) {
          console.log(res.data.data);
          this.tableData = res.data.data.data;
          this.totalNum = res.data.data.total_num;
        }
      });
    },
    getcroplist() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=basemanager.baseinfo.massif_by_crop_list",
        data: this.qs.stringify({}),
      }).then((res) => {
        if (res.data.data) {
          console.log(res.data.data);
          var data = res.data.data;
          for (var i = 0; i < data.length; i++) {
            var obj = {
              value: data[i].crop_name,
              label: data[i].crop_name,
            };
            this.cropoptions.push(obj);
          }
        }
      });
    },
    addinfof() {
      this.dialogVisible = false;
      this.ruleForm = {
        massif_id: "", //        必传      地块id
        plant_year: "", //       必须      年份   2022
        crop_name: "", //        必须      作物   xxxxx
        harvest: "", //          必须      产量   100
        remarks: "", //         非必须     备注
      };
    },
    addinfot() {
      // this.dialogVisible = true;
      var year = new Date(this.ruleForm.plant_year).getFullYear();
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$axios({
            method: "post",
            url: "api/api_gateway?method=basemanager.baseinfo.add_plant_record",
            data: this.qs.stringify({
              massif_id: this.ruleForm.massif_id, //           必传    地块名称
              plant_year: year,
              crop_name: this.ruleForm.crop_name, //               必传    地形
              harvest: this.ruleForm.harvest, //                 必传    坡度
              remarks: this.ruleForm.remarks, //               必传    农作物id
            }),
          }).then((res) => {
            if (res.data.data) {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.success("添加成功");
              }
              this.dialogVisible = false;
              this.ruleForm = {
                massif_id: "", //        必传      地块id
                plant_year: "", //       必须      年份   2022
                crop_name: "", //        必须      作物   xxxxx
                harvest: "", //          必须      产量   100
                remarks: "", //         非必须     备注
              };
            } else {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.error(res.data.message);
              }
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    opendata(id) {
      this.dialogVisible2 = true;
      this.getyearlist(id);
      this.gettabledata(id);
      this.massif_id = id;
    },
    adddata(id) {
      this.dialogVisible = true;
      this.ruleForm.massif_id = id;
    },
    getyearlist(massif_id) {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=basemanager.baseinfo.get_plant_year_list",
        data: this.qs.stringify({
          massif_id: massif_id,
        }),
      }).then((res) => {
        if (res.data.data) {
          console.log(res.data.data);
          var data = res.data.data;
          this.yearlist = [];
          for (var i = 0; i < data.length; i++) {
            var obj = {
              value: data[i],
              label: data[i],
            };
            this.yearlist.push(obj);
          }
        }
      });
    },
    handleCurrentChange(e) {
      this.tablepage = e;
      this.gettabledata(this.massif_id);
    },
    yearchange(e) {
      this.tablepage = 1;
      this.ysersel = e;
      this.gettabledata(this.massif_id);
    },
    gettabledata(massif_id) {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=basemanager.baseinfo.get_plant_record",
        data: this.qs.stringify({
          massif_id: massif_id,
          plant_year: this.ysersel, //       非必须    年份
          page: this.tablepage, //            非必须     页码，默认1
          page_size: 10, //       非必须     每页条目数，默认10
        }),
      }).then((res) => {
        if (res.data.data) {
          // console.log(res.data.data.data);
          this.total_num = res.data.data.total_num;
          this.tabledatadia = res.data.data.data;
        }
      });
    },
    deldata(id) {
      this.$confirm("此操作将删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=basemanager.baseinfo.del_plant_record",
            data: this.qs.stringify({
              record_id: id,
            }),
          }).then((res) => {
            if (res.data.data) {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.success("删除成功");
              }
              this.gettabledata(this.massif_id);
            } else {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.error(res.data.message);
              }
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getmassiflist();
    this.getbaselist();
    this.getcroplist();
  },
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.cropbox {
  width: 100%;
  height: 100%;
  .baselistbox_top {
    width: 100%;
    height: 130px;
    background-color: #fff;
    border-radius: 10px;
    .baselistbox_top_title {
      width: 100%;
      height: 65px;
      display: flex;
      padding: 20px;
      box-sizing: border-box;
      line-height: 25px;
      justify-content: space-between;
      p:first-child {
        font-size: 18px;
        font-weight: 700;
      }
    }
    .baselistbox_top_line {
      width: 100%;
      height: 1px;
      background-color: #f2f2f2;
    }
    .baselistbox_top_search {
      width: 100%;
      height: 68px;
      display: flex;
      padding: 20px;
      box-sizing: border-box;
      line-height: 28px;
      justify-content: flex-end;
      .left_search {
        display: flex;
        .firstsearch {
          margin-right: 15px;
        }
      }
      .btnbox,
      .btnbox2 {
        width: 68px;
        height: 26px;
        border: 1px solid #4f71ff;
        text-align: center;
        border-radius: 3px;
        font-size: 14px;
        line-height: 26px;
        cursor: pointer;
      }
      .btnbox {
        background-color: #4f71ff;
        color: #fff;
      }
      .btnbox2 {
        color: #4f71ff;
      }
    }
  }
  .baselistbox_table {
    width: 100%;
    // height: calc(100% - 140px);
    background-color: #fff;
    margin-top: 10px;
    padding: 20px;
    box-sizing: border-box;
    position: relative;
    border-radius: 10px;
    /deep/.el-table__header {
      th {
        background-color: #f1f1f3;
      }
    }
    .pagination {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
      /deep/.el-pager {
        .active {
          background-color: #4f71ff !important;
        }
      }
      /deep/.el-input__inner:hover {
        border-color: #4f71ff;
      }
    }
  }
}
.datainfobox {
  /deep/.el-date-editor {
    width: 200px;
  }
  /deep/.el-select {
    width: 200px;
  }
  /deep/.el-input {
    width: 200px;
  }
  /deep/.el-textarea {
    .el-textarea__inner {
      font-family: "Avenir", Helvetica, Arial, sans-serif;
    }
  }
}
.datalistbox {
  .tablebox {
    margin: 15px 0;
  }
  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    /deep/.el-pager {
      .active {
        background-color: #4f71ff !important;
      }
    }
    /deep/.el-input__inner:hover {
      border-color: #4f71ff;
    }
  }
}
</style>