<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="地块编号" prop="fieldCode">
        <el-input v-model="queryParams.fieldCode" placeholder="请输入地块编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="地块名称" prop="fieldName">
        <el-input v-model="queryParams.fieldName" placeholder="请输入地块名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="所属农场" prop="farmId">
        <el-input v-model="queryParams.farmId" placeholder="请输入所属农场ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->

      <el-form-item label="所属农场" prop="deptIdList">
        <treeselect v-model="queryParams.deptIdList" :options="deptOptions" multiple :flat="true" :limit="1"
          :limitText="count => `+${count}`" style="width:200px" :show-count="true" placeholder="请选所属机构" />
      </el-form-item>


      <el-form-item label="使用状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择使用状态" clearable>
          <el-option v-for="dict in dict.type.field_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="地块类型" prop="fieldType">
        <el-select v-model="queryParams.fieldType" placeholder="请选择地块类型" clearable>
          <el-option v-for="dict in dict.type.sys_field_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="种植作物" prop="growCrops">
        <el-input v-model="queryParams.growCrops" placeholder="请输入种植作物" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="土壤类型" prop="soilType">
        <el-select v-model="queryParams.soilType" placeholder="请选择土壤类型" clearable>
          <el-option v-for="dict in dict.type.field_soil_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="灌溉方式" prop="irrigationType">
        <el-select v-model="queryParams.irrigationType" placeholder="请选择灌溉方式" clearable>
          <el-option v-for="dict in dict.type.field_irrigation_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="负责人" prop="managerId">
        <el-input v-model="queryParams.managerId" placeholder="请输入负责人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="创建时间" prop="createdTime">
        <el-date-picker clearable v-model="queryParams.createdTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item> -->

      <el-form-item label="日期" prop="rangeTime" :width="150">
        <el-date-picker v-model="queryParams.rangeTime" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:field:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:field:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:field:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:field:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fieldList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="地块编号" align="center" prop="fieldCode" />
      <el-table-column label="地块名称" align="center" prop="fieldName" />
      <!-- <el-table-column label="所属农场" align="center" prop="farmId" /> -->
      <el-table-column label="所属农场" align="center" key="deptName" prop="dept.deptName" />
      <el-table-column label="地块类型" align="center" prop="fieldType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_field_type" :value="scope.row.fieldType" />
        </template>
      </el-table-column>
      <el-table-column label="面积(亩)" align="center" prop="size" />
      <el-table-column label="种植作物" align="center" prop="growCrops" />

      <el-table-column label="土壤类型" align="center" prop="soilType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.field_soil_type" :value="scope.row.soilType" />
        </template>
      </el-table-column>
      <el-table-column label="灌溉方式" align="center" prop="irrigationType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.field_irrigation_type" :value="scope.row.irrigationType" />
        </template>
      </el-table-column>
      <el-table-column label="使用状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.field_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="绑定设备" align="center" prop="bindDeviceCount" />
      <el-table-column label="绑定人员" align="center" prop="bindUserCount" />
      <el-table-column label="负责人" align="center" prop="managerName" />
      <!-- <el-table-column label="地块描述" align="center" prop="description" />
      <el-table-column label="地理位置数据(GeoJSON格式)" align="center" prop="locationData" /> -->
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上次更新" align="center" prop="updatedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button size="mini" type="text" icon="el-icon-edit" @click="management(scope.row)"
            v-hasPermi="['system:field:edit']">管理</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:field:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:field:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改地块信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="地块名称" prop="fieldName">
          <el-input v-model="form.fieldName" placeholder="请输入地块名称" />
        </el-form-item>

        <el-form-item label="地块编号" prop="fieldCode">
          <el-input v-model="form.fieldCode" placeholder="请输入地块编号" />
        </el-form-item>

        <!-- <el-form-item label="所属农场" prop="farmId">
          <el-input v-model="form.farmId" placeholder="请输入所属农场ID" />
        </el-form-item> -->

        <el-form-item label="所属农场" prop="farmId">
          <treeselect v-model="form.farmId" :options="deptOptions" :show-count="true" placeholder="请选所属机构"
            @input='queryPersonCharge(form.farmId)' :disabled="detail" />
        </el-form-item>

        <el-form-item label="地块类型" prop="fieldType">
          <el-select v-model="form.fieldType" placeholder="请选择地块类型">
            <el-option v-for="dict in dict.type.sys_field_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="面积(亩)" prop="size">
          <el-input v-model="form.size" placeholder="请输入面积(亩)" />
        </el-form-item>

        <el-form-item label="负责人" prop="managerId">
          <el-input v-model="form.managerName" placeholder="请输入负责人" />
        </el-form-item>

        <el-form-item label="种植作物" prop="growCrops">
          <el-input v-model="form.growCrops" placeholder="请输入种植作物" />
        </el-form-item>

        <el-form-item label="土壤类型" prop="soilType">
          <el-select v-model="form.soilType" placeholder="请选择土壤类型">
            <el-option v-for="dict in dict.type.field_soil_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="灌溉方式" prop="irrigationType">
          <el-select v-model="form.irrigationType" placeholder="请选择灌溉方式">
            <el-option v-for="dict in dict.type.field_irrigation_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="使用状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.field_status" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="地块描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listField, getField, delField, addField, updateField } from "@/api/base/field"
import { deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Field",
  components: { Treeselect },
  dicts: ['field_status', 'field_irrigation_type', 'field_soil_type','sys_field_type'],
  data() {
    return {
      // 点击详情按钮是否可编辑
      detail: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 地块信息表格数据
      fieldList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门树选项
      deptOptions: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fieldCode: null,
        fieldName: null,
        farmId: null,
        fieldType: null,
        growCrops: null,
        size: null,
        soilType: null,
        irrigationType: null,
        status: null,
        managerId: null,
        description: null,
        locationData: null,
        createdTime: null,
        updatedTime: null,
        createdBy: null,
        updatedBy: null,
        deptIdList: [],
        rangeTime: [],
        isDeleted: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fieldCode: [
          { required: true, message: "地块编号不能为空", trigger: "blur" }
        ],
        fieldName: [
          { required: true, message: "地块名称不能为空", trigger: "blur" }
        ],
        farmId: [
          { required: true, message: "所属农场ID不能为空", trigger: "blur" }
        ],
        fieldType: [
          { required: true, message: "地块类型不能为空", trigger: "change" }
        ],
        growCrops: [
          { required: true, message: "种植作物(字典)不能为空", trigger: "blur" }
        ],
        size: [
          { required: true, message: "面积(亩)不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "使用状态不能为空", trigger: "change" }
        ],
        createdTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updatedTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
        createdBy: [
          { required: true, message: "创建人ID不能为空", trigger: "blur" }
        ],
        updatedBy: [
          { required: true, message: "更新人ID不能为空", trigger: "blur" }
        ],
        isDeleted: [
          { required: true, message: "是否删除不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /**查询对应的负责人 */
    queryPersonCharge() {

    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },

    /** 查询地块信息列表 */
    getList() {

      console.log(this.queryParams);
      
      this.loading = true
      if (null != this.queryParams.rangeTime && '' != this.queryParams.rangeTime) {
        this.queryParams.params["beginfieldDate"] = this.queryParams.rangeTime[0];
        this.queryParams.params["endfieldDate"] = this.queryParams.rangeTime[1];
      }
      listField(this.queryParams).then(response => {
        this.fieldList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        fieldCode: null,
        fieldName: null,
        farmId: null,
        fieldType: null,
        growCrops: null,
        size: null,
        soilType: null,
        irrigationType: null,
        status: null,
        managerId: null,
        description: null,
        locationData: null,
        createdTime: null,
        updatedTime: null,
        createdBy: null,
        updatedBy: null,
        isDeleted: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加地块信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getField(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改地块信息"
      })
    },

    /** 管理按钮操作 */
    management(row) {
      //console.log(row.id);
      
       this.$router.push('/management/index/' + row.id);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateField(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addField(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除地块信息编号为"' + ids + '"的数据项？').then(function () {
        return delField(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/field/export', {
        ...this.queryParams
      }, `field_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
