<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :inline="true"
      :model="queryParams"
      label-width="68px"
    >
      <el-form-item label="属性值" prop="attributeValue">
        <el-input
          v-model="queryParams.attributeValue"
          clearable
          placeholder="请输入属性值"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-search"
          size="mini"
          type="primary"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-popover
          content="大屏地址KEY：bigScreenUrl、系统logoKEY：logoUrl、系统名称KEY：logoTitle"
          placement="bottom"
          title="预设属性KEY"
          trigger="click"
          width="200">
          <el-button slot="reference" size="mini" style="margin-left: 10px" type="info">预设配置</el-button>
        </el-popover>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:attribute:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:attribute:remove']"
          :disabled="multiple"
          icon="el-icon-delete"
          plain
          size="mini"
          type="danger"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="attributeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="50" />
      <el-table-column
        align="center"
        label="属性KEY"
        prop="enterpriseAttribute"
      />
      <el-table-column align="center" label="属性值" prop="attributeValue" />
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:attribute:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            v-hasPermi="['system:attribute:remove']"
            icon="el-icon-delete"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改企业属性对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body class="eldialog-wrap" width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="属性KEY" prop="enterpriseAttribute">
          <el-input v-model="form.enterpriseAttribute" :disabled="form.recordId != null" placeholder="请输入属性KEY" />
        </el-form-item>
        <el-form-item label="属性值" prop="attributeValue">
          <el-input v-model="form.attributeValue" clearable placeholder="请输入属性值" />
        </el-form-item>
        <el-form-item label="选择图片" >
          <el-upload
            :before-upload="beforeRemove"
            :http-request="upload"
            :show-file-list="false"
            action=""
            class="upload-demo"
            multiple>
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传图片文件，且不超过2M</div>
          </el-upload>
        </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>
  </div>
</template>

<script>
import {
  listAttribute,
  getAttribute,
  delAttribute,
  addAttribute,
  updateAttribute,
  exportAttribute,
} from "@/api/system/attribute";
import { uploadFile } from "@/api/file";

export default {
  name: "Attribute",
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业属性表格数据
      attributeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recordId: null,
        recordStatus: null,
        attributeValue: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        enterpriseAttribute: [
          { required: true, message: "属性KEY不能为空", trigger: "change" },
        ],
        attributeValue: [
          { required: true, message: "属性值不能为空", trigger: "change" },
        ]
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询企业属性列表 */
    getList() {
      this.loading = true;
      listAttribute(this.queryParams).then((response) => {
        this.attributeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    beforeRemove(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
        return false;
      }else if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }else{
        return true;
      }
    },
    upload(file) {
      console.log("upload",file)
      let formData = new FormData();
      formData.append("file", file.file);
      uploadFile(formData).then(response => {
        if (response.code === 200) {
          this.form.attributeValue = response.url;
        }
      }).catch(e => {
        console.log(e)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        recordStatus: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        enterpriseAttribute: null,
        attributeValue: null,
        tenantId: 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.recordId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业属性";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const enterpriseAttribute = row.recordId || this.ids;
      getAttribute(enterpriseAttribute).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改企业属性";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.recordId != null) {
            updateAttribute(this.form).then((response) => {
              if (response.msg === 'ok') {
                this.$store.dispatch("SetAttributeByKey", {
                  [this.form.enterpriseAttribute]: this.form.attributeValue
                })
                this.msgSuccess("修改成功");
                this.open = false;
              } else {
                this.msgError(response.msg);
              }
              this.getList();
            });
          } else {
            addAttribute(this.form).then((response) => {
              if (response.msg === 'ok') {
                this.$store.dispatch("SetAttributeByKey", {
                  [this.form.enterpriseAttribute]: this.form.attributeValue
                })
                this.msgSuccess("修改成功");
                this.open = false;
              } else {
                this.msgError(response.msg);
              }
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const enterpriseAttributes = row.recordId || this.ids;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delAttribute(enterpriseAttributes);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有企业属性数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportAttribute(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
