<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :fullscreen="false" width="60%" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="memberForm" label-well-code="right" label-width="100px">
      <div class="form-div">
        <div class="form-left">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model.trim="memberForm.name" :disabled="isDetailMode" type="text" placeholder="必填"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-select v-model="memberForm.sex" :disabled="isDetailMode" placeholder="请选择性别">
                  <el-option
                    v-for="item in sexList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="手机号" prop="tel">
                <el-input v-model.trim="memberForm.tel" :disabled="isDetailMode" type="text" placeholder="必填"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生日" prop="birth">
                <el-date-picker
                  v-model.trim="memberForm.birth"
                  :disabled="isDetailMode"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择生日"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>
    <div v-show="isDetailMode" class="score-div">
      <normal-table :data="scoreList" :head="tableOption.head" :query="listQuery" :total="total" :list-loading="listLoading">
        <template slot="columns">
          <el-table-column label="积分类型" prop="type" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.type=='1'">新增积分</el-tag>
              <el-tag v-else type="danger">使用积分</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="积分数" prop="score" align="center"/>
          <el-table-column label="剩余积分" prop="remain" align="center"/>
          <el-table-column label="内容" prop="content" align="center"/>
          <el-table-column label="时间" prop="ts" align="center"/>
        </template>
      </normal-table>
    </div>
    <div v-show="!isDetailMode" slot="footer" class="dialog-footer">
      <el-button :disabled="!canEdit" type="primary" @click="saveData">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addMember, updateMember } from '@/api/biz/member'
import { getDictByType } from '@/api/common'

export default {
  name: 'EditMember',
  data() {
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update,detail
      memberForm: {
        id: '', // id
        name: '', // 姓名
        sex: '', // 性别
        tel: '', // 手机号
        birth: '', // 生日
        notes: '' // 备注
      }, // 表单
      textMap: {
        update: '编辑',
        create: '新增',
        detail: '详情'
      }, // 表头显示标题
      scoreList: [], // 积分记录
      sexList: [], // 性别列表
      typeList: [],
      postList: [], // 岗位
      jobList: [], // 作业内容
      rules: {
        name: [{ required: true, message: '姓名不能为空', trigger: ['blur', 'change'] }],
        sex: [{ required: true, message: '性别不能为空', trigger: ['blur', 'change'] }],
        tel: [{ required: true, message: '手机号不能为空', trigger: ['blur', 'change'] }],
        birth: [{ required: true, message: '生日不能为空', trigger: ['blur', 'change'] }]
      }, // 前端校验规则
      isEditMode: false, // 编辑模式
      isDetailMode: false, // 详情模式
      canEdit: true,
      tableOption: {
        head: {
          show: true, // 是否需要标题栏，
          text: '积分记录列表' // 标题名称
        },
        options: {
          needIndex: true // 是否需要序号列
        },
        toolsOption: {
          selectColumns: false, // 是否需要筛选列
          refresh: false // 是否需要刷新按钮
        }
      }, // 表格属性
      listQuery: {
        keywords: '', // 关键字
        isClassification: '1',
        position: '', // 位置
        offset: 1,
        limit: 20,
        sort: '',
        order: 'desc'
      }, // 筛选条件
      total: 0, // 数据总数
      listLoading: false // 列表loading
    }
  },
  mounted() {
    this.fetchSexList()
  },
  methods: {
    /**
     * 初始化对话框
     * @param dialogStatus 对话框类型
     * @param dialogFormVisible 对话框是否可见
     * @param row 内容参数（编辑和详情需要）
     */
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.resetForm()
        this.isEditMode = false
        this.isDetailMode = false
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.memberForm = {
          id: row.id, // id
          name: row.name, // 姓名
          sex: row.sex, // 性别
          tel: row.tel, // 手机号
          birth: row.birth, // 生日
          notes: row.notes // 备注
        }
        this.canEdit = true
        this.isEditMode = true
        this.isDetailMode = false
      } else {
        this.memberForm = {
          id: row.id, // id
          name: row.name, // 姓名
          sex: row.sex, // 性别
          tel: row.tel, // 手机号
          birth: row.birth, // 生日
          notes: row.notes // 备注
        }
        this.fetchScoreList()
        this.isEditMode = true
        this.isDetailMode = true
      }
    },
    // 重置表单
    resetForm() {
      this.memberForm = {
        id: '', // id
        name: '', // 姓名
        sex: '', // 性别
        tel: '', // 手机号
        birth: '', // 生日
        notes: '' // 备注
      }
    },
    // 保存数据
    saveData: function() {
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      this.canEdit = false
      this.$refs['dataForm'].validate((valid) => {
        console.log(this.memberForm)
        if (valid) {
          addMember(this.memberForm).then(response => {
            if (response.code === 200) {
              this.$confirm('新增成功，是否继续新增?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.resetForm()
                this.$nextTick(() => {
                  this.$refs['dataForm'].clearValidate()
                  this.canEdit = true
                })
              }).catch(() => {
                this.$emit('watchChild')
                this.dialogFormVisible = false
                this.canEdit = true
              })
            }
          }).catch((e) => {
            this.canEdit = true
          })
        } else {
          this.canEdit = true
        }
      })
    },
    // 修改数据
    updateData: function() {
      this.canEdit = false
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateMember(this.memberForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.$emit('watchChild')
              this.dialogFormVisible = false
              this.canEdit = true
            }
          }).catch((e) => {
            this.canEdit = true
          })
        }
      })
    },
    // 获取性别列表
    fetchSexList() {
      getDictByType('sex').then(response => {
        if (response.code === 200) {
          this.sexList = response.data
        }
      })
    },
    // 获取积分记录
    fetchScoreList() {
      this.listLoading = true
      this.scoreList = [
        { type: '1', score: 100, remain: 100, content: '积分+100', ts: '2021-05-07 12:00:00' },
        { type: '1', score: 100, remain: 200, content: '积分+100', ts: '2021-05-07 13:00:00' },
        { type: '1', score: 100, remain: 300, content: '积分+100', ts: '2021-05-07 14:00:00' },
        { type: '2', score: 300, remain: 0, content: '兑换-300', ts: '2021-05-07 15:00:00' },
        { type: '1', score: 100, remain: 100, content: '积分+100', ts: '2021-05-07 16:00:00' },
        { type: '1', score: 100, remain: 200, content: '积分+100', ts: '2021-05-07 17:00:00' }
      ]
      this.listLoading = false
    },
    // 取消
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-select{
    width: 100%;
  }
  .el-date-editor{
    width: 100%;
  }
  .form-div{
    width:100%;
    height:100%;
    display:flex;
    justify-content: space-between;
  }
  .form-left{
    flex:1;
    height:100%;
  }
  .score-div{
    .table-container{
      border-top:1px solid #ebebeb !important;
      .pagination-container{
        padding-bottom: 10px !important;
      }
    }
  }
</style>
