<template>
  <div>
    <el-row :gutter="24">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{ __('默认搜索') }}</span>
          </div>
          <el-form>
            <el-form-item>
              <el-button @click="addRow">
                {{ __('添加行') }}
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-table border :data="list" height="350" @cell-click="tabClick">
                <el-table-column
                  align="center"
                  fixed="left"
                  :label="__('操作')"
                  width="100"
                >
                  <template slot-scope="scope">
                    <el-button type="text" @click="delRow(scope.$index)">
                      {{ __('删除') }}
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  :label="__('搜索词')"
                  prop="default_search_words"
                  width="250"
                >
                  <template slot-scope="scope">
                    <span
                      v-if="
                        scope.$index === tabClickIndex &&
                        scope.column.id === columnId
                      "
                    >
                      <el-input
                        ref="editInput"
                        v-model="scope.row.default_search_words"
                        @blur.stop="inputBlur"
                      />
                    </span>
                    <span v-else>{{ scope.row.default_search_words }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  :label="__('搜索显示词')"
                  prop="default_search_label"
                  width="300"
                >
                  <template slot-scope="scope">
                    <span
                      v-if="
                        scope.$index === tabClickIndex &&
                        scope.column.id === columnId
                      "
                    >
                      <el-input
                        ref="editInput"
                        v-model="scope.row.default_search_label"
                        @blur.stop="inputBlur"
                      />
                    </span>
                    <span v-else>{{ scope.row.default_search_label }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-form>
          <div>
            <el-button
              icon="el-icon-s-tools"
              type="primary"
              @click="saveDefault"
            >
              {{ __('修改') }}
            </el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix" style="line-height: 28px">
            <span>{{ __('热门搜索') }}</span>
          </div>
          <el-row style="line-height: 36px">
            <el-col :span="2" style="text-align: right; padding-right: 6px">
              {{ __('默认词') }}
            </el-col>
            <el-col :span="22">
              <el-tag
                v-for="tag in dynamicTags"
                :key="tag"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="saveTagInput"
                v-model="inputValue"
                class="input-new-tag"
                size="mini"
                @blur="handleInputConfirm"
                @keyup.enter.native="handleInputConfirm"
              />
              <el-button
                v-else
                class="button-new-tag"
                size="mini"
                @click="showInput"
              >
                {{ __('添加') }}
              </el-button>
            </el-col>
          </el-row>
          <el-row>
            <div style="margin-top: 20px">
              <el-button icon="el-icon-s-tools" type="primary" @click="saveHot">
                {{ __('修改') }}
              </el-button>
            </div>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { translateTitle as __ } from '@/utils/i18n'
  import { get, doEdit } from '@/api/base/config'

  export default {
    name: 'Search',
    components: {},
    data() {
      return {
        tabClickIndex: null, // 点击的行
        columnId: null, // 点击的列
        list: [],
        dynamicTags: [],
        inputVisible: false,
        inputValue: '',
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      addRow() {
        this.list.push({
          default_search_words: '',
          default_search_label: '',
        })
      },
      delRow(index) {
        this.$baseConfirm(this.__('你确定要删除选中项吗'), null, async () => {
          this.list.splice(index, 1)
        })
      },
      handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      },
      showInput() {
        this.inputVisible = true
        this.$nextTick(() => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },
      handleInputConfirm() {
        let inputValue = this.inputValue
        if (inputValue && !this.dynamicTags.includes(inputValue)) {
          this.dynamicTags.push(inputValue)
        }
        this.inputVisible = false
        this.inputValue = ''
      },
      __,
      async fetchData() {
        this.getDefault()
        this.getHot()
      },
      async getDefault() {
        const { data } = await get({ config_key: 'suggest_search_words' })
        this.handleDefaultList(data)
      },
      async getHot() {
        const { data } = await get({ config_key: 'search_hot_words' })
        this.handleHotList(data)
      },
      handleHotList(data) {
        if (data && data.config_value) {
          let value = data.config_value
          this.dynamicTags = value.split(',')
        }
      },
      handleDefaultList(data) {
        if (data && data.config_value) {
          let value = data.config_value
          this.list = JSON.parse(value)
        }
      },
      saveDefault() {
        if (this.list.length > 0) {
          this.$baseConfirm(
            this.__('修改立马生效,是否继续？'),
            null,
            async () => {
              const { msg, status } = await doEdit({ param: this.getParam() })
              if (200 == status) {
                this.$baseMessage(msg, 'success')
              } else {
                this.$baseMessage(msg, 'error')
              }
              this.fetchData()
            }
          )
        } else {
          this.$baseMessage('请选添加行数据！', 'success')
        }
      },
      saveHot() {
        if (this.list.length > 0) {
          this.$baseConfirm(
            this.__('修改立马生效,是否继续？'),
            null,
            async () => {
              const { msg, status } = await doEdit({
                param: JSON.stringify({
                  search_hot_words: this.dynamicTags.toString(),
                }),
              })
              if (200 == status) {
                this.$baseMessage(msg, 'success')
              } else {
                this.$baseMessage(msg, 'error')
              }
              this.fetchData()
            }
          )
        } else {
          this.$baseMessage('请选添加行数据！', 'success')
        }
      },
      getParam() {
        let obj = {
          suggest_search_words: this.list,
        }
        return JSON.stringify(obj)
      },
      handleEdit() {},
      tabClick(row, column) {
        this.tabClickIndex = this.list.indexOf(row)
        this.columnId = column.id
        // inout 获取焦点
        this.$nextTick(() => {
          if (!this.$refs['editInput']) return
          this.$refs['editInput'].focus()
        })
      },
      // 失去焦点初始化
      async inputBlur() {
        this.tabClickIndex = null
        this.columnId = null
      },
    },
  }
</script>
<style scoped>
  .button-new-tag {
    margin-left: 10px;
  }

  .input-new-tag {
    margin-left: 10px;
    width: 100px;
  }
</style>
