<template>
    <el-card shadow="never" class="aui-card--fill">
        <div class="mod-home">
            <div class="top adfac">
                <div class="back adfac" @click="handleBack">
                    <img src="@/assets/img/back.png">
                    <span>返回</span>
                </div>
            </div>
            <div class="title">新增会员</div>
            <el-form ref="dataForm" :model="dataForm" :rules="dateRules" label-width="120px" class="aui-form--labelLeft" style="margin-top: 20px;">
                <el-form-item label="添加会员" prop="addType">
                    <el-radio-group v-model="dataForm.addType">
                        <el-radio :label="1">批量导入</el-radio>
                        <el-radio :label="2">手动录入</el-radio>
                    </el-radio-group>
                </el-form-item>
                <template v-if="dataForm.addType === 1">
                    <el-form-item label="">
                        <div class="f_pldr">
                            <div class="fp_box">
                                <div class="fpb_pre">
                                    <div class="fpbp_btn" @click="handleDownloadExcel" v-if="$hasPermission('core:appuser:save')">下载Excel示例文件</div>
                                </div>
                                <img src="@/assets/img/arrow_right_two.png">
                                <div class="fpb_pre sc">
                                    <el-upload v-if="$hasPermission('core:appuser:uploadSave')"
                                        :action="uploadUrl"
                                        :headers="uploadHeaders"
                                        :on-success="uploadFileSuccess"
                                        :before-upload="beforeAvatarUpload"
                                        :limit="1">
                                        <div class="fpbp_btn">上传Excel文件</div>
                                    </el-upload>
                                </div>
                            </div>
                            <p>文件后缀名为xls或者xlsx，文件中所含列数请勿超过20列</p>
                        </div>
                    </el-form-item>
                </template>
                <template v-else-if="dataForm.addType === 2">
                    <el-form-item label="会员昵称" prop="nickName">
                        <el-input v-model="dataForm.nickName" placeholder="请输入会员昵称"></el-input>
                    </el-form-item>
                    <el-form-item label="渠道方" prop="channelId">
                        <el-select v-model="dataForm.channelId" placeholder="请选择渠道方">
                            <el-option v-for="item in channelOptions" :key="item.id" :label="item.channelName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="善行少年编号" prop="uniqueNo">
                        <el-input v-model="dataForm.uniqueNo" placeholder="根据选择渠道方自动生成编号" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="姓名" prop="realName">
                        <el-input v-model="dataForm.realName" placeholder="请输入会员姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-select v-model="dataForm.gender" placeholder="请选择性别">
                            <el-option v-for="item in genderOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="dataForm.phone" placeholder="请输入手机号码"></el-input>
                    </el-form-item>
                    <el-form-item label="身份证号" prop="idCard">
                        <el-input v-model="dataForm.idCard" placeholder="请输入身份证号"></el-input>
                    </el-form-item>
                    <el-form-item label="家庭公益名称" prop="welfareName">
                        <el-input v-model="dataForm.welfareName" placeholder="请输入家庭公益名称"></el-input>
                    </el-form-item>
                    <el-form-item label="家庭公益口号" prop="welfareSlogan">
                        <el-input v-model="dataForm.welfareSlogan" placeholder="请输入家庭公益口号"></el-input>
                    </el-form-item>
                    <el-form-item label="爱心值" prop="loveValue">
                        <el-input type="number" v-model="dataForm.loveValue" placeholder="请输入爱心值"></el-input>
                    </el-form-item>
                </template>
                <el-form-item>
                    <!-- <el-button type="primary" @click="handleUploadSave" v-if="$hasPermission('core:appuser:uploadSave')&&dataForm.addType===1">保存</el-button> -->
                    <el-button type="primary" @click="handleSubmit" v-if="$hasPermission('core:appuser:save')&&dataForm.addType===2">保存</el-button>
                    <el-button type="default" @click="handleCancel">返回</el-button>
                </el-form-item>
            </el-form>
        </div>
    </el-card>
</template>

<script>
import Cookies from 'js-cookie'
export default {
  data () {
    return {
      dataForm: {
        addType: 1,
        nickName: '',
        channelId: '',
        uniqueNo: '',
        realName: '',
        gender: '',
        phone: '',
        idCard: '',
        welfareName: '',
        welfareSlogan: '',
        loveValue: ''
      },
      dateRules: {
        addType: [
          { required: true, message: '请选择添加会员方式', trigger: 'change' }
        ],
        nickName: [
          { required: true, message: '请输入会员昵称', trigger: 'blur' }
        ],
        channelId: [
          { required: true, message: '请选择渠道方', trigger: 'change' }
        ],
        realName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
        ],
        welfareName: [
          { required: true, message: '请输入家庭公益名称', trigger: 'blur' }
        ],
        welfareSlogan: [
          { required: true, message: '请输入家庭公益口号', trigger: 'blur' }
        ],
        loveValue: [
          { required: true, message: '请输入爱心值', trigger: 'blur' }
        ]
      },
      channelOptions: [],
      genderOptions: [
        { id: 0, name: '男' },
        { id: 1, name: '女' },
        { id: 2, name: '保密' }
      ],
      // uploadUrl: `${window.SITE_CONFIG['apiURL']}/sys/oss/uploadFile`,
      uploadUrl: `${window.SITE_CONFIG['apiURL']}/core/app/user/import`,
      uploadHeaders: {
        token: Cookies.get('token')
      },
      file: ''
    }
  },
  watch: {
    'dataForm.channelId': function (val) {
      if (val) {
        this.dataForm.uniqueNo = `SXSN-PAB-${new Date().getTime()}`
      }
    }
  },
  created () {
    this.getSupplierOptions()
  },
  methods: {
    getSupplierOptions () {
      this.$http.get('/core/channel/page', { params: { page: 1, limit: -1 } }).then(res => {
        this.channelOptions = res.data.data.list.filter(item => item.type === 1) || []
      })
    },
    handleBack () {
      this.$router.push({ name: 'member-query' })
    },
    handleCancel () {
      this.handleBack()
    },
    handleDownloadExcel () {
      window.location.href = `${window.SITE_CONFIG['apiURL']}/core/app/user/download?token=${Cookies.get('token')}`
    },
    beforeAvatarUpload (file) {
      const isXls = file.type === 'application/vnd.ms-excel'
      const isXlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isXls && !isXlsx) {
        this.$message.error('上传文件只能是 xls 或 xlsx 格式!')
      }
      return isXls || isXlsx
    },
    uploadFileSuccess (response, file, fileList) {
      if (response && response.code === 0) {
        this.$message.success('会员批量导入成功！')
        this.file = response.data || ''
        this.handleBack()
      } else {
        this.$message.error(response.msg || '文件上传失败！')
      }
    },
    handleUploadSave () {
      if (!this.file) return this.$message.error('请先上传Excel文件！')
      this.$http.post('/core/app/user/import', { file: this.file }).then(({ data: res }) => {
        if (res.code !== 0) return this.$message.error(res.msg || '导入失败！')
        this.$message.success('会员批量导入成功！')
        this.handleBack()
      })
    },
    handleSubmit () {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          console.log('提交的表单数据:', this.dataForm)
          if (this.dataForm.addType === 1) {
            // ...处理批量导入的逻辑（通常在上传成功的回调里处理）
            alert('请上传文件以完成批量导入')
          } else {
            this.$http.post('/core/app/user', this.dataForm).then(({ data: res }) => {
              if (res.code === 0) {
                this.$message.success('会员新增成功！')
                this.handleBack()
              } else {
                this.$message.error(res.msg || '会员新增失败！')
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-upload-list{
  display: none;
}

.top {
    padding-bottom: 13px;
    box-shadow: inset 0px -1px 0px 0px #F0F1F7;
    .back {
        cursor: pointer;
        img {
          width: 22px;
          height: 22px;
        }
        span {
            font-family: PingFang-SC, PingFang-SC;
            font-weight: bold;
            font-size: 14px;
            color: #00AE57;
            line-height: 20px;
            margin-left: 6px;
        }
    }
    .line {
        width: 1px;
        height: 16px;
        background: #F0F1F7;
        margin-left: 14px;
    }
    .text {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 14px;
        color: #657588;
        line-height: 20px;
        margin-left: 10px;
    }
}

.title{
  font-family: PingFang-SC, PingFang-SC;
  font-weight: bold;
  font-size: 16px;
  color: #252525;
  line-height: 22px;
  margin-top: 20px;
}

.f_pldr{
    .fp_box{
        display: flex;
        width: 526px;
        height: 125px;
        border-radius: 4px;
        border: 1px solid #EDEEF0;
        position: relative;
        .fpb_pre{
            width: calc(50% - 1px);
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            .fpbp_btn{
                width: 140px;
                height: 36px;
                border-radius: 6px;
                border: 1px solid #E5E7EB;
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 12px;
                color: #00AE57;
                line-height: 32px;
                text-align: center;
                cursor: pointer;
            }
            &.sc{
                border-left: 1px solid #EDEEF0;
                .fpbp_btn{
                    background: #00AE57;
                    border: 1px solid #00AE57;
                    color: #FFFFFF;
                }
            }
        }
        img{
            width: 50px;
            height: 20px;
            position: absolute;
            left: 50%;
            margin-left: -25px;
            top: 50%;
            margin-top: -10px;
        }
    }
    p{
        margin-top: 11px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 12px;
        color: #C1C7D2;
        line-height: 20px;
        text-align: justify;
    }
}

.el-input,.el-select,.el-date-picker {
    width: 390px;
}
</style>
