<template>
  <div class="app-container">
    <!--操作区-->
    <el-button
      type="primary"
      icon="el-icon-plus"
      @click="create"
      class="margin-left"
      >添加商户号</el-button
    >
    <el-button
      type="primary"
      icon="el-icon-download"
      @click="download"
      class="margin-left"
      >下载模板</el-button
    >

    <a href="javascript:;" v-if="checkRole([5])" class="file margin-sm"
      >批量导入<input
        type="file"
        name="file"
        ref="file"
        @change="chooseFile($event)"
    /></a>
    <el-button
      type="primary"
      @click="bulkImport"
      class="margin-left"
      v-else
      plain
      >批量导入</el-button
    >
    <!--搜索区-->
    <el-select
      filterable
      clearable
      v-model="page.data.adminId"
      placeholder="请选择所属账号"
      class="margin-left input"
    >
      <el-option
        v-for="item in user_list"
        :key="item.adminId"
        :label="item.username"
        :value="item.adminId"
      >
      </el-option>
    </el-select>
    <el-input
      v-model="page.data.bussinessNumber"
      placeholder="请输入商户号"
      class="margin-left input"
    ></el-input>
    <el-button
      type="primary"
      icon="el-icon-search"
      @click="fetchData"
      class="margin-left"
      >搜索</el-button
    >
    <!--主表格-->
    <el-table
      class="table"
      ref="table_form"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="序号" align="center" width="80px">
        <template slot-scope="scope">
          {{ indexMethod(scope.$index) }}
        </template>
      </el-table-column>
      <el-table-column label="商户号" align="center">
        <template slot-scope="scope">
          {{ scope.row.bussinessNumber | matchNull }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="姓名" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name | matchNull }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center">
        <template slot-scope="scope">
          {{ scope.row.phone | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="身份证" align="center">
        <template slot-scope="scope">
          {{ scope.row.phone | matchNull }}
        </template>
      </el-table-column>
      <el-table-column
        label="省-市-区-街道"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.provinceName | matchNull }}-{{
            scope.row.cityName | matchNull
          }}-{{ scope.row.areaName | matchNull }}-{{
            scope.row.streetName | matchNull
          }}
        </template>
      </el-table-column>
      <el-table-column label="社区" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.streetName | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.address | matchNull }}
        </template>
      </el-table-column> -->
      <el-table-column label="所属账号" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.username | matchNull }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="" label="操作区" width="200">
        <template slot-scope="scope">
          <el-button
            type="danger"
            size="small"
            @click="deleteUser(scope.row.id)"
            >删除</el-button
          >
          <el-button type="primary" size="small" @click="update(scope.row)"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--分页栏-->
    <pagination
      :total="total"
      :page.sync="page.pageNum"
      :limit.sync="page.pageSize"
      @pagination="fetchData"
    />
    <!--对话框-->
    <el-dialog
      :title="dialogTitle[dialogType]"
      :visible.sync="dialogVisible"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="user_form"
        :rules="rules"
        ref="user_form"
        label-width="120px"
        label-position="left"
      >
        <!-- <div class="flex">
          <el-form-item label="省" prop="provinceId" label-width="120px">
            <el-select
              v-model="user_form.provinceId"
              @change="chooseProvince"
              placeholder="请选择省份"
            >
              <el-option
                v-for="item in province_list"
                :key="item.areaCodeId"
                :label="item.name"
                :value="item.areaCodeId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="市"
            prop="cityId"
            label-width="50px"
            style="margin-left: 10px"
          >
            <el-select
              v-model="user_form.cityId"
              @change="chooseCity"
              placeholder="请选择城市"
            >
              <el-option
                v-for="item in city_list"
                :key="item.areaCodeId"
                :label="item.name"
                :value="item.areaCodeId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="区/县"
            prop="areaId"
            label-width="60px"
            style="margin-left: 10px"
          >
            <el-select
              v-model="user_form.areaId"
              @change="chooseArea"
              placeholder="请选择区/县"
            >
              <el-option
                v-for="item in area_list"
                :key="item.areaCodeId"
                :label="item.name"
                :value="item.areaCodeId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="街道" prop="streetId" label-width="120px">
          <el-select
            v-model="user_form.streetId"
            style="width: 100%"
            placeholder="请选择街道"
          >
            <el-option
              v-for="item in street_list"
              :key="item.areaCodeId"
              :label="item.name"
              :value="item.areaCodeId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="社区" prop="streetId" label-width="120px">
          <el-select
            v-model="user_form.streetId"
            style="width: 100%"
            placeholder="请选择街道"
          >
            <el-option
              v-for="item in street_list"
              :key="item.areaCodeId"
              :label="item.name"
              :value="item.areaCodeId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="address" label-width="120px">
          <el-input
            show-word-limit
            v-model.trim="user_form.address"
            placeholder="请选择详细地址"
          />
        </el-form-item>
        <div class="flex">
          <el-form-item
            label="姓名"
            style="margin-right: 5px; flex: 0.5"
            prop="name"
          >
            <el-input
            placeholder="请输入姓名"
              maxlength="10"
              show-word-limit
              v-model.trim="user_form.name"
            />
          </el-form-item>
          <el-form-item
            label="手机号"
            style="margin-left: 5px; flex: 0.5"
            prop="phone"
          >
            <el-input
              placeholder="请输入手机号"
              maxlength="11"
              show-word-limit
              v-model.trim="user_form.phone"
            />
          </el-form-item>
        </div> -->
        <div class="flex">
          <el-form-item
            label="绑定账号"
            prop="adminId"
            style="margin-right: 5px; flex: 0.5"
          >
            <el-select
              filterable
              clearable
              v-model="user_form.adminId"
              placeholder="请选择账号"
              style="width: 100%"
            >
              <el-option
                v-for="item in user_list"
                :key="item.adminId"
                :label="item.username"
                :value="item.adminId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="商户号"
            style="margin-left: 5px; flex: 0.5"
            prop="bussinessNumber"
          >
            <el-input
              placeholder="请输入商户号"
              v-model.trim="user_form.bussinessNumber"
            />
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogType === 'add' ? add() : doUpdate()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <!--导入对话框-->
    <el-dialog title="批量导入" :visible.sync="dialogVisibleUpload" width="40%">
      <el-form
        :model="form_upload"
        :rules="rules_upload"
        ref="form_upload"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="绑定账号" prop="adminId">
          <el-select
            filterable
            clearable
            v-model="form_upload.adminId"
            placeholder="请选择账号"
          >
            <el-option
              v-for="item in user_list"
              :key="item.adminId"
              :label="item.username"
              :value="item.adminId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <a href="javascript:;" class="file margin0"
            >{{ form_upload.file ? form_upload.file.name : "选择文件"
            }}<input
              type="file"
              name="file"
              ref="file"
              @change="chooseFile($event)"
          /></a>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleUpload = false"> 取消 </el-button>
        <el-button type="primary" @click="upload"> 确定 </el-button>
      </div>
    </el-dialog>

    <!--错误返回-->
    <el-dialog
      title="提示"
      center
      :visible.sync="resultVisible"
      destroy-on-close
    >
      <el-table
        class="table"
        ref="table_form_result"
        v-loading="false"
        :data="result_list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        height="500"
      >
        <el-table-column label="错误序号" align="center" width="100px">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="错误描述" align="center">
          <template slot-scope="scope">
            {{ scope.row | matchNull }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resultVisible = false">
          我已知晓
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserListSearch } from "@/api/user_manage";
import Pagination from "@/components/Pagination";
import { checkRole } from "@/utils/checkRole";
import { uploadAdminInfoExcel } from "@/api/ordinary_user"; // secondary package based on el-pagination
import {
  deleteMerchants,
  edit,
  getPageList,
  uploadBussinessNumberExcel,
} from "@/api/merchants";
export default {
  components: { Pagination },
  filters: {
    matchNull(str) {
      if (!str) {
        return "-";
      } else {
        return str;
      }
    },
  },
  data() {
    return {
      // 主表格&主表格加载状态
      list: null,
      listLoading: true,
      // 分页参数
      page: {
        data: {
          adminId: null,
          bussinessNumber: null,
        },
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      // 账号列表_搜索
      user_list: [],
      // 是否显示对话框
      dialogVisible: false,
      // 对话框标题
      dialogTitle: {
        add: "添加商户号",
        update: "编辑商户号",
      },
      dialogType: "add",
      // 添加账号参数
      user_form: {
        adminId: null,
        bussinessNumber: null,
        id: null,
      },
      user_form_copy: {},
      // 验证规则
      rules: {
        adminId: [
          { required: true, message: "请选择所属账号", trigger: "change" },
        ],
        bussinessNumber: [
          { required: true, message: "请输入商户号", trigger: "change" },
        ],
      },
      dialogVisibleUpload: false,
      // 批量导入结果返回
      resultVisible: false,
      result_list: [],

      // 批量导入
      form_upload: {
        adminId: null,
        file: null,
      },
      // 验证规则--批量导入
      rules_upload: {
        adminId: [{ required: true, message: "请选择账号", trigger: "blur" }],
        file: [{ required: true, message: "请上传文件", trigger: "blur" }],
      },
    };
  },
  created() {
    this.fetchData();
    this.getUserListSearch();
    this.user_form_copy = JSON.parse(JSON.stringify(this.user_form));
    this.form_upload_copy = JSON.parse(JSON.stringify(this.form_upload));
  },
  methods: {
    // 查询权限
    checkRole,
    // 获取列表数据
    fetchData() {
      this.listLoading = true;
      getPageList(this.page).then((res) => {
        this.list = res.data.list;
        this.total = res.data.total;
        this.listLoading = false;
      });
    },
    // 打开添加账号对话框
    create() {
      this.user_form = JSON.parse(JSON.stringify(this.user_form_copy));
      this.dialogType = "add";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["user_form"].clearValidate();
      });
    },
    // 获取账号列表数据_搜索
    getUserListSearch() {
      getUserListSearch().then((res) => {
        this.user_list = res.data;
      });
    },
    // 确定添加
    add() {
      this.$refs["user_form"].validate((valid) => {
        if (valid) {
          edit(this.user_form).then((res) => {
            this.dialogVisible = false;
            this.fetchData();
            this.$message({
              type: "success",
              message: "添加成功!",
            });
          });
        }
      });
    },
    // 删除账号
    deleteUser(id) {
      this.$confirm("确定要删除此账号吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        deleteMerchants(id).then((res) => {
          this.fetchData();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        });
      });
    },
    // 打开编辑
    update(row) {
      this.user_form = Object.assign(this.user_form, row);
      this.dialogType = "update";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["user_form"].clearValidate();
      });
    },
    // 确定编辑
    doUpdate() {
      this.$refs["user_form"].validate((valid) => {
        if (valid) {
          edit(this.user_form).then((res) => {
            this.dialogVisible = false;
            this.fetchData();
            this.$message({
              type: "success",
              message: "编辑成功!",
            });
          });
        }
      });
    },
    // 下载模板
    download() {
      window.location.href =
        process.env.VUE_APP_BASE_API + "/static/bussinessNubmerExcel.xlsx";
    },
    // 打开批量导入对话框
    bulkImport() {
      this.form_upload = JSON.parse(JSON.stringify(this.form_upload_copy));
      this.dialogVisibleUpload = true;
      this.$nextTick(() => {
        this.$refs["form_upload"].clearValidate();
      });
    },
    // 选择文件
    chooseFile(e) {
      var files = e.currentTarget.files;
      if (!files.length) {
        return;
      }
      this.form_upload.file = files[0];
      if (!checkRole([1, 2])) {
        this.upload();
      }
    },
    upload() {
      let isUpload = false;
      if (!checkRole([1, 2])) {
        isUpload = true;
      } else {
        this.$refs.form_upload.validate((valid) => {
          isUpload = valid;
        });
      }
      if (isUpload) {
        const loading = this.$loading({
          lock: true,
          text: "拼命导入中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        var formData = new FormData();
        formData.append("file", this.form_upload.file);
        formData.append("adminId", this.form_upload.adminId);
        uploadBussinessNumberExcel(formData)
          .then((res) => {
            loading.close();
            this.fetchData();
            if (res.data.length > 0) {
              this.resultVisible = true;
              this.result_list = res.data;
            } else {
              this.dialogVisibleUpload = false;
              this.$message({
                type: "success",
                message: "导入成功!",
              });
            }
          })
          .catch((err) => {
            loading.close();
            this.fetchData();
          });
      }
    },
    // 返回列表序号
    indexMethod(index) {
      return (this.page.pageNum - 1) * this.page.pageSize + index + 1;
    },
  },
};
</script>
<style scoped>
.table {
  margin-top: 15px;
}
.flex {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.margin-left {
  margin: 10px 0 0 10px;
}
.input {
  width: 150px;
}
/*批量导入按钮*/
.file {
  margin: 10px 0 0 10px;
  position: relative;
  background: #d0eeff;
  border: 1px solid #99d3f5;
  border-radius: 4px;
  padding: 10px 20px;
  box-sizing: border-box;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
}
.file input {
  position: absolute;
  font-size: 14px;
  width: 106px;
  height: 40px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
.file:hover {
  background: #aadffd;
  border-color: #78c3f3;
  color: #004974;
  text-decoration: none;
}
.margin0 {
  margin: 0;
}
</style>
