<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-if="showSearch"  @submit.native.prevent>
      <!--<el-form-item label-width="auto" label="种子品种" prop="variety">-->
        <!--<el-input-->
          <!--v-model="queryParams.variety"-->
          <!--placeholder="请输入种子品种"-->
          <!--clearable-->
          <!--size="small"-->
          <!--@keyup.enter.native="handleQuery"-->
        <!--/>-->
      <!--</el-form-item>-->
      <el-form-item label="种子名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入种子名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--<el-form-item label-width="auto" label="种子型号" prop="model">-->
        <!--<el-input-->
          <!--v-model="queryParams.model"-->
          <!--placeholder="请输入种子型号"-->
          <!--clearable-->
          <!--size="small"-->
          <!--@keyup.enter.native="handleQuery"-->
        <!--/>-->
      <!--</el-form-item>-->
      <!--<el-form-item label-width="auto" label="种子售卖量" prop="salesVolume">-->
        <!--<el-input-->
          <!--v-model="queryParams.salesVolume"-->
          <!--placeholder="请输入种子售卖量"-->
          <!--clearable-->
          <!--size="small"-->
          <!--@keyup.enter.native="handleQuery"-->
        <!--/>-->
      <!--</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 label-width="auto" label="种子封装方式" prop="packagingMethod">-->
        <!--<el-input-->
          <!--v-model="queryParams.packagingMethod"-->
          <!--placeholder="请输入种子封装方式"-->
          <!--clearable-->
          <!--size="small"-->
          <!--@keyup.enter.native="handleQuery"-->
        <!--/>-->
      <!--</el-form-item>-->
      <!--<el-form-item label-width="auto" label="创建时间" prop="createDate">-->
        <!--<el-date-picker clearable size="small"-->
          <!--v-model="queryParams.createDate"-->
          <!--type="date"-->
          <!--value-format="yyyy-MM-dd"-->
          <!--placeholder="选择创建时间">-->
        <!--</el-date-picker>-->
      <!--</el-form-item>-->
      <!--<el-form-item label-width="auto" label="修改时间" prop="updateDate">-->
        <!--<el-date-picker clearable size="small"-->
          <!--v-model="queryParams.updateDate"-->
          <!--type="date"-->
          <!--value-format="yyyy-MM-dd"-->
          <!--placeholder="选择修改时间">-->
        <!--</el-date-picker>-->
      <!--</el-form-item>-->
      <!--<el-form-item label-width="auto" label="备注" prop="remarks">-->
        <!--<el-input-->
          <!--v-model="queryParams.remarks"-->
          <!--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>
        <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="['seed_info:SeedInfo: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="['seed_info:SeedInfo: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="['seed_info:SeedInfo: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="['seed_info:SeedInfo: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="['seed_info:SeedInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SeedInfoList" @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="name" />
      <!--<el-table-column label="种子品种" align="center" prop="variety" />-->
      <el-table-column label="种子类型" align="center" prop="seedType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.farm_seed_type" :value="scope.row.seedType"/>
        </template>
      </el-table-column>
      <!--<el-table-column label="种子型号" align="center" prop="model" />-->
      <!--<el-table-column label="种子售卖量" align="center" prop="salesVolume" />-->
      <!--<el-table-column label="种子库存" align="center" prop="stock" />-->
      <el-table-column label="种子封装方式" align="center" prop="packagingMethod">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.farm_encapsulation_way" :value="scope.row.packagingMethod"/>
        </template>
      </el-table-column>
      <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="['seed_info:SeedInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['seed_info:SeedInfo: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="1000px" class="form-style">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="种子名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入种子名称" maxlength="20"/>
            </el-form-item>
            <!--<el-form-item label="种子品种" prop="variety">-->
              <!--<el-input v-model="form.variety" placeholder="请输入种子品种" maxlength="20"/>-->
            <!--</el-form-item>-->
            <el-form-item label="种子类型" prop="seedType">
              <el-select v-model="form.seedType" placeholder="请选择种子类型" filterable>
                <el-option
                  v-for="dict in dict.type.farm_seed_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="种子封装方式" prop="packagingMethod">
              <el-select v-model="form.packagingMethod" placeholder="请选择种子封装方式" filterable>
                <el-option
                  v-for="dict in dict.type.farm_encapsulation_way"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属部门" prop="deptId">
<!--              <Deptselector :setValue=setDataDeptId :dataDeptId="form.deptId"/>-->
              <treeselect v-model="form.deptId" :options="deptOptions" multiple:false :show-count="true" :noResultsText="'空'" :noOptionsText="'空'"
                          placeholder="请选择部门" @select="hx"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="种子型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入种子型号" maxlength="20"/>
            </el-form-item>
            <el-form-item label="种子售卖量(吨)" prop="salesVolume">
              <el-input v-model="form.salesVolume" placeholder="请输入种子售卖量"  maxlength="20"/>
            </el-form-item>
            <el-form-item label="种子库存(吨)" prop="stock">
              <el-input v-model="form.stock" placeholder="请输入种子库存" maxlength="20"/>
            </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
        :noResultsText="'空'"
        :noOptionsText="'空'"
        :flat="false"
        :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_seed_type">{{ dict.label }} </span>
          </span><br>
          <span>种子封装方式：
            <span v-for="dict in dict.type.farm_encapsulation_way">{{ 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 { listSeedInfo, getSeedInfo, delSeedInfo, addSeedInfo, updateSeedInfo } from "@/api/data/digitalagriculture/seed_info/SeedInfo";
import {checkPositiveDecimal} from "@/api/rules/rules";
import Deptselector from '@/views/components/deptselector'
import { getToken } from '@/utils/auth'
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: "SeedInfo",
  dicts: ['farm_encapsulation_way', 'farm_seed_type'],
  components: {
    Deptselector,
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层宽度
      labelWidth: '150px',
      // 文本框宽度
      inputStyle: 'width: 310px',
      // 种子信息表格数据
      SeedInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: [],
      // 导入参数
      upload: {
        // 是否显示导入弹出层
        open: false,
        // 导入弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/center-data/SeedInfo/import/importData'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        variety: null,
        name: null,
        seedType: null,
        model: null,
        salesVolume: null,
        stock: null,
        packagingMethod: null,
        createDate: null,
        updateDate: null,
        remarks: null,
        deptId: null,
        deptName: 0,
      },
      // 表单参数
      form: {},
      //数字验证
      checkPositiveDecimal: checkPositiveDecimal,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "种子名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '种子名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: "所属部门不能为空", trigger: "change" },
        ],
        salesVolume: [
          {required: true, message: "种子售卖量不能为空", trigger: "blur"},
          {validator: checkPositiveDecimal, trigger: 'blur'}
        ],
        stock: [
          {required: true, message: "种子库存不能为空", trigger: "blur"},
          {validator: checkPositiveDecimal, trigger: 'blur'}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    setDataDeptId(e) {
      this.form.deptId = e.deptId;
      this.form.deptName = e.deptName;
    },
    /** 查询部门下拉树结构 */
    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;
      listSeedInfo(this.queryParams).then(response => {
        this.SeedInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        variety: null,
        name: null,
        seedType: null,
        model: null,
        salesVolume: null,
        stock: null,
        packagingMethod: null,
        createBy: null,
        createDate: null,
        updateBy: null,
        updateDate: null,
        deptId: null,
        remarks: null,
        delFlag: 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
      getSeedInfo(id).then(response => {
        this.form = response.data;
        this.title = "修改种子信息";
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSeedInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSeedInfo(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 delSeedInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/center-data/SeedInfo/importTemplate', {}, `SeedInfo_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/SeedInfo/export', {
        ...this.queryParams
      }, `种子信息_${format_date(new Date())}.xlsx`)
    },
    // 点击按钮修改是否只查询本级部门用户
    changeQueryType() {
      this.queryParams.deptName = this.queryParams.deptName === 0 ? 1 : 0;
    }
  }
};
</script>
