<template>
  <div class="templateList">
    <div class="form-box">
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-position="left"
        size="mini"
        label-width="80px"
        class="form"
      >
        <el-row :gutter="36">
          <el-col :span="8">
            <el-form-item label="层级" prop="level" label-width="40px">
              <el-select style="width: 100%" v-model="searchForm.level" clearable>
                <el-option
                  v-for="item in orgLevelArr"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行员号" prop="userId" label-width="60px">
              <el-input
                clearable
                v-model="searchForm.userId"
                style="width: 100%"
                placeholder="请输入行员号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行员姓名" prop="userName">
              <el-input
                clearable
                v-model="searchForm.userName"
                style="width: 100%"
                placeholder="请输入行员姓名"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="button">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleResetSearch">重置</el-button>
      </div>
    </div>

    <div class="control-button">
      <el-upload
        style="display: inline-block;margin-right: 10px;"
        :limit="1"
        accept=".xlsx"
        action="#" 
        :http-request="requestUpload" 
        :show-file-list="false" 
        :before-upload="beforeUpload"
        :disabled="loadingUpload"
        ref="uploadRef"
      >
        <el-button icon="el-icon-upload2" type="primary">上传文件</el-button>
      </el-upload>
      <el-button icon="el-icon-download" @click="downloadFile">
        下载模板
      </el-button>
      <el-button :disabled="selectedRow.length <= 0" @click="handleBatchDelete">
        批量删除
      </el-button>
    </div>

    <div class="table-box">
      <el-table
        ref="tableRef"
        :data="tableData"
        size="mini"
        style="widht: 100%"
        ighlight-current-row
        @selection-change="handleChangeSelection"
        v-loading="tableLoading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="机构号" prop="orgId" min-width="160" />
        <el-table-column label="层级" prop="level" min-width="160">
          <template slot-scope="scope">
            {{ getLevel(scope.row.level) }}
          </template>
        </el-table-column>
        <el-table-column label="行员号" prop="userId" min-width="160" />
        <el-table-column label="行员姓名" prop="userName" min-width="160" />
        <el-table-column label="操作" prop="edit" width="160" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleUpdate(scope)">
              修改
            </el-button>
            <el-button type="text" size="small" @click="handleDelete(scope)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlepageChange"
      />
    </div>

    <el-dialog title="提示" :visible.sync="showTips" width="30%">
      <span>确认删除选中的数据吗？</span>
      <div slot="footer">
        <el-button @click="handleCancelDelete">取消</el-button>
        <el-button type="primary" @click="handleConfirmDelete">确定</el-button>
      </div>
    </el-dialog>

    <update-modal
      :dialogVisible="dialogVisible"
      :orgLevelArr="orgLevelArr"
      :rowInfo="rowInfo"
      @close="dialogVisible = false"
      @fresh="getData"
    />
  </div>
</template>

<script>
import { getModelList, deleteByIds, uploadLevel } from "@/api/configure/levelConfig.js";
import UpdateModal from "./updateLevelModal.vue";
export default {
  data() {
    return {
      searchForm: {},
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      deleteIds: [],
      showTips: false,
      selectedRow: [],
      orgLevelArr: [
        { label: "网点", value: "2" },
        { label: "支行", value: "1" },
        { label: "总行", value: "0" },
      ],
      dialogVisible: false,
      loadingUpload: false,
      tableLoading: false,
      rowInfo: {}
    };
  },
  mounted() {
    this.getData();
  },
  components: {
    UpdateModal,
  },
  methods: {
    getLevel(val) {
      const index = this.orgLevelArr.findIndex(v => v.value === val)
      if (index > -1) return this.orgLevelArr[index].label
      return ''
    },
    getData() {
      const params = {
        num: (this.currentPage-1)*this.pageSize,
        size: this.pageSize,
        ...this.searchForm
      };
      this.tableLoading = true;
      getModelList(params).then((res) => {
        this.tableData = res.rows || [];
        this.total = res.total;
        this.tableLoading = false;
      }).catch(error => {
        this.tableLoading = false;
      });
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.getData();
    },

    handlepageChange(newPage) {
      this.currentPage = newPage;
      this.getData();
    },

    handleSearch() {
      this.currentPage = 1;
      this.getData();
    },

    handleResetSearch() {
      this.searchForm = {};
      this.handleSearch();
    },

    handleUpdate(scope) {
        this.rowInfo = scope.row
        this.dialogVisible = true
    },

    handleDelete(scope) {
      this.deleteIds = [scope.row.id];
      this.showTips = true;
    },

    handleCancelDelete() {
      this.deleteIds = [];
      this.showTips = false;
    },

    handleConfirmDelete() {
      const params = this.deleteIds.join(",");
      deleteByIds(params).then((res) => {
        if (res.code === 200) {
          this.showTips = false;
          this.$message.success("删除成功");
          this.currentPage = 1;
          this.pageSize = 10;
          this.total = 0;
          this.getData();
        }
      });
    },

    handleChangeSelection(selection) {
      this.selectedRow = selection;
    },

    handleBatchDelete() {
      this.deleteIds = this.selectedRow.map((item) => item.id);
      this.showTips = true;
    },

    downloadFile() {
      const API = "system/lscjSysuser/export";
      const TEXT = "层级设置模板";
      this.download(API, {}, `${TEXT}_${new Date().getTime()}.xlsx`);
    },

    // 上传之前格式校验
    beforeUpload(file) {
        const isExcel = file.name.search('xlsx') !== -1;
        if (!isExcel) {
            this.$message.warn("请导入正确的格式！");
            return false;
        }
        return true;
    },

    // 导入
    async requestUpload(fileOut) {
        const { file } = fileOut;
        const formData = new FormData();
        formData.append('file', file);
        this.loadingUpload = true;
        console.log('formData', formData)
        try {
          this.tableLoading = true;
          const res = await uploadLevel(formData);
          if (res.code === 200) {
              this.currentPage = 1;
              this.getData();
              this.$message.success("导入完成！");
          } else {
              this.$message.warn(res.data?.msg);
          }
          this.loadingUpload = false;
        } catch (error) {
          this.loadingUpload = false;
          this.tableLoading = false;
        }
        this.$refs.uploadRef.clearFiles()
    }
  },
};
</script>

<style scoped lang="scss">
.templateList {
  padding: 30px 16px;
  .form-box {
    display: flex;
    justify-content: space-between;
    .form {
      width: 70%;
    }
  }

  .control-button {
    margin-bottom: 16px;
  }

  .table-box {
    .el-pagination {
      float: right;
      margin-top: 8px;
    }
  }
}
</style>
