<template>
  <div class="app-container">
    <div v-show="step == 1">
      <div class="setting_title">开通账号</div>
      <el-divider></el-divider>
      <div class="tips">说明：开通商户账号是指开通商城后台管理系统的总登录账号。</div>

      <el-card shadow="never" class="my-card">
        <el-form class="my-form" ref="step1Form" :model="step1Form" :rules="step1FormRules" label-width="100px" label-position="right">
          <el-form-item label="商户账号" prop="account">
            <el-input v-model="step1Form.account" autocomplete="off" placeholder="请输入商户账号"></el-input>
            <el-popover
              class="question"
              placement="right-start"
              title="账号设置"
              width="260"
              trigger="hover"
              content="账号设置需按数字、字母组合设置至少12位账号">
              <svg-icon icon-class="question" slot="reference" />
            </el-popover>
          </el-form-item>
          <el-form-item label="账户昵称" prop="nickName">
            <el-input v-model="step1Form.nickName" autocomplete="off" placeholder="请输入账户昵称"></el-input>
          </el-form-item>
          <el-form-item label="小程序名称" prop="appName">
            <el-input v-model="step1Form.appName" autocomplete="off" placeholder="请输入小程序名称"></el-input>
          </el-form-item>
          <el-form-item label="负责人" prop="chargePerson">
            <el-input v-model="step1Form.chargePerson" autocomplete="off" placeholder="请输入负责人"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="step1Form.phone" autocomplete="off" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="step1Form.email" autocomplete="off" placeholder="请输入电子邮箱"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
			<div style="display:flex;">
				<el-input placeholder="请选择地址" autocomplete="off" readonly style="margin-right: 20px;" v-model="step1Form.address"></el-input>
				<geographicalPosi :formData="step1Form" @selectPosi="selectAddress"></geographicalPosi>
			</div>
          </el-form-item>
          <el-form-item label="登录密码" prop="newPassword">
            <el-input v-model="step1Form.newPassword" ref="password1" autocomplete="off" placeholder="请输入登录密码" :type="passwordType1"></el-input>
            <span class="show-pwd" @click="showPwd(1)">
              <svg-icon :icon-class="passwordType1 === 'password' ? 'eye' : 'eye-open'" />
            </span>
            <el-popover
              class="question"
              placement="right-start"
              title="密码设置"
              width="260"
              trigger="hover"
              content="密码设置需按数字、字母组合设置至少12位密码">
              <svg-icon icon-class="question" slot="reference" />
            </el-popover>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="step1Form.confirmPassword" ref="password2" autocomplete="off" placeholder="请再次输入密码" :type="passwordType2"></el-input>
            <span class="show-pwd" @click="showPwd(2)">
              <svg-icon :icon-class="passwordType2 === 'password' ? 'eye' : 'eye-open'" />
            </span>
            <el-popover
              class="question"
              placement="right-start"
              title="密码设置"
              width="260"
              trigger="hover"
              content="确认密码需要和登录密码保持一致">
              <svg-icon icon-class="question" slot="reference" />
            </el-popover>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div v-show="step == 2">
      <div class="setting_title">商城配置</div>
      <el-divider></el-divider>
      <el-form label-width="100px" label-position="right">
        <el-upload
          class="avatar-uploader"
          :action="baseURL + 'common/upload'"
          :headers="myHeaders"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :before-upload="beforeUpload">
        </el-upload>
        <el-form-item label="主logo：" prop="imgUrl">
          <div class="images">
            <div class="main-img">
              <div class="img" v-if="img1_url" @mouseover="img1_hover = true;" @mouseout="img1_hover = false;">
                <el-image ref="img1" :src="img1_url" :preview-src-list="[img1_url]" style="width: 120px; height: 120px" fit="contain"></el-image>
                <div class="mask" v-show="img1_hover">
                  <i class="el-icon-zoom-in" @click="previewImage('img1')"></i>
                  <i class="el-icon-upload2" @click="uploadImage('img1')"></i>
                </div>
              </div>
              <div class="add" v-else @click="uploadImage('img1')">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </div>
            <div class="tmp-img">
              <el-image :src="require('@/assets/template/template_1.png')" :preview-src-list="[require('@/assets/template/template_1.png')]" style="width: 120px; height: 120px; display: block" fit="contain"></el-image>
              <div class="tmp">示例图</div>
            </div>
          </div>
          <div class="tips">
            <span>建议尺寸：400*400</span>
          </div>
        </el-form-item>
        <el-form-item label="通用logo：" prop="imgUrl">
          <div class="images">
            <div class="main-img">
              <div class="img" v-if="img2_url" @mouseover="img2_hover = true;" @mouseout="img2_hover = false;">
                <el-image ref="img2" :src="img2_url" :preview-src-list="[img2_url]" style="width: 120px; height: 120px" fit="contain"></el-image>
                <div class="mask" v-show="img2_hover">
                  <i class="el-icon-zoom-in" @click="previewImage('img2')"></i>
                  <i class="el-icon-upload2" @click="uploadImage('img2')"></i>
                </div>
              </div>
              <div class="add" v-else @click="uploadImage('img2')">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </div>
            <div class="tmp-img">
              <el-image :src="require('@/assets/template/template_2.png')" :preview-src-list="[require('@/assets/template/template_2.png')]" style="width: 120px; height: 120px; display: block" fit="contain"></el-image>
              <div class="tmp">示例图</div>
            </div>
          </div>
          <div class="tips">
            <span>建议尺寸：280*60</span>
          </div>
        </el-form-item>
        <el-form-item label="头像logo：" prop="imgUrl">
          <div class="images">
            <div class="main-img">
              <div class="img" v-if="img3_url" @mouseover="img3_hover = true;" @mouseout="img3_hover = false;">
                <el-image ref="img3" :src="img3_url" :preview-src-list="[img3_url]" style="width: 120px; height: 120px" fit="contain"></el-image>
                <div class="mask" v-show="img3_hover">
                  <i class="el-icon-zoom-in" @click="previewImage('img3')"></i>
                  <i class="el-icon-upload2" @click="uploadImage('img3')"></i>
                </div>
              </div>
              <div class="add" v-else @click="uploadImage('img3')">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </div>
            <div class="tmp-img">
              <el-image :src="require('@/assets/template/template_3.png')" :preview-src-list="[require('@/assets/template/template_3.png')]" style="width: 120px; height: 120px; display: block" fit="contain"></el-image>
              <div class="tmp">示例图</div>
            </div>
          </div>
          <div class="tips">
            <span>建议尺寸：400*400</span>
          </div>
        </el-form-item>



        <!-- --------------------------- -->
        <!-- <el-form-item label="头像logo：" prop="imgUrl">
          <div class="images">
            <div class="main-img">
              <div class="img" v-if="img3_url" @mouseover="img3_hover = true;" @mouseout="img3_hover = false;">
                <el-image ref="img3" :src="img3_url" :preview-src-list="[img3_url]" style="width: 120px; height: 120px" fit="contain"></el-image>
                <div class="mask" v-show="img3_hover">
                  <i class="el-icon-zoom-in" @click="previewImage('img3')"></i>
                  <i class="el-icon-upload2" @click="uploadImage('img3')"></i>
                </div>
              </div>
              <div class="add" v-else @click="uploadImage('img3')">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </div>
          </div>
        </el-form-item> -->
        <!-- --------------------------- -->
        <!-- <el-form-item label="头像logo：" prop="imgUrl">
          <div class="images">
            <div class="main-img">
              <div class="img" v-if="img3_url" @mouseover="img3_hover = true;" @mouseout="img3_hover = false;">
                <el-image ref="img3" :src="img3_url" :preview-src-list="[img3_url]" style="width: 120px; height: 120px" fit="contain"></el-image>
                <div class="mask" v-show="img3_hover">
                  <i class="el-icon-zoom-in" @click="previewImage('img3')"></i>
                  <i class="el-icon-upload2" @click="uploadImage('img3')"></i>
                </div>
              </div>
              <div class="add" v-else @click="uploadImage('img3')">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </div>
          </div>
        </el-form-item> -->
        <!-- --------------------------- -->


      </el-form>
    </div>

    <div v-show="step == 3">
      <div class="setting_title">微信配置</div>
      <el-divider></el-divider>
      <!-- <div class="tips">说明：企微配置是指通过配置企业微信将企微用户和系统打通，实现企业微信用户信息同平台互通，聊天会话信息同步</div> -->
      <div class="tips" style="margin-top: 20px">商户名称：{{step1Form.nickName}}</div>

      <el-form class="my-form2" ref="step3Form" :model="step3Form" :rules="step3FormRules" label-width="200px" label-position="right">
        <!-- <el-card shadow="never" class="my-card">
          <div class="title">1.配置企业ID</div>
          <div class="box">指引：进入<el-link type="primary" :underline="false" href="https://element.eleme.io" target="_blank">企业微信</el-link>打开【我的企业】，将企业ID分别复制并填写到下方输入框中</div>
          <el-form-item label="企业ID" prop="enterpriseId">
            <el-input v-model="step3Form.enterpriseId" autocomplete="off" placeholder="请输入企业ID"></el-input>
          </el-form-item>
        </el-card>

        <el-card shadow="never" class="my-card">
          <div class="title">2.配置通讯录密钥（Secret）</div>
          <div class="box">进入<el-link type="primary" :underline="false" href="https://element.eleme.io" target="_blank">企业微信</el-link>打开【客户联系】-选择【客户】-展开右侧【API】。将外部联系人Secret复制并填写到下方输入框中。如果外部联系人Secret不更新，请将更新后的外部联系人Secret更新复制更新到下方输入框中。</div>
          <el-form-item label="通讯录密钥（Secret）" prop="listSecret">
            <el-input v-model="step3Form.listSecret" autocomplete="off" placeholder="请输入通讯录密钥（Secret）"></el-input>
          </el-form-item>
          <el-divider></el-divider>
          <div class="title">配置通讯录同步密钥（Secret）</div>
          <div class="box">进入<el-link type="primary" :underline="false" href="https://element.eleme.io" target="_blank">企业微信</el-link>打开【管理工具】-选择【通讯录同步】-获取通讯录同步Secret。将通讯录同步Secret复制并填写到下方输入框中。如果通讯录同步Secret不更新，请将更新后的通讯录同步Secret更新复制更新到下方输入框中。</div>
          <el-form-item label="通讯录同步密钥（Secret）" prop="listSyncSecret">
            <el-input v-model="step3Form.listSyncSecret" autocomplete="off" placeholder="请输入通讯录同步密钥（Secret）"></el-input>
          </el-form-item>
        </el-card>

        <el-card shadow="never" class="my-card">
          <div class="title">3.配置小程序</div>
          <div class="box">进入<el-link type="primary" :underline="false" href="https://element.eleme.io" target="_blank">企业微信</el-link>打开【应用管理】-选择【应用】-选择【小程序】-获取小程序AgentiD、小程序Secret。将小程序AgentiD、小程序Secret复制并填写到下方输入框中。</div>
          <el-form-item label="小程序（AgentiD）" prop="appAgentId">
            <el-input v-model="step3Form.appAgentId" autocomplete="off" placeholder="请输入小程序（AgentiD）"></el-input>
          </el-form-item>
          <el-form-item label="小程序（Secret）" prop="appSecret">
            <el-input v-model="step3Form.appSecret" autocomplete="off" placeholder="请输入小程序（Secret）"></el-input>
          </el-form-item>
        </el-card> -->

        <el-card shadow="never" class="my-card">
          <div class="title" style="margin-bottom: 20px;">1.其他基础配置</div>
          <el-form-item label="小程序appId" prop="appId">
            <el-input v-model="step3Form.appId" autocomplete="off" placeholder="请输入小程序appId"></el-input>
          </el-form-item>
          <el-form-item label="商户号Id" prop="merchantId">
            <el-input v-model="step3Form.merchantId" autocomplete="off" placeholder="请输入商户号Id"></el-input>
          </el-form-item>
          <el-form-item label="商户号Key" prop="merchantKey">
            <el-input v-model="step3Form.merchantKey" autocomplete="off" placeholder="请输入商户号Key"></el-input>
          </el-form-item>
          <el-form-item label="子appId" prop="childAppId">
            <el-input v-model="step3Form.childAppId" autocomplete="off" placeholder="请输入子appId"></el-input>
          </el-form-item>
          <el-form-item label="子密钥" prop="childKey">
            <el-input v-model="step3Form.childKey" autocomplete="off" placeholder="请输入子密钥"></el-input>
          </el-form-item>
          <el-form-item label="子商户号Id" prop="childMerchantId">
            <el-input v-model="step3Form.childMerchantId" autocomplete="off" placeholder="请输入子商户号Id"></el-input>
          </el-form-item>
          <el-form-item label="微信订阅模版" prop="templateId">
            <el-input v-model="step3Form.templateId" autocomplete="off" placeholder="请输入微信订阅模版"></el-input>
          </el-form-item>
        </el-card>
      </el-form>
    </div>

    <div class="page-footer">
      <div class="footer" :class="classObj">
        <el-button @click="changeStep(0)" v-show="step > 1">上一步</el-button>
        <el-button @click="changeStep(1)" v-show="step < 3">下一步</el-button>
        <el-button type="primary" @click="clickSubmitForm" :loading="formLoading">{{ formLoading ? '提交中 ...' : '提 交' }}</el-button>
        <el-popconfirm
          title="确定关闭吗？"
          @confirm="goBack"
          style="margin-left: 10px;"
        >
          <el-button slot="reference">关 闭</el-button>
        </el-popconfirm>
      </div>
    </div>
    
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { addAccount } from "@/api/merchant";
import geographicalPosi from '@/components/geographicalPosi/index.vue'
export default {
	components: {geographicalPosi},
  data() {
    var validateAccount = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入商户账号'));
      } else if (value.length < 12) {
        callback(new Error('账号长度至少12位'));
      } else if (/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/.test(value) == false) {
        callback(new Error('账号必须包含数字和字母'));
      } else {
        callback();
      }
    };
    var validatePass3 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入登录密码'));
      } else if (value.length < 12) {
        callback(new Error('密码长度至少12位'));
      } else if (/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/.test(value) == false) {
        callback(new Error('密码必须包含数字和字母'));
      } else {
        if (this.step1Form.confirmPassword !== '') {
          this.$refs.step1Form.validateField('confirmPassword');
        }
        callback();
      }
    };
    var validatePass4 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.step1Form.newPassword) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: {'x-token': getToken()},
      step: 1,
      step1Form: {
        account: '', // 账号
        nickName: '', // 用户名
        appName: '', // 小程序名称
        chargePerson: '', // 负责人
        phone: '', // 联系电话
        email: '', // 电子邮箱
				lat: '',
				lng: '',
        address: '', // 地址
        newPassword: '', // 登录密码
        confirmPassword: '', // 确认密码
      },
      step1FormRules: {
        account: [
          { required: true, validator: validateAccount, trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
		address: [
          { required: true, message: '请选择GPS地址', trigger: 'blur' }
        ],
        appName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        chargePerson: [
          { required: true, message: '请输入负责人', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, validator: validatePass3, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass4, trigger: 'blur' }
        ],
      },
      passwordType1: 'password',
      passwordType2: 'password',

      uploadImageType: null,
      img1_url: '',
      img1_hover: false,
      img2_url: '',
      img2_hover: false,
      img3_url: '',
      img3_hover: false,

      step3Form: {
        enterpriseId: '',
        listSecret: '',
        listSyncSecret: '',
        appAgentId: '',
        appSecret: '',
        appId: '',
        merchantId: '',
        merchantKey: '',
        childAppId: '',
        childKey: '',
        childMerchantId: '',
        templateId: '',
      },
      step3FormRules: {
        enterpriseId: [
          // { required: true, message: '请输入企业ID', trigger: 'blur' }
        ],
        listSecret: [
          // { required: true, message: '请输入通讯录密钥（Secret）', trigger: 'blur' }
        ],
        listSyncSecret: [
          // { required: true, message: '请输入通讯录同步密钥（Secret）', trigger: 'blur' }
        ],
        appAgentId: [
          // { required: true, message: '请输入小程序（AgentiD）', trigger: 'blur' }
        ],
        appSecret: [
          // { required: true, message: '请输入小程序（Secret）', trigger: 'blur' }
        ],
      },
      formLoading: false,
    }
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened
      }
    },
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
		
		selectAddress(res){
			this.step1Form.lng = res.center[0]
			this.step1Form.lat = res.center[1]
			this.step1Form.address = res.name
		},
		
    // 显示隐藏密码
    showPwd(num) {
      if(num == 1) {
        if (this.passwordType1 === 'password') {
          this.passwordType1 = ''
        } else {
          this.passwordType1 = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password1.focus()
        })
      }
      if(num == 2) {
        if (this.passwordType2 === 'password') {
          this.passwordType2 = ''
        } else {
          this.passwordType2 = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password2.focus()
        })
      }
    },

    // 下一步
    nextStep() {
      this.$refs.step1Form.validate((valid) => {
        if (valid) {
          this.step = 2;
        }
      })
    },

    uploadImage(type) {
      this.uploadImageType = type;
      document.querySelector('.avatar-uploader input').click();
    },

    // 上传图片
    uploadSuccess(res, file) {
      this[this.uploadImageType + '_url'] = res.data.url;
    },

    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ['jpg', 'jpeg', 'png'];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$errorMsg('只支持上传jpg/jpeg/png文件!');
        return false;
      }
    },

    // 预览图片
    previewImage(type) {
      this.$refs[type].showViewer = true;
    },

    // 切换步骤
    changeStep(type) {
      if(type == 1) {
        this.step ++;
      }else {
        this.step --;
      }
    },

    // 点击 提交表单
    clickSubmitForm() {
      // 验证第一步
      this.$refs.step1Form.validate((valid) => {
        if (valid) {
          // 验证第二步
          if(this.img1_url && this.img2_url && this.img3_url) {
            // 验证第三步
            this.$refs.step3Form.validate((valid) => {
              if (valid) {
                this.submitForm();
              }else {
                this.step = 3;
              }
            })
          }else {
            this.$errorMsg('请完善商城配置');
            this.step = 2;
          }
        }else {
          this.step = 1;
        }
      })
    },

    // 提交表单
    submitForm() {
      this.$refs.step3Form.validate((valid) => {
        if (valid) {
          this.formLoading = true;
          let params = {
            type: 1,
            userName: this.step1Form.account,
            nickName: this.step1Form.nickName,
            minAppName: this.step1Form.appName,
            linkName: this.step1Form.chargePerson,
            linkPhone: this.step1Form.phone,
            email: this.step1Form.email,
			lat: this.step1Form.lat,
			lng: this.step1Form.lng,
            address: this.step1Form.address,
            password: this.step1Form.confirmPassword,

            minLogo1: this.img1_url,
            minLogo2: this.img2_url,
            minLogo3: this.img3_url,

            corpId: this.step3Form.enterpriseId,
            secret2: this.step3Form.listSecret,
            secret3: this.step3Form.listSyncSecret,
            agentId1: this.step3Form.appAgentId,
            secret1: this.step3Form.appSecret,
            appId: this.step3Form.appId,
            mchId: this.step3Form.merchantId,
            mchKey: this.step3Form.merchantKey,
            subAppId: this.step3Form.childAppId,
            subSecret: this.step3Form.childKey,
            subMchId: this.step3Form.childMerchantId,
            template: this.step3Form.templateId,
          }
          addAccount(params).then(res => {
            this.$successMsg('开通成功');
            setTimeout(() => {
              this.goBack();
            }, 1500)
          }).finally(res => {
            this.formLoading = false;
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .setting_title {
    padding-left: 0;
  }
  .tips {
    font-size: 14px;
  }
  .my-card {
    margin-top: 20px;
    .box {
      background: rgb(235, 240, 249);
      padding: 10px;
      font-size: 14px;
      margin: 20px 0;
      line-height: 18px;
      ::v-deep .el-link {
        vertical-align: unset;
      }
    }
  }
  .my-form {
    width: 450px;
    margin: 0 auto;
  }
  .show-pwd {
    position: absolute;
    right: 15px;
    top: 0;
    font-size: 16px;
    cursor: pointer;
    user-select: none;
  }
  .question {
    position: absolute;
    right: -30px;
    top: 0;
    font-size: 20px;
    cursor: pointer;
    user-select: none;
  }
  .my-form2 {
    ::v-deep input {
      width: 400px;
    }
  }
  .tips {
    margin-top: 10px;
    span {
      display: inline-block;
      width: 300px;
      text-align: center;
      line-height: 32px;
      background: #ffefef;
      font-size: 14px;
      color: #f66460;
    }
  }
  .images {
    display: flex;
    flex-wrap: wrap;
    .main-img {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 120px;
      margin-right: 20px;
      .img {
        border: 1px dashed #eaeaea;
        border-radius: 5px;
        overflow: hidden;
        position: relative;
        .el-image {
          display: block;
        }
        .mask {
          position: absolute;
          left: 0;
          top: 0;
          width: 120px;
          height: 120px;
          background: rgba($color: #000000, $alpha: 0.3);
          display: flex;
          align-items: center;
          justify-content: center;
          i {
            font-size: 20px;
            color: #ffffff;
            cursor: pointer;
            margin: 0 8px;
          }
        }
      }
      .text {
        font-size: 14px;
        color: #666666;
      }
    }
    .add {
      width: 120px;
      height: 120px;
      border: 1px dashed #eaeaea;
      border-radius: 5px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      i {
        font-size: 30px;
        color: #999;
      }
    }
    .tmp-img {
      position: relative;
      .tmp {
        position: absolute;
        left: 0;
        top: 0;
        line-height: 20px;
        padding: 0 8px;
        background: #f66460;
        border-radius: 0 0 10px 0;
        font-size: 12px;
        color: #ffffff;
      }
    }
  }
</style>