<!-- 新增农作物 -->
<template>
  <div class="cropaddbox">
    <div class="baselistbox_top">
      <div class="baselistbox_top_title">
        <p @click="goBackPage()" style="cursor: pointer">
          <i class="el-icon-back"></i>
          <span>返回</span>
        </p>
        <p>{{ title }}</p>
      </div>
      <p class="baselistbox_top_line"></p>
      <div class="baselistbox_top_search">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <div class="demo-ruleForm-left">
            <el-form-item label="农作物名称" prop="cropname">
              <el-input
                v-model="ruleForm.cropname"
                :maxlength="10"
                size="mini"
              ></el-input>
            </el-form-item>
            <el-form-item label="作物品种" prop="cropvariety">
              <el-input
                v-model="ruleForm.cropvariety"
                :maxlength="10"
                size="mini"
              ></el-input>
            </el-form-item>
            <el-form-item label="显示颜色" prop="cropcolor">
              <el-color-picker
                v-model="ruleForm.cropcolor"
                size="small"
              ></el-color-picker>
            </el-form-item>
          </div>
          <div class="demo-ruleForm-right">
            <el-form-item label="农作物图片" prop="cropimage">
              <el-upload
                class="avatar-uploader"
                :action="$http + '/api/util/upload/img/'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :on-error="handleAvatarError"
              >
                <img
                  v-if="ruleForm.cropimage"
                  :src="ruleForm.cropimage"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <div class="baselistbox_table">
      <div class="btnbox2" @click="adddata">
        <i class="el-icon-plus"></i>
        <span>新增</span>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="cycle_name" label="生长周期名称" width="180">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.cycle_name"
              :autofocus="true"
              size="mini"
              placeholder="请输入内容"
              :maxlength="6"
              @blur="scope.row.nameinput = false"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="cycle_date" label="时间" width="240">
          <template slot-scope="scope">
            <div class="monthbox">
              <el-select
                v-model="scope.row.cycle_date[0]"
                size="mini"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in monthoptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <i class="el-icon-date"></i>
              <el-select
                v-model="scope.row.cycle_date[1]"
                size="mini"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in monthoptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="期间可能发生虫害" width="380px">
          <template slot-scope="scope">
            <div class="tagbox">
              <div style="width: 92%">
                <el-tag
                  :key="index"
                  v-for="(tag, index) in scope.row.pest_pest"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag, scope.row.pest_pest)"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <p class="selp" @click="sellist(scope.row.pest_pest)">选择</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="期间可能发生病害" width="380px">
          <template slot-scope="scope">
            <div class="tagbox">
              <div style="width: 92%">
                <el-tag
                  :key="index"
                  v-for="(tag, index) in scope.row.pest_disease"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag, scope.row.pest_disease)"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <p class="selp" @click="sellistdis(scope.row.pest_disease)">
                选择
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="备注" width="350px">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.content"
              :autofocus="true"
              size="mini"
              placeholder="请输入内容"
              :maxlength="20"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <i
              class="el-icon-remove-outline"
              @click="deldata(scope.row)"
              style="color: red;cursor: pointer;"
            ></i>
          </template>
        </el-table-column>
      </el-table>
      <div class="operationbox">
        <el-button size="mini" @click="reset">重 置</el-button>
        <el-button size="mini" type="primary" @click="addbtn">确 定</el-button>
      </div>
    </div>
    <el-dialog
      title="选择病虫害"
      :visible.sync="dialogVisible"
      width="580px"
      top="3%"
      :close-on-click-modal="false"
    >
      <div class="wormbox">
        <div class="top_search">
          <div class="firstsearch">
            <el-input
              v-model="wormname"
              size="mini"
              placeholder="请输入病虫害名称"
            ></el-input>
          </div>
          <div class="btnbox" @click="inquire">查询</div>
        </div>
        <div class="bot_table" v-loading="loading">
          <el-table
            ref="multipleTable"
            :data="wormtable"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50px"> </el-table-column>
            <el-table-column label="图片" width="150px">
              <template slot-scope="scope">
                <img
                  v-lazy="scope.row.img_urls"
                  alt=""
                  style="width: 25px; height: 25px"
                />
              </template>
            </el-table-column>
            <el-table-column label="名称">
              <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination
            background
            layout="prev, pager, next,jumper"
            :total="total"
            :page-size="8"
            @current-change="handleCurrentChange"
            v-if="pageloading"
          >
          </el-pagination>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="confirmdata" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { jsonp } from "vue-jsonp";
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择农作物图片"));
      } else {
        callback();
      }
    };
    return {
      id: "",
      title: "",
      ruleForm: {
        cropname: "",
        cropvariety: "",
        cropcolor: "#4f71ff",
        cropimage: "",
        cropimage2: "",
      },
      rules: {
        cropname: {
          required: true,
          message: "请输入农作物名称",
          trigger: "blur",
        },
        cropvariety: {
          required: true,
          message: "请输入物作品种",
          trigger: "blur",
        },
        cropcolor: {
          required: true,
          message: "请输选择显示颜色",
          trigger: "blur",
        },
        cropimage: {
          required: true,
          validator: validatePass,
          trigger: "blur",
        },
      },
      tableData: [],
      monthoptions: [
        {
          value: 1,
          label: "一月",
        },
        {
          value: 2,
          label: "二月",
        },
        {
          value: 3,
          label: "三月",
        },
        {
          value: 4,
          label: "四月",
        },
        {
          value: 5,
          label: "五月",
        },
        {
          value: 6,
          label: "六月",
        },
        {
          value: 7,
          label: "七月",
        },
        {
          value: 8,
          label: "八月",
        },
        {
          value: 9,
          label: "九月",
        },
        {
          value: 10,
          label: "十月",
        },
        {
          value: 11,
          label: "十一月",
        },
        {
          value: 12,
          label: "十二月",
        },
      ],
      dialogVisible: false,
      loading: false,
      wormcode: "2",
      wormname: "",
      wormtable: [],
      multipleSelection: [],
      page: 1,
      total: 8,
      sellistcontainer: {},
      pageloading: false,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //返回上一页
    goBackPage() {
      this.$router.go(-1);
    },
    handleAvatarSuccess(res, file) {
      this.ruleForm.cropimage2 = this.$http + res.img_url;
      this.ruleForm.cropimage = URL.createObjectURL(file.raw);
    },
    handleAvatarError(res) {
      console.log(res);
    },
    beforeAvatarUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    handleClose(tag, data) {
      // this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      // console.log(data)
      data.splice(data.indexOf(tag), 1);
    },
    adddata() {
      var obj = {
        cycle_name: "播种期",
        cycle_date: [1, 2],
        pest_pest: [],
        pest_disease: [],
        nameinput: false,
        content: "",
      };
      this.tableData.push(obj);
    },
    deldata(data) {
      this.tableData.splice(this.tableData.indexOf(data), 1);
    },
    sellist(data) {
      this.wormname = "";
      this.page = 1;
      this.sellistcontainer = data;
      this.dialogVisible = true;
      this.wormcode = "2";
      this.getwormlist();
      this.pageloading = false;
    },
    sellistdis(data) {
      this.wormname = "";
      this.page = 1;
      this.sellistcontainer = data;
      this.dialogVisible = true;
      this.wormcode = "1";
      this.getwormlist();
      this.pageloading = false;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    inquire() {
      this.pageloading = false;
      this.page = 1;
      this.getwormlist();
    },
    getwormlist() {
      this.loading = true;
      this.$axios({
        method: "post",
        url: "api/api_gateway?method=pest.pests.pests_info",
        data: this.qs.stringify({
          code: this.wormcode,
          page: this.page,
          page_size: 8,
          pest_name: this.wormname,
        }),
      }).then((res) => {
        this.pageloading = true;
        this.loading = false;
        if (res.data.data) {
          this.wormtable = res.data.data.data;
          this.total = res.data.data.nums;
          // this.$nextTick(() => {
          //   document.getElementsByClassName("number")[0].innerText = "首页";
          //   var length = document.getElementsByClassName("number").length;
          //   document.getElementsByClassName("number")[length - 1].innerText =
          //     "末页";
          // });
        }
      });
    },
    handleCurrentChange(e) {
      this.page = e;
      this.getwormlist();
    },
    confirmdata() {
      this.dialogVisible = false;
      console.log(this.sellistcontainer);
      for (var i = 0; i < this.multipleSelection.length; i++) {
        if (this.sellistcontainer.length) {
          for (var j = 0; j < this.sellistcontainer.length; j++) {
            if (
              this.sellistcontainer.indexOf(this.multipleSelection[i].name) ==
              -1
            ) {
              this.sellistcontainer.push(this.multipleSelection[i].name);
            }
          }
        } else {
          this.sellistcontainer.push(this.multipleSelection[i].name);
        }
      }
      console.log(this.sellistcontainer);
    },
    reset() {
      this.ruleForm.cropname = "";
      this.ruleForm.cropvariety = "";
      this.ruleForm.cropimage = "";
      this.ruleForm.cropcolor = "";
      this.ruleForm.cropimage2 = "";
      this.tableData = [];
    },
    addbtn() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.title == "新增农作物") {
            this.$axios({
              method: "post",
              url: "api/api_gateway?method=information.crop.add_crop_info",
              data: this.qs.stringify({
                crop_name: this.ruleForm.cropname, //       必须     农作物名称
                crop_variety: this.ruleForm.cropvariety, //    必须     作为品种
                crop_colors: this.ruleForm.cropcolor, //     必须     显示颜色
                crop_image: this.ruleForm.cropimage2, //      必须     作物图片
                cycle_list: JSON.stringify(this.tableData), //     非必须    周期数组，必须是数组格式
              }),
            }).then((res) => {
              if (res.data.data) {
                this.$message.success("添加成功");
                this.goBackPage();
              } else {
                this.$message.error(res.data.message);
              }
            });
          } else if (this.title == "修改农作物") {
            this.$axios({
              method: "post",
              url: "api/api_gateway?method=information.crop.modify_crop_info",
              data: this.qs.stringify({
                crop_id: this.id,
                crop_name: this.ruleForm.cropname, //       必须     农作物名称
                crop_variety: this.ruleForm.cropvariety, //    必须     作为品种
                crop_colors: this.ruleForm.cropcolor, //     必须     显示颜色
                crop_image: this.ruleForm.cropimage2, //      必须     作物图片
                cycle_list: JSON.stringify(this.tableData), //     非必须    周期数组，必须是数组格式
              }),
            }).then((res) => {
              if (res.data.data) {
                this.$message.success("修改成功");
                this.goBackPage();
              } else {
                this.$message.error(res.data.message);
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getcropinfo(id) {
      // information.crop.get_crop_info
      this.$axios({
        method: "post",
        url: "api/api_gateway?method=information.crop.get_crop_info",
        data: this.qs.stringify({
          crop_id: id,
        }),
      }).then((res) => {
        if (res.data.data) {
          console.log(res.data.data.data);
          var data = res.data.data.data;
          this.ruleForm.cropname = data.crop_name;
          this.ruleForm.cropvariety = data.crop_variety;
          this.ruleForm.cropimage = data.crop_image;
          this.ruleForm.cropcolor = data.crop_colors;
          this.ruleForm.cropimage2 = data.crop_image;
          this.tableData = data.cycle_list;
          for(var i=0;i<this.tableData.length;i++){
            this.tableData[i]['nameinput'] = false
          } 
          console.log(this.tableData)
        }
      });
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // var id = this.$route.query.id
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.getcropinfo(this.$route.query.id);
      this.title = "修改农作物";
    } else {
      this.title = "新增农作物";
    }
  },
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='less' scoped>
.cropaddbox {
  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;
    p:first-child {
      font-size: 14px;
      margin-right: 20px;
    }
    p:last-child {
      font-size: 18px;
      font-weight: 700;
    }
  }
  .baselistbox_top_line {
    width: 100%;
    height: 1px;
    background-color: #f2f2f2;
  }
  .baselistbox_top_search {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
    line-height: 28px;
    .demo-ruleForm {
      display: flex;
      width: 80%;
      margin: 0 auto;
      justify-content: space-between;
      .demo-ruleForm-left {
        width: 45%;
      }
      .demo-ruleForm-right {
        width: 45%;
        /deep/.avatar-uploader .el-upload {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
        }
        /deep/.avatar-uploader .el-upload:hover {
          border-color: #4f71ff;
        }
        /deep/.avatar-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          width: 150px;
          height: 150px;
          line-height: 150px;
          text-align: center;
        }
        /deep/.avatar {
          width: 150px;
          height: 150px;
          display: block;
        }
      }
    }
  }
}
.baselistbox_table {
  width: 100%;
  background-color: #fff;
  margin-top: 10px;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
  border-radius: 10px;
  .btnbox2 {
    width: 68px;
    height: 26px;
    border: 1px solid #4f71ff;
    text-align: center;
    border-radius: 3px;
    font-size: 14px;
    line-height: 26px;
    color: #4f71ff;
    margin-bottom: 10px;
    cursor: pointer;
  }
  .monthbox {
    display: flex;
    line-height: 28px;
    /deep/.el-select {
      .el-input__inner {
        border: 0;
      }
    }
    /deep/.el-icon-date {
      line-height: 28px;
      margin: 0 5px;
    }
  }
  .tagbox {
    display: flex;
    align-items: center;
    .selp {
      color: #4f71ff;
      cursor: pointer;
    }
  }
  /deep/.el-tag {
    color: #4f71ff;
    margin-right: 5px;
    margin-bottom: 5px;
    .el-tag__close:hover {
      background-color: #4f71ff;
      color: #fff;
    }
    .el-tag__close {
      color: #4f71ff;
    }
  }
}
.operationbox {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  /deep/.el-button--default {
    border: 1px solid #4f71ff;
    color: #4f71ff;
    background-color: transparent;
  }
}
.wormbox {
  .top_search {
    display: flex;
    margin-bottom: 20px;
    .btnbox {
      width: 68px;
      height: 26px;
      border: 1px solid #4f71ff;
      text-align: center;
      border-radius: 3px;
      font-size: 14px;
      line-height: 26px;
      background-color: #4f71ff;
      color: #fff;
      margin-left: 10px;
      cursor: pointer;
    }
  }
  /deep/.el-table__header {
    th {
      background-color: #f1f1f3;
    }
  }
  .pagination {
    margin-top: 20px;
    /deep/.el-pager {
      .active {
        background-color: #4f71ff !important;
      }
    }
    /deep/.el-input__inner:hover {
      border-color: #4f71ff;
    }
  }
}
</style>