<template>
  <BaseContainer>
    <NavBar title="申请成为讲师" />
    <view class="apply-lecturer">
      <view class="tit" v-if="Verify_Status == 'N'">请先实名认证，认证通过后即可继续申请</view>
      <view class="form">
        <view class="item">
          <view class="item-hd"><text>*</text>姓名</view>
          <input v-model.trim="formData.merchant_name" :disabled="applyStatus === 1" type="text" placeholder="请输入姓名"
            class="item-bd" />
        </view>
        <view class="item">
          <view class="item-hd"><text>*</text>身份证号</view>
          <input v-model.trim="formData.card_id" :disabled="applyStatus === 1" type="text" placeholder="请输入身份证号"
            class="item-bd" />
        </view>
        <view v-if="Verify_Status != 'N' && VerifyLoding">
          
        <view class="item">
          <view class="item-hd"><text>*</text>手机</view>
          <input v-model="formData.link_tel" :disabled="applyStatus === 1" type="tel" placeholder="请输入手机号"
            class="item-bd" />
        </view>
        <view class="tip">注：成为讲师后可使用该手机号用短信登录讲师后台</view>
        <view v-if="applyStatus !== 1" class="item">
          <view class="item-hd"><text>*</text>验证码</view>
          <input v-model="formData.code" type="number" placeholder="请输入验证码" class="item-bd" />
          <view :disabled="!!count" class="code-btn" type="button" @click="getCode">
            {{ count ? "重新获取(" + count + "s)" : "获取验证码" }}
          </view>
        </view>
        <view class="item">
          <view class="item-hd"><text>*</text>头像</view>
          <view class="item-bd">
            <view v-if="formData.merchant_head" class="img-wrap">
              <i v-if="formData.merchant_head && applyStatus !== 1" class="iconfont iconcha3"
                @click="deleteImage('merchant_head')"></i>
              <image mode="aspectFit" v-if="formData.merchant_head" :src="formData.merchant_head" />
            </view>
            <view v-else class="upload" @click="upload('merchant_head')"> </view>
          </view>
        </view>
        <view class="item">
          <view class="item-hd">
            <text>*</text>领域<i class="iconfont iconzhuyi-copy" @click.prevent="viewAlert"></i>
          </view>
          <input v-model.trim="view" :disabled="applyStatus === 1" type="text" placeholder="请填写" class="item-bd" />
        </view>
        <view class="item" v-if="type_address == false && kuaishou == false" @click="showPicker">
          <view class="item-hd" ><text>*</text>地区</view>
            <input  :disabled="true"  :value="addressPx ? formData.province + formData.city + formData.district : '请选择'" type="text"
            placeholder="请选择" class="item-bd" readonly  />
            <i class="iconfont icondidian"></i>
        </view>
        <view class="item" v-if="type_address == true && kuaishou == false">
          <view class="item-hd"><text>*</text>地区</view>
            <AddressPicker ref="picker" style="width: 440rpx;" @change="handleAddressPicker" />
            <i class="iconfont icondidian"></i>
        </view>
        <view class="item" v-if="type_address == false && kuaishou == true">
          <view class="item-hd"><text>*</text>地区</view>
            <AddressPicker ref="picker" style="width: 440rpx;" @change="handleAddressPicker" />
            <i class="iconfont icondidian"></i>
        </view>
        <view class="item">
          <view class="item-hd"><text>*</text>地址</view>
          <input v-model.trim="formData.address" :disabled="applyStatus === 1" type="text" placeholder="请输入详细地址"
            class="item-bd" />
        </view>
        <view class="item">
          <view class="item-hd"><text>*</text>简介</view>
          <input v-model.trim="formData.explain" :disabled="applyStatus === 1" type="text" placeholder="最多20个字"
            maxlength="20" class="item-bd" />
        </view>
        <view class="intro-item">
          <view class="item-hd">
            <view class="item-hd-lt"><text>*</text>介绍</view>
          </view>
          <textarea v-model="formData.introduction" auto-height :maxlength="2000" :disabled="applyStatus === 1"
            placeholder="请填写讲师介绍" class="item-bd intro"></textarea>
        </view>
        <view v-if="!(applyStatus === 1 && !formData.charter.length)" class="honor-item">
          <view class="item-hd">
            <view>请上传所获得的荣誉证书及相关资质证书</view>
            <view class="tip">(图片格式支持JPG、PNG、JPEG，最多上传4张)</view>
          </view>
          <view class="item-bd">
            <view v-for="item in formData.charter" :key="item" class="img-wrap">
              <i v-if="applyStatus !== 1" class="iconfont iconcha3" @click="deleteImage('charter', item)"></i>
              <image mode="aspectFit" :src="item" />
            </view>
            <view v-if="formData.charter.length < 4 && applyStatus !== 1" class="upload"
              @click="upload('charter', $event)">
            </view>
          </view>
        </view>
      </view>

        <view v-if="applyStatus !== 1" class="agree-item flex flex-center-x">
          <i :class="[agree ? 'iconxuanzhong1' : 'iconweixuanzhong', 'iconfont2']" @click="agree = !agree"></i>
          已阅读并同意
          <view class="agree-btn" @click="agreeVisible = true">《{{ title }}》</view>
        </view>

        <view class="btn flex flex-center" @click="Verify()" v-if="Verify_Status == 'N'">
          实名认证
        </view>
        <view v-if="applyStatus !== 1 && Verify_Status != 'N'" class="btn flex flex-center" @click="submitApply">
          提交申请
        </view>
    
      </view>
      <view :class="{ mask: agreeVisible }"></view>
 
      <!-- 协议弹窗 -->
      <view :class="{ show: agreeVisible }" class="agree-dialog">
        <view class="title">{{ title }}</view>
        <view class="content">
          <mp-html class="section" 
          :content="content"></mp-html>
        </view>
        <!-- <view class="content"><img class="empty" src="{__WAP_PATH}zsff/images/empty.png"></view> -->
        <button class="ok" type="button" @click="(agreeVisible = false), (agree = true)">
          我同意
        </button>

        <button class="no" type="button" @click="(agreeVisible = false), (agree = false)">
          不同意
        </button>
        <i class="iconfont iconcha3" @click="agreeVisible = false"></i>
      </view>
      <!-- 申请讲师状态 -->
      <ApplyDialog :show.sync="applyVisible" :status="applyStatus" :thetype="entry_type"  />
      <AddressPicker ref="picker" v-if="type_address == false && kuaishou == false" @change="handleAddressPicker" />

    </view>
  </BaseContainer>
</template>

<script>
import {
  getApplyData,
  getMerchantApplyStatus,
  getMerchantProtocolInfo,
  saveApply,
  getVerify,
  getdelVerify
} from "@/api/merchant";
import { getAuthCode } from "@/api/user";
import AddressPicker from "@/components/AddressPicker/index.vue";
import ApplyDialog from "@/components/ApplyDialog/index.vue";
import mpHtml from "mp-html/dist/uni-app/components/mp-html/mp-html.vue";

const COUNT = 60;

export default {
  components: {
    AddressPicker,
    ApplyDialog,
    mpHtml
  },
  data() {
    return {
      entry_type:0,
      type_address:false,
      VerifyLoding:false,
      kuaishou:false,
      addressPx:"",
      formData: {
        merchant_name: "",
        link_tel: "",
        code: "",
        merchant_head: "",
        province: "",
        city: "",
        district: "",
        address: "",
        explain: "",
        introduction: "",
        charter: [],
        card_id: ''
      },
      view: "",
      show: false,
      ready: false,
      count: 0,
      agree: false,
      agreeVisible: false,
      applyStatus: null,
      applyVisible: false,
      title: "",
      content: "",
      uid: 0,
      Verify_Status: "T"
    };
  },
  created() {
    this.getBaseInfo();
    this.is_apply();
    
  },
  onShow() {
   // #ifdef MP-TOUTIAO
   this.type_address = true
   this.VerifyLoding = true
   // #endif
   // #ifdef MP-KUAISHOU
   this.kuaishou = true
   this.VerifyLoding = true
   // #endif
   // #ifdef MP-WEIXIN
   this.VerifyLoding = true
   // #endif
   // #ifdef APP-PLUS
   this.is_verify();
   // #endif
   // #ifdef H5
   let target = navigator.userAgent.toLowerCase();
   let isWeixin = /micromessenger/.test(target);
   if (!isWeixin) {
	 this.is_verify();
   }
   // #endif
  },
  methods: {
    handleAddressPicker({ detail }) {

      let [{ value: province }, { value: city }, district = {}] = detail.value;
      if (district && district.value) district = district.value;
      this.addressPx = province+city+district
      console.log(this.addressPx)
      Object.assign(this.formData, {
        province,
        city,
        district,
      });

    },
    showPicker() {
      if (this.applyStatus == 1) return;
      this.$refs.picker.show();
    },
    // 上传图片
    async upload(name) {
      const { tempFilePaths } = await this.$util.wrapFn(uni.chooseImage, {
        count: 1,
        extension: ["png", "jpg", "jpeg"],
      });
      const path = tempFilePaths[0];

      uni.showLoading({
        mask: true,
      });
      try {
        const result = await this.$util.uploadImg(path);

        if (typeof this.formData[name] === "string") {
          this.formData[name] = result;
        } else {
          this.formData[name].push(result);
        }

        uni.hideLoading();
      } catch (err) {
        uni.hideLoading();
        this.$util.showMsg(err.msg || err);
      }
    },
    // 删除图片
    deleteImage(name, url) {
      if (typeof this.formData[name] === "string") {
        this.formData[name] = "";
      } else if (Array.isArray(this.formData[name])) {
        this.formData[name].splice(this.formData[name].indexOf(url), 1);
      }
    },
    // 提交申请
    async submitApply() {
      if (!this.formData.merchant_name) {
        return this.$util.showMsg("请输入姓名");
      }
      if (!this.formData.card_id) {
        return this.$util.showMsg("请输入身份证号");
      }
      if (!this.formData.link_tel) {
        return this.$util.showMsg("请输入手机号");
      }
      if (!/^1[3456789]\d{9}$/.test(this.formData.link_tel)) {
        return this.$util.showMsg("请输入正确的手机号");
      }
      if (!this.formData.code) {
        return this.$util.showMsg("请输入验证码");
      }
      if (!this.formData.merchant_head) {
        return this.$util.showMsg("请上传头像");
      }
      if (!this.view) {
        return this.$util.showMsg("请填写标签");
      }
      let view = this.view.split(this.view.indexOf("，") === -1 ? "," : "，");
      let viewLen = view.length;
      if (viewLen > 3) {
        return this.$util.showMsg("可添加1-3个领域");
      }
      for (let i = 0; i < viewLen; i++) {
        if (!view[i].length || view[i].length > 6) {
          return this.$util.showMsg("每个标签1-6个字");
        }
      }
      if (!this.formData.province) {
        return this.$util.showMsg("请选择地址");
      }
      if (!this.formData.explain) {
        return this.$util.showMsg("请输入讲师说明");
      }
      if (!this.formData.introduction) {
        return this.$util.showMsg("请填写讲师介绍");
      }
      if (!this.agree) {
        return this.$util.showMsg("请勾选讲师入驻协议");
      }
      this.formData.view = view;

      uni.showLoading({ mask: true });

      try {
        const { data } = await saveApply(this.formData);
        uni.hideLoading();
        this.applyVisible = true;
        this.applyStatus = 0;
      } catch (err) {
        uni.hideLoading();
        this.$util.showMsg(err.msg);
      }
    },
    getBaseInfo() {
      getMerchantProtocolInfo({type:1}).then(({ data }) => {
        const { content, title ,uid } = data;
        Object.assign(this, {
          content,
          title,
          uid
        });
      });
    },
    // 申请状态
    is_apply() {
      getMerchantApplyStatus().then(({ data }) => {
        if (data) {
          this.applyStatus = data.status;
          this.entry_type = data.entry_type
          if (data.status === 2) {
            this.ready = true;
          } else {
            this.apply_data();
          }
        } else {
          this.ready = true;
        }
      });
    },
    is_verify() {
      getVerify().then(res => {
        this.Verify_Status = res.data.status == 'F' ? 'N' : res.data.status;
        this.formData.merchant_name = res.data.cert_name
        this.formData.card_id = res.data.cert_no
        this.VerifyLoding = true
        if (res.data.status == "T") {
          this.delVerify('T');
          return this.$util.showMsg("认证成功");
        }
      })
    },
    delVerify(type) {
      var data = { type: type };
      getdelVerify(data).then(res => { })
    },
    // 申请数据
    apply_data() {
      getApplyData().then(({ data }) => {
        this.formData = data;
        this.formData.province = data.province
        this.formData.city = data.city
        this.formData.district = data.district
        this.addressPx = data.province+data.city+data.district
        this.view =  data.label ? data.label.join() : '';
        this.ready = true;
      });
    },
    // 添加领域规则弹窗
    viewAlert() {
      uni.showModal({
        title: "提示",
        content:
          "格式：领域一,领域二\n领域之间用逗号分隔\n每个领域1-6个字\n可添加1-3个领域",
        showCancel: false,
      });
    },
    Verify() {
      if (!this.formData.merchant_name) {
        return this.$util.showMsg("请输入姓名");
      }
      if (!this.formData.card_id) {
        return this.$util.showMsg("请输入身份证号");
      }
      if (!this.agree) {
        return this.$util.showMsg("请勾选讲师入驻协议");
      }
      // #ifdef MP-WEIXIN 
      var type = 5;
      // #endif
      // #ifdef APP-PLUS
      var url = `https://demo.zhishi.tczxkj.com/wap/merchant/apply_verify?uid=${this.uid}&cert_name=${this.formData.merchant_name}&cert_no=${this.formData.card_id}&type=1`
      let platform = uni.getSystemInfoSync().platform;
      if(platform == "android"){
        plus.runtime.openURL(url)  
      }else{
          plus.runtime.openURL(encodeURI(url))
      }
      // #endif
      // #ifdef H5
      var url = `https://demo.zhishi.tczxkj.com/wap/merchant/apply_verify?uid=${this.uid}&cert_name=${this.formData.merchant_name}&cert_no=${this.formData.card_id}&type=4`
      window.location.href = url
      // #endif
      // #ifdef MP-KUAISHOU
      var type = 3;
      // #endif
      // #ifdef MP-TOUTIAO
      var type = 2;
      // #endif

    },
    // 获取验证码
    async getCode() {
      let timer;
      if (!this.formData.link_tel) {
        return this.$util.showMsg("请输入手机号");
      }
      if (!/^1[3456789]\d{9}$/.test(this.formData.link_tel)) {
        return this.$util.showMsg("请输入正确的手机号");
      }
      timer = setInterval(() => {
        this.count--;
        if (!this.count) {
          clearInterval(timer);
          timer = null;
        }
      }, 1e3);
      this.count = COUNT;

      uni.showLoading({ mask: true });

      try {
        const { msg } = await getAuthCode(this.formData.link_tel);
        uni.hideLoading();
        this.$util.showMsg(msg);
      } catch (err) {
        if (timer) {
          clearInterval(timer);
          timer = null;
          this.count = 0;
        }
        this.$util.showMsg(err.msg);
      }
    },
  },
};
</script>

<style>
page{
  background: linear-gradient(60deg, #bde2f7 0%, #F7F8F9 100%);

}
</style>
<style scoped lang="scss">
.tip {
  padding-left: 22rpx;
  font-size: 20rpx;
  color: #e93323;
}

input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
}

/* 申请成为讲师 */
.apply-lecturer {
  padding: 50rpx 30rpx 50rpx;
}

.apply-lecturer .form {
  padding: 10rpx 50rpx 40rpx;
  border-radius: 24rpx;
  background-color: #ffffff;
}

.apply-lecturer .item {
  display: flex;
  align-items: center;
  padding: 40rpx 0 24rpx;
  border-top: 1px solid #e9e9e9;
}

.apply-lecturer .item:first-child {
  border-top: 0;
}

.apply-lecturer .item .item-hd {
  width: 137rpx;
  font-size: 28rpx;
  line-height: 40rpx;
  color: #282828;
  display: flex;

}

.apply-lecturer .item .item-bd {
  flex: 1;
  min-width: 0;
  font-size: 28rpx;
  line-height: 40rpx;
  color: #282828;
}

.intro {
  min-height: 4em;
}

.apply-lecturer input::placeholder {
  color: #cccccc;
}

.apply-lecturer .item .item-hd text {
  margin: 0 8rpx 0 5rpx;
  font-weight: 600;
  color: #e93323;
}

.apply-lecturer .item .item-hd .iconfont {
  margin-left: 6rpx;
  font-size: 24rpx;
  color: #ff6b00;
  cursor: pointer;
}

.apply-lecturer .item .item-bd {
  flex: 1;
  font-size: 28rpx;
  line-height: 40rpx;
  color: #282828;
}

.apply-lecturer input::placeholder {
  color: #cccccc;
}

.apply-lecturer .icondidian {
  font-size: 38rpx;
  line-height: 40rpx;
  color: #2c8eff;
}

.apply-lecturer .upload {
  position: relative;
  display: inline-block;
  width: 120rpx;
  height: 120rpx;
  background-color: #f7f7f7;
  vertical-align: middle;
}

.apply-lecturer .upload::before {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 1;
  width: 37rpx;
  height: 3rpx;
  background-color: #d8d8d8;

  transform: translate(-50%, -50%);
}

.apply-lecturer .upload::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 1;
  width: 3rpx;
  height: 37rpx;
  background-color: #d8d8d8;

  transform: translate(-50%, -50%);
}

.apply-lecturer .intro-item {
  padding: 40rpx 0;
  border-top: 1px solid #e9e9e9;
}

.apply-lecturer .intro-item .item-hd {
  display: flex;

  align-items: flex-end;
}

.apply-lecturer .intro-item .item-hd-lt {
  flex: 1;
  font-size: 28rpx;
  line-height: 40rpx;
  color: #282828;
}

.apply-lecturer .intro-item .item-hd-lt text {
  margin: 0 8rpx 0 5rpx;
  font-weight: 600;
  color: #e93323;
}

.apply-lecturer .intro-item .item-hd-rt {
  font-size: 24rpx;
  color: #666666;
}

.apply-lecturer .intro-item .item-bd {
  width: 100%;
  padding: 19rpx;
  border-radius: 10rpx;
  margin-top: 20rpx;
  background-color: #f5f5f5;
  font-size: 24rpx;
  line-height: 33rpx;
  color: #282828;
  resize: none;
}

.apply-lecturer textarea::placeholder {
  color: #999999;
}

.apply-lecturer .honor-item {
  padding: 40rpx 15rpx 0;
  border-top: 1px solid #e9e9e9;
}

.apply-lecturer .honor-item .item-hd {
  font-size: 28rpx;
  color: #666666;
}

.apply-lecturer .honor-item .tip {
  margin-top: 9rpx;
  font-size: 22rpx;
  line-height: 30rpx;
  color: #999999;
}

.apply-lecturer .honor-item .item-bd {
  margin: 50rpx -22rpx -30rpx 0;
  font-size: 0;
}

.apply-lecturer .img-wrap {
  position: relative;
  display: inline-block;
  width: 120rpx;
  height: 120rpx;
  margin: 0 22rpx 30rpx 0;
  vertical-align: middle;
}

.apply-lecturer .img-wrap:only-child {
  margin: 0;
}

.apply-lecturer .img-wrap image {
  width: 100%;
  height: 100%;
}

.apply-lecturer .img-wrap .iconfont {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 3;

  transform: translate(50%, -50%);
  font-size: 33rpx;
  color: #c5c5c5;
  cursor: pointer;
}

.apply-lecturer .btn {
  width: 100%;
  height: 86rpx;
  border-radius: 43rpx;
  margin-top: 40rpx;
  background-color: #2c8eff;
  font-size: 32rpx;
  color: #ffffff;
}

.apply-lecturer .honor-item .upload {
  margin-bottom: 30rpx;
}

.apply-lecturer .agree-item {
  padding-top: 30rpx;
  font-size: 24rpx;
  line-height: 33rpx;
  color: #999999;
}

.apply-lecturer .agree-item .iconfont2 {
  margin-right: 12rpx;
  vertical-align: middle;
  font-size: 30rpx;
  color: #c3c3c3;
  cursor: pointer;
}

.apply-lecturer .agree-item .iconxuanzhong1 {
  color: #2c8eff;
}

.apply-lecturer .agree-btn {
  color: #2c8eff;
}

.apply-lecturer .code-btn {
  font-size: 28rpx;
  color: #2c8eff;
}

.apply-lecturer .code-btn:disabled {
  color: #999999;
}

.apply-lecturer .agree-dialog {
  position: fixed;
  top: 50%;
  right: 47rpx;
  left: 47rpx;
  z-index: 56;
  display: none;

  flex-direction: column;
  max-height: 90%;
  padding: 48rpx 52rpx 35rpx;
  border-radius: 24rpx;
  background-color: #ffffff;

  transform: translateY(-50%);
  opacity: 0;
}

.apply-lecturer .agree-dialog.show {
  display: flex;
  opacity: 1;
}

.apply-lecturer .agree-dialog .title {
  text-align: center;
  font-weight: 600;
  font-size: 32rpx;
  line-height: 45rpx;
  color: #282828;
}

.apply-lecturer .agree-dialog .content {
  flex: 1;
  overflow-x: hidden;
  overflow-y: auto;
  font-size: 30rpx;
  color: #333333;
}

.apply-lecturer .agree-dialog .content * {
  white-space: pre-wrap;
}

.apply-lecturer .agree-dialog .empty {
  display: block;
  width: 414rpx;
  margin: 0 auto;
}

.apply-lecturer .agree-dialog .ok {
  flex-shrink: 0;
  width: 100%;
  height: 86rpx;
  border-radius: 43rpx;
  background-color: #2c8eff;
  font-size: 30rpx;
  line-height: 44px;
  color: #ffffff;
}

.apply-lecturer .agree-dialog .no {
  flex-shrink: 0;
  margin-top: 25rpx;
  font-size: 30rpx;
  line-height: 42rpx;
  color: #666666;
}

.apply-lecturer .agree-dialog .iconfont {
  position: absolute;
  top: 15rpx;
  right: 15rpx;
  font-size: 43rpx;
  line-height: 1;
  color: #cccccc;
  cursor: pointer;
}
.tit{
  color: #f00;
    font-size: 14px;
}
</style>
