<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片URL" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.image }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联项目" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ getProjectName(row.project) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="跳转链接" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.link }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sort_order }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.is_active ? 'success' : 'info'">
            {{ row.is_active ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="图片URL" prop="image">
          <el-input v-model="temp.image" />
        </el-form-item>
        <el-form-item label="关联项目" prop="project">
          <el-select v-model="temp.project" filterable clearable placeholder="请选择关联项目">
            <el-option
              v-for="item in projectOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跳转链接" prop="link">
          <el-input v-model="temp.link" placeholder="可选，如果选择了项目则优先跳转项目" />
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input v-model.number="temp.sort_order" />
        </el-form-item>
        <el-form-item label="启用" prop="is_active">
          <el-switch v-model="temp.is_active" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBanners, createBanner, updateBanner, deleteBanner, getProjects } from '@/api/crm'
import Pagination from '@/components/Pagination'

export default {
  name: 'BannerTable',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      projectOptions: [],
      temp: {
        id: undefined,
        image: '',
        project: undefined,
        link: '',
        sort_order: 0,
        is_active: true
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        image: [{ required: true, message: '请输入图片URL', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getProjectList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getBanners(this.listQuery).then(response => {
        this.list = response.data.results
        this.total = response.data.count
        this.listLoading = false
      })
    },
    getProjectList() {
      getProjects({ limit: 100 }).then(response => {
        this.projectOptions = response.data.results
      })
    },
    getProjectName(id) {
      if (!id) return ''
      const project = this.projectOptions.find(v => v.id === id)
      return project ? project.title : id
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        image: '',
        project: undefined,
        link: '',
        sort_order: 0,
        is_active: true
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createBanner(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateBanner(tempData.id, tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteBanner(row.id).then(() => {
            this.$notify({
              title: 'Success',
              message: 'Delete Successfully',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
        })
    }
  }
}
</script>
