<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="参数名称" prop="sysAttrName">
        <el-input
          v-model="queryParams.sysAttrName"
          placeholder="请输入参数名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="参数键名" prop="sysAttrKey">
        <el-input
          v-model="queryParams.sysAttrKey"
          placeholder="请输入参数键名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="参数键值" prop="sysAttrValue">
        <el-input
          v-model="queryParams.sysAttrValue"
          placeholder="请输入参数键值"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button v-no-more-click type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button v-no-more-click 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 v-no-more-click
                   type="primary"
                   plain
                   icon="el-icon-plus"
                   size="mini"
                   @click="handleAdd"
                   v-hasPermi="['iscs:attribute:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-no-more-click
                   type="danger"
                   plain
                   icon="el-icon-delete"
                   size="mini"
                   :disabled="multiple"
                   @click="handleDelete"
                   v-hasPermi="['iscs:attribute:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-no-more-click
                   type="danger"
                   plain
                   icon="el-icon-refresh"
                   size="mini"
                   @click="handleRefreshCache"
                   v-hasPermi="['iscs:attribute:remove']"
        >刷新缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="List" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="参数名称"  width="210px" prop="sysAttrName">
        <template slot-scope="scope">
          <span>{{ scope.row.sysAttrName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参数键名"  prop="sysAttrKey" :show-overflow-tooltip="true"/>
      <el-table-column  label="参数类型" width="90"  prop="sysAttrType" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_type"
            :value="scope.row.sysAttrType"
          />
        </template>
      </el-table-column>
      <el-table-column label="参数键值"  prop="sysAttrValue" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <!-- 判断是否为图片 URL -->
            <div class="img-box" v-if="isImageUrl(scope.row.sysAttrValue)">
              <el-image
                style="width: 50px; height: 50px"
                :preview-teleported="true"
                class="images"
                :hide-on-click-modal="true"
                :src="scope.row.sysAttrValue"
                :zoom-rate="1.2"
                :preview-src-list="[scope.row.sysAttrValue]"
                :initial-index="1"
              >
              </el-image>
              <i class="el-icon-zoom-in" id="eyeicon"></i>
            </div>

          <!-- 否则显示文字 -->
          <div v-else>
            {{ scope.row.sysAttrValue }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="备注"  prop="remark" width="300">
        <template slot-scope="scope">
          <span>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间"  prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-no-more-click
                     size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['iscs:attribute:edit']"
          >修改
          </el-button>
          <el-button v-no-more-click
                     size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleDelete(scope.row)"
                     v-hasPermi="['iscs:attribute:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改基础数据配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="参数名称" prop="sysAttrName">
          <el-input v-model="form.sysAttrName" placeholder="请输入参数名称"/>
        </el-form-item>
        <el-form-item label="参数键名" prop="sysAttrKey">
          <el-input v-model="form.sysAttrKey" placeholder="请输入参数键名"/>
        </el-form-item>
        <el-form-item label="参数类型" prop="sysAttrType">
          <el-select
            v-model="form.sysAttrType"
            placeholder="请选择参数类型"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="键值类型" prop="sysAttrType">
          <el-radio-group v-model="inputType" @change="handleInputTypeChange">
            <el-radio label="text">文字</el-radio>
            <el-radio label="image">图片</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="参数键值" prop="sysAttrValue">
          <ImageUpload v-if="inputType === 'image'" :limit="1" :value="form.sysAttrValue" :fileSize="5" @onUploaded="handleImgUplaoded"
                       @onRemoved="handleImgRemoved"
          ></ImageUpload>
          <el-input type="textarea" :rows="4" v-else v-model="form.sysAttrValue" placeholder="请输入参数键值"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="submitForm">确 定</el-button>
        <el-button v-no-more-click @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  deleteIsSystemAttributeByIds, getIsSystemAttributeByKey,
  getIsSystemAttributePage,
  insertIsSystemAttribute,
  selectIsSystemAttributeById, updateIsSystemAttribute,refreshAttrCache
} from '@/api/system/configuration'


export default {
  name: 'autoCodeRule',
  dicts: ['sys_yes_no','sys_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      List: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        sysAttrName: '',
        sysAttrValue: '',
        sysAttrKey: ''
      },
      // 表单参数
      form: {},
      inputType: 'text', // 默认选择文字
      // 表单校验
      rules: {
        sysAttrName: [
          { required: true, message: '参数名称', trigger: 'blur' }
        ],
        sysAttrKey: [
          { required: true, message: '参数键名', trigger: 'blur' }
        ],
        sysAttrValue: [
          { required: true, message: '参数键值', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshAttrCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true
      getIsSystemAttributePage(this.queryParams).then(response => {
          this.List = response.data.records
          this.total = response.data.total
          this.loading = false
        }
      )

    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        sysAttrName: '',
        sysAttrKey: '',
        sysAttrValue: '',
        remark: ''
      }
      this.resetForm('form')
    },
    // 判断是否为图片 URL
    isImageUrl(url) {
      if (typeof url !== 'string') return false;
      return /\.(jpg|jpeg|png|gif|webp|bmp)$/i.test(url);
    },
    // 处理 radio 切换
    handleInputTypeChange(value) {
      // 切换时清空输入内容
      this.form.sysAttrValue = '';
    },
    //图片上传成功
    handleImgUplaoded(imgUrl) {
      console.log(imgUrl,'图片上传')
      this.form.sysAttrValue = imgUrl[0].url
    },
    //图片移除
    handleImgRemoved(imgUrl) {
      console.log(imgUrl)
      this.form.sysAttrValue = null
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加基础数据'
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sysAttrId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const ruleId = row.sysAttrId || this.ids
      selectIsSystemAttributeById(ruleId).then(response => {
        this.form = response.data
        // 如果拿到Value是图片 直接切换
        if(this.isImageUrl(this.form.sysAttrValue)) {
          this.inputType = 'image'
        }else{
          this.inputType = 'text'
        }
        this.open = true
        this.title = '修改基础数据'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.sysAttrId != undefined) {
            updateIsSystemAttribute(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            insertIsSystemAttribute(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row, '删除')
      debugger;
      const ruleIds = row.sysAttrId || this.ids
      this.$modal.confirm('是否确认删除所选数据项？').then(function() {
        return deleteIsSystemAttributeByIds(ruleIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    }

  }
}
</script>
<style lang="scss" scoped>
//图片放大
.img-box {
  width: 50px;
  height: 50px;
  position: relative;

  #eyeicon {
    display: none;
  }
}

.img-box:hover {
  background: #000;

  .images {
    opacity: 0.6;
  }

  #eyeicon {
    display: block;
    position: absolute;
    top: 40%;
    left: 30%;
    z-index: 100;
    color: white;
    pointer-events: none;
  }
}
</style>
