<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="门店编码" prop="storeCode">
        <el-input
          v-model="queryParams.storeCode"
          placeholder="请输入门店编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入门店名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图片识别类型" prop="identifyType">
        <el-select
          v-model="queryParams.identifyType"
          clearable
          placeholder="请选择图片识别类型"
          style="width: 203px">
          <el-option
            v-for="item in identifyTypeOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue">
          </el-option>
        </el-select>
      </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="['sfa:whitelist: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="['sfa:whitelist: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:whitelist: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:whitelist:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
        >导入</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="whitelistList">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="公司" align="center" prop="gsName" show-overflow-tooltip />
      <el-table-column label="大区" align="center" prop="dqName" show-overflow-tooltip />
      <el-table-column label="销售部" align="center" prop="deptName" show-overflow-tooltip />
      <el-table-column label="门店编码" align="center" prop="storeCode" />
      <el-table-column label="门店名称" align="center" prop="storeName" show-overflow-tooltip />
<!--      <el-table-column label="门店类型" align="center" prop="storeCategory" />-->
      <el-table-column label="图片识别类型" align="center" prop="identifyTypeStr" />
      <el-table-column label="添加时间" align="center" prop="createTime" width="170" />
      <el-table-column label="添加人" align="center" prop="createBy" />
      <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="['sfa:whitelist:edit']"-->
<!--          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sfa:whitelist: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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="门店编码" prop="storeCode">
          <el-input v-model="form.storeCode" placeholder="请输入门店编码" />
        </el-form-item>
        <el-form-item label="图片识别类型" prop="identifyType">
          <el-select v-model="form.identifyType" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in identifyTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue">
            </el-option>
          </el-select>
        </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-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"
        :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" :disabled="upload.isUploading"
        >确 定</el-button
        >
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWhitelist, getWhitelist, delWhitelist, addWhitelist, updateWhitelist,importPhotoWhitelist } from "@/api/sfa/whitelist";
import { getToken } from '@/utils/auth';
export default {
  name: "Whitelist",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 图片识别白名单表格数据
      whitelistList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeCode: null,
        identifyType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      identifyTypeOptions:[],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/upload',
        loadProgress: 10,
      },
    };
  },
  created() {
    this.getDicts('photo_identify_type').then((response) => {
      this.identifyTypeOptions = response.data;
    });
    this.getList();
  },
  methods: {
    /** 查询图片识别白名单列表 */
    getList() {
      this.loading = true;
      listWhitelist(this.queryParams).then(response => {
        this.whitelistList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        photoWhitelistId: null,
        storeCode: null,
        identifyType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {};
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.photoWhitelistId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加图片识别白名单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const photoWhitelistId = row.photoWhitelistId || this.ids
      getWhitelist(photoWhitelistId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改图片识别白名单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.photoWhitelistId != null) {
            updateWhitelist(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWhitelist(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const photoWhitelistIds = row.photoWhitelistId || this.ids;
      this.$modal.confirm('是否确认删除所选中的数据项？').then(function() {
        return delWhitelist({photoWhitelistId:photoWhitelistIds});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sfa/whitelist/export', {
        ...this.queryParams
      }, `whitelist_${new Date().getTime()}.xlsx`)
    },
    handleImport() {
      this.upload.title = '白名单门店导入';
      this.upload.open = true;
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.upladLoading = this.$loading({
        lock: true,
        text: '拼命上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      let that = this;
      if(response.code==200){
        let data = {
          url:  response.fileName
        }
        importPhotoWhitelist(data).then(res => {
          this.upload.open = false;
          this.upload.isUploading = false;
          this.upladLoading.close();
          this.$refs.upload.clearFiles();
          this.$alert(res.data.error, "导入结果", { dangerouslyUseHTMLString: true });
          this.getList();
        })
      }else{
        this.upload.open = false;
        this.upload.isUploading = false;
        this.upladLoading.close();
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      }
    },
    /** 下载模板操作 */
    importTemplate() {
      let url = process.env.VUE_APP_Target + '/profile/upload/template/图片识别白名单导入模版.xlsx'
      window.open(url, '_blank')
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
