<template>
  <div class="app-container" ref="appPanel">
    <div ref="toolPanel" class="toolPanel">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <div class="toolTitle">{{ funTitle }}</div>
        </el-col>
        <el-col :span="1.5">
          <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['system:provider:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
            v-hasPermi="['system:provider:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['system:provider: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="['system:provider:import']"
          >导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button plain icon="el-icon-download" size="mini" @click="handleExport"
            v-hasPermi="['system:provider:export']">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">刷新</el-button>
        </el-col>
        <right-toolbar ref="toolBarRef" @customCols="customColsHandler" :showSearch.sync="showSearch"
          showColumnsType="transfer" :columns="columns"></right-toolbar>
      </el-row>
    </div>
    <div class="search-container" ref="searchPanel">
      <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="供应商编号" prop="providerId">
          <el-input v-model="queryParams.providerId" placeholder="请输入供应商编号" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="供应商名称" prop="providerName">
          <el-input v-model="queryParams.providerName" placeholder="请输入供应商名称" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <div ref="mainTablePanel" :style="{ height: mainTableDivHeight }">
        <el-table :key="rndKey" ref="providerTableRef" v-loading="loading" border size="mini" :height="mainTableHeight"
          :data="providerList" @selection-change="handleSelectionChange" @header-dragend="handleHeaderDragEnd">
          <el-table-column type="selection" width="55" align="center" />
          <template>
            <el-table-column v-for="item in columns" :key="item.key" :label="item.label" align="center"
              :prop="item.columnName" v-if="item.visible" :width="item.width" />
          </template>
        </el-table>
        <div class="pagePanel">
          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      </div>
    </div>

    <!-- 添加或修改供应商管理对话框 -->
    <el-dialog id="dialog-container" :title="title" :visible.sync="open" width="600px" append-to-body>
      <div class="edit-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="85px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="供应商编号" prop="providerId">
                <el-input v-model="form.providerId" placeholder="请输入供应商编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="类别编号" prop="proTypeId">
                <el-input v-model="form.proTypeId" placeholder="请输入供应商类别编号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="供应商名称" prop="providerName">
                <el-input v-model="form.providerName" placeholder="请输入供应商名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="拼音简称" prop="pyName">
                <el-input v-model="form.pyName" placeholder="请输入供应商简称" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <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
    >
      <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"
        :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>仅允许导入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 {
  addProvider,
  changeStatus,
  delProvider,
  disabled,
  enabled,
  getProvider,
  listProvider,
  updateProvider,
} from "@/api/system/provider";
import { getToken } from "@/utils/auth";
export default {
  name: "Provider",
  dicts: ["provider_level", "nature", "pay_method"],
  data () {
    return {
      rndKey: 1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商管理表格数据
      providerList: [],
      // 弹出层标题
      title: "",
      funTitle: "供应商管理",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        providerId: null,
        proTypeId: null,
        providerName: null,
        pyName: null,
        address: null,
        contact: null,
        phone: null,
        mobile: null,
        fax: null,
        email: null,
        postCode: null,
        bank: null,
        accountName: null,
        account: null,
        arrDays: null,
        providerLevel: null,
        percent: null,
        nature: null,
        website: null,
        legalMan: null,
        areaId: null,
        regAddress: null,
        invoiceTitle: null,
        taxNumber: null,
        payTypeId: null,
        invoiceAddress: null,
        recipient: null,
        recPhone: null,
        recFax: null,
        recEmail: null,
        selectIds:[]
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        providerId: [{
          required: true,
          message: "供应商编号不能为空",
          trigger: "blur",
        },],
        providerName: [{
          required: true,
          message: "供应商名称不能为空",
          trigger: "blur",
        },],
      },
      columns: [],
      // 供应商导入参数
      upload: {
        // 是否显示弹出层（供应商导入）
        open: false,
        // 弹出层标题（供应商导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的供应商数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/provider/importData",
      },
    };
  },
  created () {
    this.getList();
  },
  mounted () {
    this.computedTableHeight();
  },
  watch: {
    showSearch: function () {
      this.computedTableHeight();
    },
  },
  computed: {

  },
  destroyed() {
    this.columns = [];
  },
  methods: {
    computedTableHeight () {
      this.$nextTick(() => {
        var totalHeight = this.$refs.appPanel.clientHeight;
        var toolHeight = this.$refs.toolPanel.clientHeight;
        var searchHeight = this.$refs.searchPanel.clientHeight;
        var tablePanelHeight = totalHeight - toolHeight - searchHeight - 14 - 5;
        this.mainTableDivHeight = tablePanelHeight + "px";
        this.mainTableHeight = tablePanelHeight - 25 + "px";
      });
    },
    /** 查询供应商管理列表 */
    getList () {
      this.loading = true;
      listProvider(this.queryParams).then((response) => {
        this.columns = [];
        console.log(this.columns)
        this.columns = response.columns;
        this.providerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        providerId: null,
        proTypeId: null,
        providerName: null,
        pyName: null,
        address: null,
        contact: null,
        phone: null,
        mobile: null,
        fax: null,
        email: null,
        postCode: null,
        bank: null,
        accountName: null,
        account: null,
        arrDays: null,
        providerLevel: null,
        percent: null,
        remark: null,
        nature: null,
        website: null,
        legalMan: null,
        areaId: null,
        regAddress: null,
        invoiceTitle: null,
        taxNumber: null,
        payTypeId: null,
        invoiceAddress: null,
        recipient: null,
        recPhone: null,
        recFax: null,
        recEmail: null,
        version: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: 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;
      this.queryParams.selectIds=this.ids;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加供应商管理";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const id = row.id || this.ids;
      getProvider(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改供应商管理";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateProvider(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProvider(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 delProvider(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },

    /** 用户状态修改 */
    handleStatusChange (row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '"id为"' + row.id + '"数据项？')
        .then(function () {
          return changeStatus(row.id, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    /** 启用按钮操作 */
    handleEnable (row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认启用供应商管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return enabled(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("启用成功");
        })
        .catch(() => { });
    },
    /** 禁用按钮操作 */
    handleDisabled (row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认禁用供应商管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return disabled(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("禁用成功");
        })
        .catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "system/provider/export", {
        ...this.queryParams,
      },
        `provider_${new Date().getTime()}.xlsx`
      );
    },
    customColsHandler(columns) {
      this.columns = columns;
      this.rndKey = Math.random();
    },

    handleHeaderDragEnd(newWidth, oldWidth, column, event) {
      debugger
      // 当列宽发生变化时，将变化值写入到columns变量中。
      this.columns.map((obj) => {
        if (obj.columnName == column.property) obj.width = newWidth;
      });
      console.log(this.columns)
      this.$refs.toolBarRef.saveConfig(this.columns);
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "供应商导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/provider/importTemplate",
        {},
        `provider_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>",
        "导入结果",
        { dangerouslyHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

  },
};
</script>

<style scoped>
.app-container {
  height: calc(100vh - 84px);
}
</style>
