<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.search" placeholder="优惠券标题" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <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="标题" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="面额" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.amount }} {{ row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.expiry }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发放类型" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ issueTypeLabel(row.issue_type) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="适用范围" min-width="180px">
        <template slot-scope="{row}">
          <span>{{ renderScope(row) }}</span>
        </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="标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="面额" prop="amount">
          <el-input v-model="temp.amount" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="temp.unit" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="temp.desc" />
        </el-form-item>
        <el-form-item label="过期时间" prop="expiry">
          <el-date-picker v-model="temp.expiry" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="发放类型" prop="issue_type">
          <el-select v-model="temp.issue_type" class="filter-item" placeholder="请选择">
            <el-option v-for="item in issueTypeOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用项目" prop="applicable_projects">
          <el-select v-model="temp.applicable_projects" multiple filterable placeholder="请选择项目" style="width: 300px;">
            <el-option v-for="p in projectOptions" :key="p.id" :label="p.title" :value="p.id" />
          </el-select>
        </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 { getCoupons, createCoupon, updateCoupon, deleteCoupon, getProjects } from '@/api/crm'
import Pagination from '@/components/Pagination'

export default {
  name: 'CouponTable',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        available: 'success',
        claimed: 'info',
        used: 'gray',
        expired: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        search: undefined
      },
      statusOptions: [
        { key: 'available', label: '可领取' },
        { key: 'claimed', label: '已领取' },
        { key: 'used', label: '已使用' },
        { key: 'expired', label: '已过期' }
      ],
      issueTypeOptions: [
        { key: 'manual', label: '手动发放' },
        { key: 'registration', label: '注册赠送' },
        { key: 'project', label: '指定项目' }
      ],
      temp: {
        id: undefined,
        title: '',
        amount: '',
        unit: '元',
        desc: '',
        expiry: '',
        status: 'available',
        issue_type: 'manual',
        applicable_projects: [],
        color: 'from-blue-500 to-cyan-400',
        bgStart: 'from-blue-50',
        bgEnd: 'to-cyan-50',
        shadow: 'shadow-blue-100'
      },
      projectOptions: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        expiry: [{ required: true, message: '请选择过期时间', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
    getProjects({ page: 1, limit: 100 }).then(res => { this.projectOptions = res.data.results })
  },
  methods: {
    issueTypeLabel(key) {
      const m = { manual: '手动发放', registration: '注册赠送', project: '指定项目' }
      return m[key] || key
    },
    renderScope(row) {
      const ids = row.applicable_projects || []
      if (!ids.length) return '通用'
      const map = new Map(this.projectOptions.map(p => [p.id, p.title]))
      return ids.map(id => map.get(id) || `#${id}`).join('，')
    },
    getList() {
      this.listLoading = true
      getCoupons(this.listQuery).then(response => {
        this.list = response.data.results
        this.total = response.data.count
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        amount: '',
        unit: '元',
        desc: '',
        expiry: '',
        status: 'available',
        issue_type: 'manual',
        applicable_projects: [],
        color: 'from-blue-500 to-cyan-400',
        bgStart: 'from-blue-50',
        bgEnd: 'to-cyan-50',
        shadow: 'shadow-blue-100'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createCoupon(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)
          updateCoupon(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(() => {
          deleteCoupon(row.id).then(() => {
            this.$notify({
              title: 'Success',
              message: 'Delete Successfully',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
        })
    }
  }
}
</script>
