<template>
  <div class="binding-container">
    <el-alert title="您的微信号未绑定过系统,请先绑定一个账号" :closable="false" type="warning" center show-icon />
    <el-form label-width="80px" size="mini" style="margin-top:10px" ref="formRef" :model="formData" :rules="rules">
      <el-form-item label="用户名:" prop="id">
        <el-select
          remote 
          style="width:100%" 
          v-model="formData.id" 
          :loading="ol" 
          :filterable="true" 
          :remote-method="requestUserList"
          @change="handleChange"
          >
          <!-- Number(item.is_wx) === 1 || -->
          <el-option 
            v-for="item in accounts" 
            :key="item.value" 
            :value="item.value" 
            :disabled="Number(item.status) === 0"
            :label="item.label">
            <span style="float: left;">{{item.label}}</span>
            <span v-if="Number(item.is_wx) === 1 || Number(item.status) === 0" style="float: right;color:#F56C6C">{{Number(item.is_wx) === 1 ? '已绑定' : '已禁用'}}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="手机号:" prop="phone">
        <el-input :disabled="true" v-model="formData.phone" placeholder="手机号" />
      </el-form-item>

      <el-form-item label-width="140px" label="验证手机号后四位:" prop="lastCode">
        <el-input :disabled="!formData.id" placeholder="手机号后四位" maxlength="4" v-model="formData.lastCode" @input="handleLastValue" />
      </el-form-item>

      <el-form-item style="display: flex;justify-content: flex-end;">
        <!-- <el-button type="primary" @click="submit">绑定</el-button> -->
        <wx-open-subscribe 
          :template="template"
          id="subscribe-btn" 
          @success="handleSuccess" 
          @error="handleError" 
        >
        <script type="text/wxtag-template">
          <button>绑 定</button>
        </script>
      </wx-open-subscribe>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import asyncRequest from "@/api"
export default {
  props: ["openid","template"],
  data() {
    const validate_num = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号后四位'))
      } else if(value.length !== 4){
        callback(new Error('输入号码不足四位'))
      }else {
        callback()
      }
    }

    return {
      visible:false,
      template:"",
      ol:false,
      maxHeight: null,
      loading_wx:true,
      loading: false,
      currentAccount: {},
      formData: {
        id: "",
        phone: "",
        lastCode: ""
      },
      rules:{
        id:[{required:true,trigger:'change',message:'请选择用户'}],
        phone:[{required:true,trigger:'change',message:'请输入手机号'}],
        lastCode:[{required:true,trigger:'change',validator:validate_num}],
      }
    }
  },
  created() {
    document.title = "绑定采销账号"
  },
  beforeDestory() {
    document.title = ""
  },
  methods: {
    handleSuccess(res){
        this.submit();
    },
    handleError(){
      this.$message.warning("订阅失败，请重试!")
    },
    handleLastValue(value){
      this.formData.lastCode = value.replace(/[^\d]/g,'');
      let { lastCode = "", phone } = this.formData
      let phoneLastCode = []
      for(let i = 0;i < 4;i ++){ phoneLastCode[i] = lastCode[i] || "*" }
      const phonePreCode = phone.slice(0, 7) 
      console.log(phonePreCode)
      this.formData.phone= phonePreCode + phoneLastCode.join("");
    },
    handleChange(value) {
      const item = this.accounts.find(({ value: oV }) => oV === value)

      this.formData = {
        id: item.value,
        phone: item.mobile,
        lastCode: ""
      }
    },
    async submit(){
      try{
        await this.$refs.formRef.validate();
        const { id,lastCode } = this.formData;
        this.loading = true
        const result = await asyncRequest.bindwx({ id, lastCode, openId:this.openid })
        this.loading = false;
        if(result.code === 0){
          this.$emit("bind",result.data.token);
        }else{
          this.$message.error(result.message)
        }

      }catch(err){
        console.log(err)
      }
    },
    async requestUserList(qs) {
      this.ol = true
      const result = await asyncRequest.accountQuery({ openId: this.openid, nickname: qs })
      this.ol = false;

      const { code, data } = result;
      if (code === 0) {
        const { list } = data;
        this.accounts = list.map(({ id, nickname, mobile,is_wx,status }) => ({
          value: id,
          label: nickname,
          mobile,
          is_wx,
          status
        }))

      } else {
        this.accounts = []
      }
    },
  }
}
</script>


<style lang="scss" scoped>
.binding-container {
  display: flex;
  flex-direction: column;
  align-items:center;
  /deep/.el-form {
    width:95%;
    max-width:500px;
  }
}
</style>
