<template>
  <div class="appManagement-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">添加</el-button>
        <!-- <el-button icon="el-icon-delete" type="danger" @click="handleDelete">批量删除</el-button> -->
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-select v-model="queryForm.scene" clearable placeholder="请选择场景" @change="queryData">
              <el-option v-for="item in sceneList" :key="item.scene" :label="item.sceneName" :value="item.scene" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model.trim="queryForm.keyword" clearable placeholder="请输入查询条件" />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table v-loading="listLoading" :data="list" :element-loading-text="elementLoadingText">
      <el-table-column align="center" label="排序" prop="sort" show-overflow-tooltip />
      <el-table-column align="center" label="内容">
        <template #default="{ row }">
          <div class="content-cell">
            {{ row.content }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="场景" show-overflow-tooltip>
        <template #default="{ row }">
          {{ getSceneName(row.scene) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="使用次数" prop="useCount" show-overflow-tooltip />
      <el-table-column align="center" label="是否启用" show-overflow-tooltip>
        <template #default="{ row }">
          <el-switch active-color="#13ce66" inactive-color="#ff4949" :value="row.isEnabled" @change="handleToggleEnable(row, $event)" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button :disabled="!scope.row.isEnabled || isFirstEnabled(scope.row)" type="text" @click="handleMoveUp(scope.row)">
            上移
          </el-button>
          <el-button :disabled="!scope.row.isEnabled || isLastEnabled(scope.row)" type="text" @click="handleMoveDown(scope.row)">
            下移
          </el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit ref="edit" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { doDelete, getList, toggleEnable, doMoveUp, doMoveDown } from '@/api/spring/blessing/contentTemplate'
  import { getAll as getAllScenes } from '@/api/spring/blessing/scene'
  import Edit from './components/AppManagementEdit'

  export default {
    name: 'AppManagement',
    components: { Edit },
    data() {
      return {
        list: null,
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        elementLoadingText: '正在加载...',
        queryForm: {
          pageNo: 1,
          pageSize: 10,
          keyword: '',
          scene: '',
        },
        timeOutID: null,
        sceneList: [],
      }
    },
    created() {
      const { templateId } = this.$route.query || {}
      if (templateId) {
        this.queryForm.keyword = templateId
        this.queryForm.pageNo = 1
      }
      this.fetchSceneList()
      this.fetchData()
    },

    beforeDestroy() {
      clearTimeout(this.timeOutID)
    },
    methods: {
      setSelectRows(val) {
        this.selectRows = val
      },
      handleEdit(row) {
        if (row && row.id) {
          this.$refs['edit'].showEdit(row)
        } else {
          this.$refs['edit'].showEdit()
        }
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ ids: [row.id] })
            this.$baseMessage(msg, 'success')
            this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id).join()
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids: ids.split(',') })
              this.$baseMessage(msg, 'success')
              this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error')
            return false
          }
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const { data } = await getList(this.queryForm)
        this.list = data.list
        this.total = data.totalCount
        this.timeOutID = setTimeout(() => {
          this.listLoading = false
        }, 300)
      },
      async handleToggleEnable(row, val) {
        const prev = row.isEnabled
        row.isEnabled = val
        try {
          const { msg } = await toggleEnable(row.id, val)
          if (msg) this.$baseMessage(msg, 'success')
          this.fetchData()
        } catch (e) {
          row.isEnabled = prev
          this.$baseMessage('更新失败', 'error')
        }
      },
      async handleMoveUp(row) {
        try {
          const { msg } = await doMoveUp(row.id)
          if (msg) this.$baseMessage(msg, 'success')
          this.fetchData()
        } catch (e) {
          this.$baseMessage('操作失败', 'error')
        }
      },
      async handleMoveDown(row) {
        try {
          const { msg } = await doMoveDown(row.id)
          if (msg) this.$baseMessage(msg, 'success')
          this.fetchData()
        } catch (e) {
          this.$baseMessage('操作失败', 'error')
        }
      },
      isFirstEnabled(row) {
        if (!this.list || this.list.length === 0) return false
        const enabled = this.list.filter((item) => item.isEnabled)
        if (enabled.length === 0) return false
        return enabled[0].id === row.id
      },
      isLastEnabled(row) {
        if (!this.list || this.list.length === 0) return false
        const enabled = this.list.filter((item) => item.isEnabled)
        if (enabled.length === 0) return false
        return enabled[enabled.length - 1].id === row.id
      },
      async fetchSceneList() {
        const { data } = await getAllScenes()
        this.sceneList = data || []
      },
      getSceneName(scene) {
        const found = this.sceneList.find((item) => item.scene === scene)
        return found ? found.sceneName : scene
      },
    },
  }
</script>
