<template>
    <div id="edit-card-form-box">
        <el-dialog title="编辑会员卡" :visible.sync="editCardFormVisible" width="900px" id="edit-member-card-show" v-loading="submitLoading" :element-loading-text="loadingText">
            <el-row>
                <el-col :span="10">
                    <div class="membercard-area" :style="membercardAreaBackground">
                        <span class="ico_crown"></span>
                        <div class="card-header clearfix">
                            <h4 class="shop-name">
                                <span class="shop-logo">
                                    <img :src="orgLogo"> 
                                </span>
                                <span class="tit">{{form.card_name}}</span>
                            </h4>
                            <div class="qr-code"></div>
                        </div>
                        <h3 class="member-type"></h3>
                        <div class="card-content">
                            <p class="expiry-date">
                                有效期：
                                <span>无限期</span>
                            </p>
                        </div>
                    </div>
                </el-col>
                <el-col :span="14">
                    <el-form ref="cardForm" :rules="cardRules" :model="form" label-width="100px" id="edit-member-card-form">
                        <el-form-item label="机构Logo:" >
                            <el-upload class="org-logo" action="https://upload.qiniup.com" disabled >
                                <img v-if="orgLogo" :src="orgLogo" class="org-logo-image">
                                <i v-else class="el-icon-plus org-logo-icon"></i>
                                <div class="el-upload__tip" slot="tip">如需修改机构Logo信息，请在<em>机构中心</em>中更新。</div>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="卡片封面:" required prop="background_type">
                            <el-radio-group v-model="form.background_type">
                                <el-radio :label="bgt.id" :value="bgt.id" :key="index" v-for="(bgt, index) in backgroundTypeOptions">{{bgt.name}}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="背景色:"  prop="background_color"  v-show="form.background_type==1">
                            <el-color-picker v-model="form.background_color" @change="handleChangeColor" :predefine="predefineData"></el-color-picker>
                        </el-form-item>
                        <el-form-item label="封面图片:"  prop="background_image"  v-show="form.background_type==2">
                           <el-upload
                                v-loading="uploading"
                                :element-loading-text="loadingText"
                                class="bg-image-uploader"
                                :data="uploadData"
                                action="https://upload.qiniup.com"
                                :show-file-list="false"
                                :on-error="handleBackImageError"
                                :on-success="handleBackImageSuccess"
                                :before-upload="beforeBackImageUpload"
                            >
                                <img v-if="form.background_image" :src="form.background_image" class="bg-image">
                                <i v-else class="el-icon-plus bg-image-uploader-icon"></i>
                                <div class="el-upload__tip" slot="tip">尺寸：906*498像素，小于2M，支持jpg、png、jpeg格式</div>
                            </el-upload>
                        </el-form-item>

                        <el-form-item label="会员卡名称:" required prop="card_name" >
                            <el-input v-model="form.card_name" placeholder="最多可输入9个字符" maxlength="9"></el-input>
                        </el-form-item>
                        <el-form-item label="使用须知:"  prop="use_notice">
                            <el-input v-model="form.use_notice" type="textarea" rows='4' placeholder="会员特权会根据您上文的勾选情况系统自动生成，此处可填写其它补充信息以便会员知晓，最多可输入300个字符"  maxlength="300"></el-input>
                        </el-form-item>
                        <el-form-item label="会员权益:"  prop="card_right">
                            <el-input v-model="form.card_right" type="textarea" rows='4' placeholder="会员特权会根据您上文的勾选情况系统自动生成，此处可填写其它补充信息以便会员知晓，最多可输入300个字符"  maxlength="300"></el-input>
                        </el-form-item>
                        <el-form-item label="客服电话:"  prop="service_phone" >
                            <el-input v-model="form.service_phone" placeholder="请输入手机号或固定电话" ></el-input>
                        </el-form-item>
                        <el-form-item label="升级条件:"  prop="upgrade_integral" >
                            累积积分达到
                            <el-input v-model.number="form.upgrade_integral" style="width:100px;" placeholder="" ></el-input>
                            分
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            
            <div slot="footer" class="dialog-footer">
                <el-button @click="editCardFormVisible = false">取消</el-button>
                <el-button
                type="primary"
                @click="submitForm('cardForm')"
                >保 存
                </el-button>
            </div>
        </el-dialog>  
    </div>
</template>

<script>
import {EditMemberShipCard} from "@/api/member/member";
import { getFileExtension,checkHexColor,checkMobileOrPhone } from "@/utils/tools";
import { getToken } from "@/api/qiniu";

export default {
    name:'EditCardForm',
    props:{
        cardsData:{
            type: Array,
            default: function () {
                return [];
            }
        },
        cardIndex:{
            type:Number,
            default:-1.
        },
        form:{
            background_type:1,
            background:"#409EFF",
            background_color:"#409EFF",
            background_image:"",
            card_name:'',
            use_notice:'',
            card_right:'',
            service_phone:'',
            upgrade_integral:0,
            id:0,
        },
    },
    data(){
        var checkBgColorRule = (rule, value, callback) => {
            if (this.form.background_type == 1 && !checkHexColor(value)) {
                callback(new Error('请选择背景色'));
            }else {
               callback(); 
            }
        };
        var checkBgImageRule = (rule, value, callback) => {
            if (this.form.background_type == 2 && !value) {
                callback(new Error('请上图片封面图片'));
            }else {
               callback(); 
            }
        };
        var checkTelRule = (rule, value, callback) => {
            if (value && !checkMobileOrPhone(value)) {
                callback(new Error('请填写正确的客服电话:13888888888 或 0756-1234567'));
            }else {
               callback(); 
            }
        };
        var checkIntegralRule = (rule, value, callback) => {
            if(!value) {
                callback(); 
            }else {
                if(!Number.isInteger(value)) {
                    callback(new Error('必须是整数'));
                }else {
                    if (value<0) {
                        callback(new Error('不能小于0'));
                    }else {
                        callback(); 
                    }
                }
            }
        };
        return {
            editCardFormVisible:false,
            qiniuDomain: "https://images.shengws.com/",
            uploading:false,
            loadingText:'',
            submitLoading:false,
            uploadData: { token: "", key: "" },
            predefineData:['#65d3e3','#82cecb','#5bd18b','#58a2ec','#9675cc','#f2ca68','#ff7979','#aed15b','#75c075','#67b192','#7b8a97','#34495e','#262626'],
            backgroundTypeOptions:[
                {id:1, name:'背景色'},
                {id:2, name:'封面图片'},
            ],
            
            cardRules: {
                card_name: [{required: true, message: "请填写会员卡名称",},],
                background_color: [{ validator: checkBgColorRule}],
                background_image: [{ validator: checkBgImageRule}],
                service_phone: [{ validator: checkTelRule}],
                upgrade_integral: [{ validator:checkIntegralRule}],
            },
        }
    },
    methods:{
        open:function(){
            this.form.background_color = '';
            this.form.background_image = '';
            if (this.form.background_type == 1) {
                this.form.background_color = this.form.background;
            }else {
                this.form.background_image = this.form.background;
            }
            this.editCardFormVisible = true;
        },
        resetForm:function(formName) {
            if (typeof(this.$refs[formName]) !='undefined') {
                this.$refs[formName].resetFields();
            }
        },
        handleChangeColor:function(color){
            this.form.background = color;
        },
        handleBackImageError(err, file, fileList) {
            this.$message.error(err);
            this.uploading = false;
            return false;
        },
        handleBackImageSuccess(res, file) {
            var url = this.qiniuDomain + res.url;
            this.form.background_image = url
            this.form.background = url;
            this.uploading = false;
        },
        beforeBackImageUpload(file) {
            var fileType = file.type;
            const isJPG = fileType.indexOf("image") > -1;
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error("只能上传图片");
                return false;
            }
            if (!isLt2M) {
                this.$message.error("图片大小不能超过 2MB!");
                return false;
            }

            var date = new Date();
            var ext = getFileExtension(file.name);
            var key = "" + date.getFullYear() + (date.getMonth() + 1) + date.getDate() + date.getHours() + date.getMinutes() + date.getSeconds() + "_card_" +file.uid +"." + ext;
            this.uploading = true;
            this.loadingText = "图片上传中";

            const _self = this;
            return new Promise((resolve, reject) => {
                getToken()
                .then(response => {
                    const token = response.data.data.uptoken;
                    _self._data.uploadData.token = token;
                    _self._data.uploadData.key = key;
                    resolve(true);
                })
                .catch(err => {
                    reject(false);
                    this.uploading = false;
                });
            });
        },
        submitForm:function(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.loadingText = "正在保存...";
                    this.submitLoading = true;
                    EditMemberShipCard(this.form.id, this.form).then(response=>{
                        var res = response.data;
                        if(res.state === 1) {
                            var card = res.data.card;
                            this.cardsData.splice(this.cardIndex, 1, card);
                            this.resetForm("cardForm");
                            this.editCardFormVisible = false;
                            this.$message.success("编辑会员卡成功");
                        }else {
                            this.$message.error(res.msg);
                        }
                        this.submitLoading = false;
                    }).catch(e=>{
                        this.submitLoading = false;
                    });
                } else {
                    return false;
                }
            });
        },
    },
    computed: {
      orgLogo: function() {
        var avatar = this.$store.getters.xt_user.org.org_logo
        return avatar.length > 0
          ? avatar
          : require('../../../assets/home/userData.png')
      },
      membercardAreaBackground:function(){
          if (this.form.background_type == 1) {
              return 'background:' + this.form.background_color;
          }else {
              return 'background: url("' + this.form.background_image + '") 0% 0% / 100% 100% no-repeat;'
          }
      }
    },
}
</script>

<style rel="stylesheet/scss" >
#edit-member-card-form .org-logo .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 25px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
#edit-member-card-form .org-logo .el-upload:hover {
  border-color: #409eff;
}
#edit-member-card-form .org-logo-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

#edit-member-card-form .el-upload__tip em {
    color: #5599eb;
}

#edit-member-card-form .org-logo-image {
  width: 50px;
  height: 50px;
  display: block;
}


#edit-member-card-form .bg-image-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 10px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
#edit-member-card-form .bg-image-uploader .el-upload:hover {
  border-color: #409eff;
}
#edit-member-card-form .bg-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 278px;
  height: 130px;
  line-height: 130px;
  text-align: center;
}
#edit-member-card-form .bg-image {
  width: 278px;
  height: 130px;
  display: block;
}

#edit-member-card-show .membercard-area {
    margin: 9px;
    padding: 14px 18px 24px 17px;
    background: #5599eb;
    color: #fff;
    border-radius: 20px 20px 20px 20px;
    position: relative;
}
#edit-member-card-show  .membercard-area .ico_crown {
    position: absolute;
    right: 18px;
    width: 64px;
    height: 54px;
    background: url("https://images.shengws.com/icos-201906141103.png") no-repeat -58px -422px;
}
#edit-member-card-show .clearfix {
    clear: both;
}
#edit-member-card-show .clearfix:before {
    display: table;
    content: " ";
}
#edit-member-card-show .membercard-area .shop-name {
    font-size: 14px;
}
#edit-member-card-show .membercard-area .shop-name .shop-logo {
    display: inline-block;
    width: 40px;
    height: 40px;
    float: left;
    margin-right: 13px;
}
#edit-member-card-show .membercard-area .shop-name .shop-logo img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
}
#edit-member-card-show .membercard-area .shop-name .tit {
    height: 41px;
    line-height: 41px;
}
#edit-member-card-show  .member-type {
    height: 70px;
    line-height: 70px;
}
#edit-member-card-show .membercard-area .card-content .expiry-date {
    font-size: 12px;
}
</style>

