<template>
  <el-dialog
    title="新建会员档案"
    :visible.sync="visible"
    width="500px"
    :close-on-click-modal="false"
    class="member-create-dialog"
    @close="handleClose"
  >
    <el-form
      ref="memberForm"
      :model="memberForm"
      :rules="memberRules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="会员名称" prop="khmc" required>
        <el-input
          v-model="memberForm.khmc"
          placeholder="请输入会员名称"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="手机号" prop="sjh" required>
        <el-input
          v-model="memberForm.sjh"
          placeholder="请输入手机号"
          clearable
          maxlength="11"
        />
      </el-form-item>
      
      <!-- <el-form-item label="客户类型" prop="khlx" required>
        <el-select v-model="memberForm.khlx" placeholder="请选择客户类型" style="width: 100%">
          <el-option label="会员" value="会员" />
          <el-option label="非会员" value="非会员" />
        </el-select>
      </el-form-item> -->
      
      <el-form-item label="客户来源" prop="jdqd" required>
        <el-select 
          v-model="memberForm.jdqd" 
          placeholder="请选择客户来源" 
          style="width: 100%"
          @change="handleSourceChange"
        >
          <el-option label="嘉宾" value="嘉宾" />
          <el-option label="自然到店" value="自然到店" />
          <el-option label="会员推广" value="会员推广" />
          <el-option label="网络推广" value="网络推广" />
        </el-select>
      </el-form-item>
      
      <el-form-item 
        v-if="memberForm.jdqd === '嘉宾'" 
        label="推荐人" 
        prop="tjr" 
        :required="memberForm.jdqd === '嘉宾'"
      >
        <el-select 
          v-model="memberForm.tjr" 
          placeholder="请选择推荐人" 
          style="width: 100%"
          filterable
          clearable
        >
          <el-option 
            v-for="item in referrerOptions" 
            :key="item.id" 
            :label="item.fullName" 
            :value="item.id" 
          />
        </el-select>
      </el-form-item>
    </el-form>
    
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'MemberCreateDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      memberForm: {
        khmc: '',
        sjh: '',
        khlx: '老客',
        jdqd: '嘉宾',
        tjr: ''
      },
      memberRules: {
        khmc: [
          { required: true, message: '请输入会员名称', trigger: 'blur' }
        ],
        sjh: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        ],
        khlx: [
          { required: true, message: '请选择客户类型', trigger: 'change' }
        ],
        jdqd: [
          { required: true, message: '请选择客户来源', trigger: 'change' }
        ],
        tjr: [
          { 
            validator: (rule, value, callback) => {
              if (this.memberForm.jdqd === '嘉宾' && !value) {
                callback(new Error('选择嘉宾时必须选择推荐人'))
              } else {
                callback()
              }
            }, 
            trigger: 'change' 
          }
        ]
      },
      referrerOptions: []
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.resetForm()
        this.loadReferrerOptions()
      }
    }
  },
  methods: {
    // 重置表单
    resetForm() {
      this.memberForm = {
        khmc: '',
        sjh: '',
        khlx: '老客',
        jdqd: '嘉宾',
        tjr: ''
      }
      this.$nextTick(() => {
        if (this.$refs.memberForm) {
          this.$refs.memberForm.clearValidate()
        }
      })
    },
    
    // 处理客户来源变化
    handleSourceChange(value) {
      if (value !== '嘉宾') {
        this.memberForm.tjr = ''
      }
    },
    
    // 加载推荐人选项
    async loadReferrerOptions() {
      try {
        const response = await request({
          url: '/api/Extend/LqKhxx?page=1&pageSize=1000',
          method: 'GET'
        })
        
        if (response.code === 200 && response.data.list.length > 0) {
          this.referrerOptions = response.data.list.map(item => ({
            id: item.id,
            fullName: item.khmc
          }))
        } else {
          this.referrerOptions = []
        }
      } catch (error) {
        console.error('加载推荐人选项失败:', error)
        this.referrerOptions = []
      }
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.memberForm.validate((valid) => {
        if (valid) {
          this.createMember()
        }
      })
    },
    
    // 创建会员
    async createMember() {
      this.loading = true
      
      try {
        const response = await request({
          url: '/api/Extend/LqKhxx',
          method: 'POST',
          data: this.memberForm
        })
        
        if (response.code === 200) {
          this.$message.success('会员建档成功！')
          this.$emit('success', response.data)
          this.handleClose()
        } else {
          this.$message.error(`建档失败：${response.msg || '未知错误'}`)
        }
      } catch (error) {
        console.error('建档失败:', error)
        this.$message.error('网络错误，请检查连接后重试')
      } finally {
        this.loading = false
      }
    },
    
    // 关闭弹窗
    handleClose() {
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style lang="scss" scoped>
.member-create-dialog {
  .el-dialog {
    border-radius: 8px;
  }
  
  .el-form-item {
    margin-bottom: 20px;
  }
  
  .el-form-item__label {
    font-weight: 500;
    color: #303133;
  }
  
  .el-input__inner,
  .el-select .el-input__inner {
    height: 36px;
    line-height: 36px;
  }
  
  .dialog-footer {
    text-align: right;
    padding: 20px 0 0 0;
  }
  
  .el-button {
    padding: 8px 20px;
    border-radius: 4px;
  }
  
  .el-button--primary {
    background-color: #409EFF;
    border-color: #409EFF;
  }
}
</style>
