<template>
    <el-drawer :title="titleMap[mode]" :append-to-body="true" v-model="visible" :size="800" destroy-on-close :close-on-click-modal="false" @closed="$emit('closed')" :with-header="false">
        <el-container class="flex-column" v-loading="loading">
            <div class="drawer-detail-main">
                <div class="drawer-detail-header">
                    <div class="drawer-detail-header-body">
                        <div class="drawer-detail-header-left">{{ titleMap[mode] }} <span class="tips"></span></div>
                        <div class="drawer-detail-header-left">
                            <el-button type="default" icon="el-icon-close" @click="visible=false"></el-button>
                        </div>
                    </div>
                </div>
            </div>
            <el-steps simple :active="stepActive" finish-status="success">
                <el-step title="基础信息"></el-step>
                <el-step title="其他信息"></el-step>
                <el-step title="角色账号"></el-step>
            </el-steps>
            <el-main>
                <el-form ref="dialogForm" :model="formData" :rules="rules" label-width="100px" label-position="top">
                    <template v-if="stepActive==1">
                        <el-form-item label="所属代理" prop="agent_id">
                            <el-input v-model="formData.agent_id" clearable placeholder="请选择代理" readonly :style="{ width: '100%' }" @click="selectUser">
                                <template #append>
                                    <el-tooltip
                                        effect="dark"
                                        content="点这里，清除选择"
                                        placement="top-start"
                                    >
                                    <div class="remove-a" @click="clearUser">清除</div>
                                    </el-tooltip>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="门店编码" prop="store_code">
                            <el-input v-model="formData.store_code" placeholder="根据编号规则自动生成" clearable :style="{ width: '100%' }">
                                <template #append><el-button @click="generateRandomNumber">生成</el-button></template>
                            </el-input>
                        </el-form-item>
                        <el-row :gutter="10">
                            <el-col :span="12">
                                <el-form-item label="门店名称" prop="truename">
                                    <el-input v-model="formData.truename" clearable placeholder="请输入门店名称"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="店长名称" prop="store_mch">
                                    <el-input v-model="formData.store_mch" clearable placeholder="请输入店长名称"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="门店类型" prop="store_type">
                                    <el-select v-model="formData.store_type" placeholder="请选择门店类型">
                                        <el-option label="洗护实体店" :value="1"></el-option>
                                        <el-option label="洗护代收店" :value="2"></el-option>
                                        <el-option label="洗护美团店" :value="3"></el-option>
                                        <el-option label="洗护抖音店" :value="4"></el-option>
                                        <el-option label="商城自提店" :value="5"></el-option>
                                        <el-option label="洗护口碑店" :value="6"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="洗衣能力" prop="wash_type">
                                    <el-radio-group v-model="formData.wash_type">
                                        <el-radio border :label="1">门店自洗</el-radio>
                                        <el-radio border :label="2">洗衣地址</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="门店地址" prop="store_address">
                            <el-input v-model="formData.store_address" clearable placeholder="请输入门店地址"></el-input>
                        </el-form-item>
                    </template>
                    
                    <template class="mt20" v-if="stepActive==2">
                        <el-form-item label="营业执照" prop="license">
                            <sc-upload accept="image/gif,image/jpeg,image/jpg,image/png" v-model="formData.license" title="大小不超过10M"></sc-upload>
                        </el-form-item>
                        <el-form-item label="门店状态" prop="store_status">
                            <el-radio-group v-model="formData.store_status">
                                <el-radio :label="1">已启用</el-radio>
                                <el-radio :label="2">已失效</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="独立财务" prop="store_order">
                            <el-radio-group v-model="formData.store_order">
                                <el-radio :label="1">关闭</el-radio>
                                <el-radio :label="2">开启</el-radio>
                            </el-radio-group>
                            <div class="el-form-item-msg">温馨提示：开启独立财务后，该门店将实施单独扣费，费用不足时无法发送短信等功能</div>
                        </el-form-item>
                        <el-form-item label="短信收费" prop="store_sms" v-if="formData.store_order==2">
                            <el-input v-model="formData.store_sms" clearable placeholder="请输入短信费用">
                                <template #append>元/条</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="快递加价" prop="store_express" v-if="formData.store_order==2">
                            <el-input v-model="formData.store_express" clearable placeholder="请输入快递溢价">
                                <template #append>元/次</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="网单收费加价（短信、快递加价失效）" prop="store_inter_order" v-if="formData.store_order==2">
                            <el-input v-model="formData.store_inter_order" clearable placeholder="请输入网单收费">
                                <template #append>元/单</template>
                            </el-input>
                            <div class="el-form-item-msg"></div>
                        </el-form-item>
                    </template>
                    <template class="mt20" v-if="stepActive==3">
                        <el-form-item label="登录账号" prop="username">
                            <el-input v-model="formData.username" clearable placeholder="请输入登录账号"></el-input>
                            <div class="el-form-item-msg">不设置登录账号可以使用手机号码登录</div>
                        </el-form-item>
                        <el-form-item prop="mobile" :label="$t('login.mobilePlaceholder')">
                            <el-input v-model="formData.mobile" clearable :placeholder="$t('login.mobilePlaceholder')">
                                <template #prepend>+86</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="yzm" :label="$t('login.smsPlaceholder')">
                            <div class="login-msg-yzm">
                                <el-input v-model="formData.yzm" clearable :placeholder="$t('login.smsPlaceholder')"></el-input>
                                <el-button @click="getYzm" :disabled="disabled">{{this.$t('login.smsGet')}}<span v-if="disabled"> ({{time}})</span></el-button>
                            </div>
                        </el-form-item>
                        <el-form-item prop="captcha" :label="$t('login.code')">
                            <div class="login-msg-yzm">
                                <el-input v-model="formData.captcha" clearable :placeholder="$t('login.codeErr')"></el-input>
                                <el-tooltip placement="top-start" :content="$t('login.codeTips')">
                                    <div class="captcha" @click="getCaptcha"><img :src="captcha.base64" /></div>
                                </el-tooltip>
                            </div>
                        </el-form-item>
                        <el-form-item label="登录密码" prop="password">
                            <el-input type="password" v-model="formData.password" clearable show-password placeholder="请输入登录密码"></el-input>
                        </el-form-item>
                        <el-form-item label="确认密码" prop="password2">
                            <el-input type="password" v-model="formData.password2" clearable show-password placeholder="请再次输入密码"></el-input>
                        </el-form-item>
                    </template>
                </el-form>
            </el-main>
            <el-footer style="text-align: right;">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="danger" :loading="isSaveing" @click="submitPre()" v-if="stepActive > 1 ">上一步</el-button>
                <el-button type="primary" :loading="isSaveing" @click="submit(stepActive)">{{ stepActive==3?'提交':'下一步' }}</el-button>
            </el-footer>
        </el-container>
    </el-drawer>
    <agentData ref="agentData" :multiple="false" @success="handleSuccess"></agentData>
</template>

<script>
import agentData from "@/views/manage/components/agent";
export default {
    components: {
        agentData
    },
    data(){
        return {
            loading: false,
            mode:"add",
            visible: false,
            titleMap:{
                add:"新增门店",
                edit:"编辑门店"
            },
            stepActive:1,
            formData:{
                license:"https://washmy.oss-cn-guangzhou.aliyuncs.com/storage/5e1a79764c588ff81d0e09ccc26d2c85c9a6425f.png", // https://washmy.oss-cn-guangzhou.aliyuncs.com/storage/5e1a79764c588ff81d0e09ccc26d2c85c9a6425f.png
            },
            time:60,
            disabled:false,
            rules:{
                store_order: [
                    {required: true, message: '请选择'}
                ],
                store_status: [
                    {required: true, message: '请选择'}
                ],
                agent_id: [
                    {required: true, message: '请选择'}
                ],
                wash_type: [
                    {required: true, message: '请选择'}
                ],
                truename: [
                    {required: true, message: '请输入门店名称'}
                ],
                store_mch: [
                    {required: true, message: '请输入店长名称'}
                ],
                store_type: [
                    {required: true, message: '请选择门店类型'}
                ],
                store_address: [
                    {required: true, message: '请输入门店地址'}
                ],
                password: [
                    {required: true, message: '请输入登录密码'}
                ],
                password2: [
                    {required: true, message: '请再次输入密码'},
                    {validator: (rule, value, callback) => {
                        if (value !== this.formData.password) {
                            callback(new Error('两次输入密码不一致!'));
                        }else{
                            callback();
                        }
                    }}
                ],
                mobile: [
                    { required: true, message: this.$t('login.mobileError'), trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const phoneReg = /^1[3-9]\d{9}$/ // 手机号正则
                            const landlineReg = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/
                            if (!value) {
                                callback(new Error('请输入联系方式'))
                            } else if (!phoneReg.test(value) && !landlineReg.test(value)) {
                                callback(new Error('请输入有效的手机号码号码'))
                            } else {
                                callback()
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                yzm: [
                    {required: true, message: this.$t('login.smsError')}
                ],
                captcha: [
                    {required: true, message: this.$t('login.codeErr')}
                ],
                license: [
                    {required: true, message: "请上传营业执照"}
                ],
            },
            captcha:{}
        }
    },
    methods: {
        open(mode = 'add'){
            this.mode = mode;
            this.visible = true;
            this.generateRandomNumber()
            if (mode == 'add') {
                this.getCaptcha();
            }
            return this
        },
        submitPre(){
            this.stepActive--
        },
        async getCaptcha(){
            var resp = await this.$API.common.captcha.get();
            if (resp.code == 0) {
                return this.$message.error(resp.msg);
            }
            this.captcha = resp.data;
        },
        async getYzm(){
			var field = ["mobile","captcha"];
			this.$refs.dialogForm.validateField(field, async (valid) => {
				if(!valid){
					return false
				}
                var resp = await this.$API.common.sms.post({"mobile":this.formData.mobile,"code":this.formData.captcha,"key":this.captcha.key,"scene":"register"});
                if (resp.code == 0) {
                    this.getCaptcha();
                    return this.$message.error(resp.msg);
                }
                this.$message.success(resp.msg)
                this.disabled = true
                this.time = 60
                var t = setInterval(() => {
                    this.time -= 1
                    if(this.time < 1){
                        clearInterval(t)
                        this.disabled = false
                        this.time = 0
                    }
                },1000)
            });            
        },
        generateRandomNumber() {
            this.formData.store_code = "DF"+Math.random().toString().slice(2, 13);
        },
        //表单注入数据
        setData(data){
            this.formData = data;
        },
        cancel(){
            this.formData = {store_system:2,store_goods:1,store_status:1};
            this.stepActive = 1;
            this.visible = false;
        },
        handleSuccess(data){
            this.formData.agent_id = data.agent_id;
        },
        clearUser(){
            this.formData.agent_id = "";
        },
        selectUser(){
            this.$nextTick(() => {
                this.$refs.agentData.open()
            })
        },
        async submit(){
            var validate = await this.$refs.dialogForm.validate().catch(()=>{});
            if(!validate){ return false }
            if (this.stepActive < 3) {
                this.stepActive++;
            } else {
                this.submitState = true;
            }
            let submitData = JSON.parse(JSON.stringify(this.formData));
            if (this.submitState) {
				submitData.password = this.$TOOL.crypto.MD5(this.formData.password)
				submitData.password2 = this.$TOOL.crypto.MD5(this.formData.password2)
				submitData.scene = "register";
                this.isSaveing = true;
                var resp = await this.$API.store.save.post(submitData);
                this.isSaveing = false;
                if (resp.code == 0) {
                    return this.$message.error(resp.msg);
                }
                this.$message.success(resp.msg);
                this.visible = false;
                this.formData = {};
                this.stepActive = 1;
                this.$emit("success");
            }
        }

    }
}
</script>

<style>

.login-msg-yzm {display: flex;width: 100%;}
.login-msg-yzm .el-button {margin-left: 10px;--el-button-size:42px;}
.login-msg-yzm .captcha{
	display: flex;
	align-items: center;
	cursor: pointer;
    border: var(--el-border);
    margin-left: 10px;
	border-radius: 2px;
}
.captcha img{
	height: 32px;
}
</style>