<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-row>
        <el-col :span="8">
          <el-form-item class="treeselectForm treeselectForm2" label="组织架构" prop="deptCodes">
            <tree @treeselectFn="treeselectFn" :treeval="queryParams.deptCodes" style="width: 193px;"></tree>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item class="treeselectForm treeselectForm2" label="区县" prop="streetCode">
            <quxian @treeselectFn="quxianselectFn" :treeval="queryParams.streetCodes" style="width: 193px;"></quxian>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <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-col>
      </el-row>
    </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="['sfa:streetDept:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-circle-check"
          size="mini"
          :disabled="multiple"
          @click="effectFn"
          v-hasPermi="['sfa:streetDept: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="['sfa:streetDept: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="['sfa:streetDept:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['sfa:streetDept:add']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="streetDeptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="省" align="center" prop="provinceName" />
      <el-table-column label="市" align="center" prop="cityName" />
      <el-table-column label="区县code" align="center" prop="streetCode" />
      <el-table-column label="区县名称" align="center" prop="streetName" width="180" />
      <el-table-column label="销售部code" align="center" prop="deptCode" width="90" />
      <el-table-column label="销售部名称" align="center" prop="deptName" width="180" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.effectTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="生效时间" align="center" prop="effectTime" width="180">
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.effectTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="effectFn(scope.row)"
            v-hasPermi="['sfa:streetDept:edit']"
          >生效</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sfa:streetDept:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sfa:streetDept:remove']"
            class="text-danger"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :pageSizes="pageSizes"
      :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 :class="['treeselectForm','treeselectForm3']" label="组织架构" prop="deptCode">
           <tree-single @treeselectFn="treeselectFnSingle" :treeval="form.deptCode" :ismultiple="false" style="width:293px;"></tree-single>
        </el-form-item>
        <el-form-item class="treeselectForm treeselectForm3" label="区县名称" prop="streetCode">
          <quxian-single @treeselectFn="quxianselectFnSingle" :treeval="form.streetCode" style="width:293px;"></quxian-single>
        </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>

    <el-dialog class="upload" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <div style="margin-bottom: 14px;">
        <!--<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据-->
        <el-link type="primary" style="font-size:14px" @click="importTemplate">下载模板</el-link>
      </div>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="importError"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</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 { listStreetDept, getStreetDept, delStreetDept, addStreetDept, updateStreetDept,effect,streetDeptImport } from "@/api/sfa/streetDept";
import tree from "@/views/components/sfa/treeselect";
import treeSingle from "@/views/components/sfa/treeselectSingle";
import quxian from "@/views/components/sfa/quxian";
import quxianSingle from "@/views/components/sfa/quxianSingle";
import { getToken } from "@/utils/auth";
export default {
  name: "StreetDept",
    components: { tree,treeSingle,quxian,quxianSingle },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售部与区县对应关系表格数据
      streetDeptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        streetCodes: null,
        deptCodes: null,
      },
        pageSizes:[10, 50, 100],
      // 表单参数
      form: {
          streetCode: null,
          deptCode: null,
      },
      // 表单校验
      rules: {
          streetCode:[ { required: true, message: '请选择组织架构', trigger: 'change' }],
          deptCode:[ { required: true, message: '请选择区县', trigger: 'change' }],
      },
        upload: {
            // 是否显示弹出层（用户导入）
            open: false,
            // 弹出层标题（用户导入）
            title: "",
            // 是否禁用上传
            isUploading: false,
            // 是否更新已经存在的用户数据
            updateSupport: 0,
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + "/sfa/streetDept/import"
        },
        loadingImport:null,
    };
  },
  created() {
    this.getList();
  },
  methods: {
      treeselectFn(val){
          this.queryParams.deptCodes = val;
      },
      treeselectFnSingle(val){
          this.form.deptCode = val;
      },
      quxianselectFn(val){
          this.queryParams.streetCodes = val;
      },
      quxianselectFnSingle(val){
          this.form.streetCode = val;
      },
    /** 查询销售部与区县对应关系列表 */
    getList() {
      this.loading = true;
      listStreetDept(this.queryParams).then(response => {
        this.streetDeptList = response.rows;
        this.total = response.total;
        if(response.total > 100){
            this.pageSizes = [10, 50, 100,response.total];
        }
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        streetCode: null,
        deptCode: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.queryParams.streetCodes = null;
        this.queryParams.deptCodes = null;
      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 id;
      if(row.id || row.id === 0){
          id = row.id;
      }else{
          id = this.ids;
      }
      getStreetDept(id).then(response => {
        this.form = response.data;
        this.form.deptCode =parseInt(this.form.deptCode);
        this.form.streetCode =this.form.streetCode;
        this.open = true;
        this.title = "修改销售部与区县对应关系";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStreetDept(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStreetDept(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
      effectFn(row){
          const loading = this.$loading({
              lock: true,
              text: '批量生效中，注意：批量生效用时较长，无需重复操作，几分钟后查看生效时间',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
          });
          let id = [];
          if(row.id || row.id === 0){
              id.push(row.id);
          }else{
              id = this.ids;
          }
          effect({id}).then(response => {
              if(response && response.code == 200){
                  loading.close();
                  this.$modal.msgSuccess("生效成功");
                  this.getList();
              }else{
                  setTimeout(() => {
                      loading.close();
                  }, 2000);
              }

          });
      },
    /** 删除按钮操作 */
    handleDelete(row) {
        let that = this;
        let id = [];
        if(row.id || row.id === 0){
            id.push(row.id) ;
        }else{
            id = this.ids;
        }
      // const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该的数据项？').then(function() {
        delStreetDept({id}).then(response => {
            if(response && response.code == 200){
                that.getList();
                that.$modal.msgSuccess("删除成功");
            }else{
                that.$modal.msgError("删除失败");
            }

        });
      }).then(() => {

      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sfa/streetDept/export', {
        ...this.queryParams
      }, `streetDept_${new Date().getTime()}.xlsx`)
    },
      /** 导入按钮操作 */
      handleImport() {
          this.upload.title = "销售部与区县对应关系导入";
          this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
          let url = '';
          if(process.env.NODE_ENV != "production"){
              url = 'ssbsfa/';
          }
          window.location.href = process.env.VUE_APP_DOWNLOADURL+ url + 'profile/upload/template/%E5%8C%BA%E5%8E%BF%E9%94%80%E5%94%AE%E9%83%A8%E5%8F%98%E6%9B%B4.xlsx'
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
          this.loadingImport = this.$loading({
              lock: true,
              text: '上传中',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
          });
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
          if(response.code==200){
              this.upload.open = false;
              this.upload.isUploading = false;
              this.$refs.upload.clearFiles();
              this.loadingImport.close();
              this.$modal.msgSuccess("导入成功");
              this.getList();
          }else{
              this.upload.open = false;
              this.upload.isUploading = false;
              this.$refs.upload.clearFiles();
              this.loadingImport.close();
              this.$modal.msgError('导入失败：'+response.msg);
          }
      },
      importError(err, file, fileList){
      },
      // 提交上传文件
      submitFileForm() {
          this.$refs.upload.submit();
      }
  }
};
</script>
