<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-if="showSearch"  @submit.native.prevent>
      <el-form-item label="农具品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入农具品牌"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="农具用途" prop="purpose">
        <el-input
          v-model="queryParams.purpose"
          placeholder="请输入农具用途"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="deptId">
        <template slot="label">
          <span @click="changeQueryType" v-if="queryParams.deptName == 0">本级及下级</span>
          <span @click="changeQueryType" v-if="queryParams.deptName == 1">只查询本级</span>
        </template>
        <treeselect v-model="queryParams.deptId" :options="deptOptions" multiple:false :show-count="true"
                    placeholder="请选择部门" @select="hx" :noResultsText="'空'" :noOptionsText="'空'" style="width: 240px"/>
        <el-input v-model="queryParams.deptName" v-if="false"/>
      </el-form-item>
      <!--<el-form-item label-width="auto" label="农具库存" prop="stock">
        <el-input
          v-model="queryParams.stock"
          placeholder="请输入农具库存"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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="['implements_info:ImplementsInfo: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="['implements_info:ImplementsInfo: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="['implements_info:ImplementsInfo:remove']"
        >删除</el-button>
      </el-col>
     <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['implements_info:ImplementsInfo:import']"
        >导入
        </el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['implements_info:ImplementsInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ImplementsInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="${comment}" align="center" prop="id" />-->
      <el-table-column label="农具品牌" align="center" prop="brand" />
      <el-table-column label="农具种类" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.farm_tools_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="农具用途" align="center" prop="purpose" />
      <!--<el-table-column label="农具库存（个）" align="center" prop="stock" />-->
      <el-table-column label="农具数量" align="center" prop="number" />
      <el-table-column label="权属" align="center" prop="ownership" />
      <!--<el-table-column label="创建时间" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" />-->
      <el-table-column label="所属部门" align="center" prop="deptName" />
      <el-table-column label="创建人" align="center" prop="createName"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="修改人" align="center" prop="updateName"/>
      <el-table-column label="修改时间" align="center" prop="updateTime"/>
      <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="handleUpdate(scope.row)"
            v-hasPermi="['implements_info:ImplementsInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['implements_info:ImplementsInfo: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="600px" class="form-style">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="农具品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入农具品牌" maxlength="20"/>
            </el-form-item>
            <el-form-item label="农具种类" prop="type">
              <el-select v-model="form.type" placeholder="请输入农具种类" filterable>
                <el-option
                  v-for="dict in dict.type.farm_tools_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="农具用途" prop="purpose">
              <el-input v-model="form.purpose" placeholder="请输入农具用途" maxlength="20"/>
            </el-form-item>
            <!--<el-form-item label="农具库存个" prop="stock">-->
              <!--<el-input v-model="form.stock" placeholder="请输入农具库存" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"  maxlength="20"/>-->
            <!--</el-form-item>-->
            <el-form-item label="农具数量(个)" prop="number">
              <el-input v-model="form.number" placeholder="请输入农具数量" maxlength="10"/>
            </el-form-item>
            <el-form-item label="权属" prop="ownership">
              <el-input v-model="form.ownership" placeholder="请输入权属" maxlength="20"/>
            </el-form-item>
            <el-form-item label="所属部门" prop="deptId" :label-width="labelWidth">
<!--              <treeselect-->
<!--                v-if="!disable"-->
<!--                :flat="false"-->
<!--                :allowSelectingDisabledDescendants="true"-->
<!--                v-model="form.deptId" :options="deptOptions" :show-count="true"-->
<!--                placeholder="请选择所属部门"/>-->
<!--              <el-select v-model="form.deptName" placeholder="请选择所属部门" :style="inputStyle" v-if="disable" :disabled="disable">-->
<!--                <el-option-->
<!--                  v-for="dept in deptOptions"-->
<!--                  :key="dept.deptId"-->
<!--                  :label="dept.deptName"-->
<!--                  :value="dept"-->
<!--                />-->
<!--              </el-select>-->
<!--              <deptselector :setValue=setDataDeptId :dataDeptId="form.deptId" v-model="form.deptId"></deptselector>-->
              <treeselect v-model="form.deptId" :options="deptOptions" multiple:false :show-count="true" :noResultsText="'空'" :noOptionsText="'空'"
                          placeholder="请选择部门" @select="hx"/>
            </el-form-item>
          </el-col>
        </el-row>
      </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>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <treeselect
        :flat="false"
        :noResultsText="'空'"
        :noOptionsText="'空'"
        :allowSelectingDisabledDescendants="true"
        v-model="upload.deptId" :options="deptOptions" :show-count="true"
        placeholder="请选择所属部门"/>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&deptId=' + upload.deptId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--<div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的数据
          </div>-->
          <span>导入模板字典项</span><br>
          <span>农具种类：
            <span v-for="dict in dict.type.farm_tools_type">{{ dict.label }} </span>
          </span><br>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listImplementsInfo, getImplementsInfo, delImplementsInfo, addImplementsInfo, updateImplementsInfo } from "@/api/data/digitalagriculture/implements_info/ImplementsInfo";
import deptselector from '@/views/components/deptselector';
import {checkNonnegativeInteger} from "@/api/rules/rules";
import { getToken } from '@/utils/auth'
import { treeselectAll } from "@/api/system/dept";
import { treeselect, addDeptToTreeSelect } from "@/api/rfh/community/community";
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {format_date} from "@/views/data/common/dateExport";
import request from "@/utils/request";

export default {
  name: "ImplementsInfo",
  dicts:['farm_tools_type'],
  components: {
    deptselector,
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层宽度
      labelWidth: '150px',
      // 文本框宽度
      inputStyle: 'width: 310px',
      // 农具信息表格数据
      ImplementsInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      // 导入参数
      upload: {
        // 是否显示导入弹出层
        open: false,
        // 导入弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/center-data/ImplementsInfo/import/importData'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        brand: null,
        purpose: null,
        stock: null,
        number: null,
        ownership: null,
        createDate: null,
        updateDate: null,
        deptId: null,
        deptName: 0,
        remarks: null,
      },
      // 表单参数
      form: {},
      // 正整数校验
      checkNonnegativeInteger: checkNonnegativeInteger,
      // 表单校验
      rules: {
        brand: [
          { required: true, message: "农具品牌不能为空", trigger: "blur" }
        ],
        number: [
          {required: true, message: "农具数量不能为空", trigger: "blur"},
          {validator: checkNonnegativeInteger, trigger: 'blur'}
        ],
        deptId: [
          { required: true, message: "所属部门不能为空", trigger: "change" },
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    setDataDeptId(e) {
      this.form.deptId = e.deptId
      this.form.deptName = e.deptName
    },
    setDeptId(deptId) {
      this.form.deptId = deptId
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      request({
        url: '/system/dept/treeselect',
        method: 'get'
      }).then(response => {
        this.deptOptions = response.data;
      });
    },
    hx(node) {
      this.form.dataDeptId = node.id
      this.form.deptId = node.id
      this.form.deptName = node.label
      this.$refs.form.validateField('deptId');
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.handleQuery()
    },
    /** 查询农具信息列表 */
    getList() {
      this.loading = true;
      listImplementsInfo(this.queryParams).then(response => {
        this.ImplementsInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        brand: null,
        purpose: null,
        stock: null,
        number: null,
        ownership: null,
        createBy: null,
        createDate: null,
        updateBy: null,
        updateDate: null,
        remarks: null,
        delFlag: null,
        deptId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.deptName = 0;
      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();
      let _this = this;
      const id = row.id || this.ids
      getImplementsInfo(id).then(response => {
        this.form = response.data;
        this.title = "修改农具信息";
        this.open = true;
        // treeselect().then(response => {
        //   _this.deptOptions = response.data;
        //   treeselectAll().then(response => {
        //     addDeptToTreeSelect(_this.form.deptId, _this.deptOptions, response.data[0]);
        //     this.open = true;
        //   });
        // });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.form.deptName = this.deptOptions.filter((item) => {
          //   return this.form.deptId == item.id;
          // })[0].label;
          if (this.form.id != null) {
            updateImplementsInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addImplementsInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否删除选中的数据？').then(function() {
        return delImplementsInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/center-data/ImplementsInfo/importTemplate', {}, `ImplementsInfo_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/center-data/ImplementsInfo/export', {
        ...this.queryParams
      }, `农具信息_${format_date(new Date())}.xlsx`)
    }
    ,
    // 点击按钮修改是否只查询本级部门用户
    changeQueryType() {
      this.queryParams.deptName = this.queryParams.deptName == 0 ? 1 : 0;
    }
  }
};
</script>
