<template>
  <div class="app-container">
    <!-- 查询表单区域 -->
    <el-form :model="listQuery" size="small" :inline="true" label-position="top">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="会员姓名">
            <el-input v-model="listQuery.customerName" placeholder="请输入会员姓名" style="width: 100%" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="性别">
            <el-select v-model="listQuery.sex" clearable placeholder="请选择性别" style="width: 100%">
              <el-option :key="item.type" v-for="item in sexList" :label="item.name" :value="item.type">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="注册渠道">
            <el-select v-model="listQuery.registerChannel" clearable filterable placeholder="请选择注册渠道" style="width: 100%">
              <el-option :key="item.dictLabel" v-for="item in register_channel" :label="item.dictLabel" :value="item.dictLabel">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="会员等级">
            <el-select v-model="listQuery.customerLevel" clearable filterable placeholder="请选择会员等级" style="width: 100%">
              <el-option :key="item.id" v-for="item in customer_level" :label="item.level" :value="item.level">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="状态">
            <el-select v-model="listQuery.status" clearable placeholder="请选择状态" style="width: 100%">
              <el-option :key="item.type" v-for="item in statusList" :label="item.name" :value="item.type">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="搜索">
            <el-button style="width: 100%;" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="重置">
            <el-button style="width: 100%;" icon="el-icon-refresh" type="primary" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" class="editButton" size="small" icon="el-icon-plus" @click="handleCreate">添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="small" @click="handleDownload">导出</el-button>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <div class="border-card">
      <el-table height="450" size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>
        <el-table-column type="index" label="序号" header-align="center" align="center" width="55"></el-table-column>
        <el-table-column align="center" min-width="80px" label="会员编号" prop="customerCode"></el-table-column>
        <el-table-column align="center" min-width="100px" label="会员姓名" prop="customerName"></el-table-column>
        <el-table-column align="center" min-width="80px" label="性别" prop="sexStr"></el-table-column>
        <el-table-column align="center" min-width="100px" label="注册渠道" prop="registerChannel"></el-table-column>
        <el-table-column align="center" min-width="100px" label="会员生日" prop="customerBirthday"></el-table-column>
        <el-table-column align="center" min-width="100px" label="会员等级" prop="customerLevel"></el-table-column>
        <el-table-column align="center" min-width="80px" label="状态">
          <template slot-scope="props">
            <span v-if="props.row.status == 0" style="color: #67C23A;font-weight: bold;">启用</span>
            <span v-if="props.row.status == 1" style="color: #E6A23C;font-weight: bold;">停用</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="240px" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" class="editText" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.status == 1" type="text" icon="el-icon-success" class="openText" size="small" @click="changeState(scope.row.id, scope.row.status)">启用</el-button>
            <el-button v-if="scope.row.status == 0" type="text" icon="el-icon-circle-close" class="closeText" size="small" @click="changeState(scope.row.id, scope.row.status)">停用</el-button>
            <el-button type="text" icon="el-icon-delete" class="deleteText" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="listQuery.page" :page-sizes="[10, 20, 30, 50]" :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="40%">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="110px">
        <el-form-item label="会员编号" prop="customerCode">
          <el-input v-model="dataForm.customerCode" placeholder="请输入会员编号"></el-input>
        </el-form-item>
        <el-form-item label="会员名称" prop="customerName">
          <el-input v-model="dataForm.customerName" placeholder="请输入会员名称"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="dataForm.sex">
            <el-radio :key="item.type" v-for="item in sexList" :label="item.type">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="注册渠道" prop="registerChannel">
          <el-select v-model="dataForm.registerChannel" filterable placeholder="请选择注册渠道" style="width: 100%">
            <el-option :key="item.dictLabel" v-for="item in register_channel" :label="item.dictLabel" :value="item.dictLabel">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员生日" prop="customerBirthday">
          <el-date-picker style="width: 100%;" v-model="dataForm.customerBirthday" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>     
        <el-form-item label="会员等级" prop="customerLevel">
          <el-input v-model="dataForm.customerLevel" placeholder="请输入会员等级"></el-input>
        </el-form-item>
        <el-form-item label="积分余额" prop="pointsBalance">
          <el-input v-model="dataForm.pointsBalance" placeholder="请输入积分余额" onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入备注" v-model="dataForm.remarks"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { listVip, createVip, updateVip, deleteVip, setState, vipLevel } from '@/api/vip'
import { dataTypeList } from '@/api/public'
import waves from '@/directive/waves' // 水波纹指令

export default {
  directives: { waves },
  data() {
    return {
      register_channel: [],
      customer_level: [],
      list: [],
      total: undefined,
      listLoading: true,
      sexList: [
        {
          type: '0',
          name: '男'
        },
        {
          type: '1',
          name: '女'
        }
      ],
      statusList: [
        {
          type: 0,
          name: '启用'
        },
        {
          type: 1,
          name: '停用'
        }
      ],
      listQuery: {
        page: 1,
        limit: 10,
        customerName: undefined,
        sex: undefined,
        registerChannel: undefined,
        customerLevel: undefined,
        status: undefined
      },
      dataForm: {
        customerCode: undefined,
        customerName: undefined,
        sex: undefined,
        registerChannel: undefined,
        customerBirthday: undefined,
        customerLevel: undefined,
        pointsBalance: undefined,
        remarks: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑会员',
        create: '添加会员'
      },
      rules: {
        customerCode: [
          { required: true, message: '会员编号不能为空', trigger: 'blur' }
          // { min: 14, max: 14, message: "会员编号必须为14位", trigger: "blur" },
          // { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{14,}$/, message: "会员编号必须为14位字母加数字", trigger: "blur" }
        ],
        customerName: [{ required: true, message: '会员姓名不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getDictType()
    this.getList()
  },
  methods: {
    getDictType() {
      // 注册渠道
      dataTypeList({ dictType: 'register_channel' }).then(response => {
        this.register_channel = response.data.data
      })
      // 会员等级
      vipLevel().then(response => {
        this.customer_level = response.data.data
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.listQuery = {
        page: 1,
        limit: 10,
        customerName: undefined,
        sex: undefined,
        registerChannel: undefined,
        customerLevel: undefined,
        status: undefined
      }
      this.handleQuery()
    },
    getList() {
      this.listLoading = true
      listVip(this.listQuery).then(response => {
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleQuery() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        customerCode: undefined,
        customerName: undefined,
        sex: undefined,
        registerChannel: undefined,
        customerBirthday: undefined,
        customerLevel: undefined,
        pointsBalance: undefined,
        remarks: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createVip(this.dataForm).then(response => {
            this.list.unshift(response.data.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateVip(this.dataForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.dataForm.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteVip({ id: row.id }).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {

      })
    },
    handleDownload() {
      window.location.href = process.env.BASE_API + '/customer-vip/export'
    },
    changeState(id, status) {
      setState({ id: id, status: status }).then(response => {
        this.$notify({
          title: '成功',
          message: '状态修改成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    }
  }
}
</script>