<template>
  <view class="containers">
    <view class="auth-header">
      <view class="auth-logo">
        <!-- <u-avatar size="100" icon="github-circle-fill" fontSize="100"></u-avatar> -->
        <image class="imgCss" src="@/static/images/empty/gas-logo.png" mode="widthFix"></image>
        <view class="welcomeTitleCss">
          欢迎登录
        </view>
        <view class="platformCss">
          市场洞察平台
        </view>
      </view>
    </view>

    <view class="auth-box">
      <u--form labelPosition="left" :model="formData" :rules="rules" ref="form">
        <u-form-item prop="username" ref="item-mobile">
          <u-input type="text" maxlength="16" border="surround" shape="circle" v-model="formData.username" clearable
            placeholder="请输入您的用户名" style="width: 610rpx;">
            <u-icon slot="prefix" size="20" style="margin-right: 48rpx;" name="/static/images/icon/user.png"></u-icon>
          </u-input>
        </u-form-item>

        <u-gap height="10"></u-gap>

        <u-form-item prop="password" ref="item-password">
          <u-input :type="inputType" prefixIcon="lock" maxlength="16" border="surround" shape="circle"
            v-model="formData.password" placeholder="请输入登录密码" style="width: 610rpx;">
            <u-icon slot="prefix" size="20" style="margin-right: 48rpx;" name="/static/images/icon/pwd.png"></u-icon>
            <template slot="suffix">
              <u-icon v-if="inputType === 'password'" size="20" color="#666666" name="eye-fill"
                @click="inputType = 'text'"></u-icon>
              <u-icon v-if="inputType === 'text'" size="20" color="#666666" name="eye-off"
                @click="inputType = 'password'"></u-icon>
            </template>
          </u-input>
        </u-form-item>

        <u-gap height="10"></u-gap>

        <u-form-item prop="code" ref="item-code">
          <u--input v-model="formData.code" placeholder="请输入验证码" shape="circle" type="text" class="input">
            <template slot="prefix">
              <img class="prefix-icon" src='/static/images/login/code.png' />
            </template>
          </u--input>
          <image :src="codeUrl" @click="getCode" class="login-code-img"></image>
        </u-form-item>
        <view class="remember-box" @click="rememberMe = !rememberMe">
          <img class="suffix-icon"
            :src="rememberMe ? '/static/images/login/remember.png' : '/static/images/login/not-remember.svg'" />
          <view class="text" :class="rememberMe ? 'remember-text' : ''">记住密码</view>
        </view>
        <view class="btn-group">
          <u-button class="auth-btn" customStyle="margin-top: 50px" @click="handleSubmit" @>登录</u-button>
        </view>
      </u--form>
    </view>
    <u-loading-page v-if="isDing" :loading="isDing" iconSize="50" loadingMode="spinner"
      image="/static/images/empty/loding-logo.gif" loadingText="检测为钉钉环境\n自动登录中..." bg-color="#e8e8e8"></u-loading-page>
  </view>
</template>

<script>
  import {passwordLogin,getCodeImg,} from '@/api/auth'
  import { encrypt, decrypt } from "@/utils/jsencrypt";
  import * as dd from 'dingtalk-jsapi'
  export default {
    data() {
      return {
        currentModeIndex: 0,
        inputType: 'password',
        codeDisabled: false,
        codeTips: '',
        formData: {
          // username: 'xucfa',
          // password: 'qkOzF!liEfd',
          username: '',
          password: '',
          code: '',
          uuid: ''
        },
        rememberMe: false,
        codeUrl: "",
        rules: {
          username: {
            type: 'string',
            required: true,
            message: '请填写用户名',
            trigger: ['blur', 'change']
          },
          password: {
            type: 'string',
            required: true,
            message: '请填写登录密码',
            trigger: ['blur', 'change']
          },
          code: {
            type: 'string',
            required: true,
            message: '请填写验证码',
            trigger: ['blur', 'change']
          },
        },
        isDing: false
      }
    },
    onLoad() {},
    onShow() {
      this.getCode();
      this.detectionEnvironment();
      this.getLocalCache()
      // console.log(this.$isDing);
      // this.isDing = true;
    },
    onReady() {
      // 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      detectionEnvironment() {
        let that = this;
        console.log(this.$isDing);
        if (this.$isDing) {
          this.isDing = true;
          dd.ready(() => {
            dd.runtime.permission.requestAuthCode({
              corpId: "dinge6053c157358448735c2f4657eb6378f",
              onSuccess: (info) => {
                that.$store.dispatch('Login', {
                  type: 2,
                  data: info.code
                }).then(res => {
                  uni.$u.toast('登录成功');
                  //获取全部字典信息 保存至store
                  that.$store.dispatch('loadDictDatas')
                  setTimeout(() => {
                    uni.switchTab({
                      url: '/pages/market/index'
                    })
                    // uni.navigateTo({
                    //   url: '/pages/market/total'
                    // })
                  }, 300)
                }).catch(err => {
                  // alert(JSON.stringify(err))
                  console.log(err);
                  // uni.$u.toast('非钉钉内部账号');
                  setTimeout(() => {
                    that.isDing = false;
                  }, 500)
                })
              },
              onFail: (err) => {
                that.isDing = false
                console.log(err);
              }
            })
          })
        }
      },
      //记住账号密码
      getLocalCache() {
        // uni.setStorageSync('roleId', roleIdString)
        const rememberMe = uni.getStorageSync('rememberMe');
        console.log("是否记住密码", Boolean(rememberMe));
        if (!rememberMe) return;
        const username = uni.getStorageSync('username')
        const password = uni.getStorageSync('password')
        console.log("密码缓存",password);
        this.formData = {
          username: username === undefined ? this.formData.username : username,
          password: password === undefined ? this.formData.password : decrypt(password),
        };
        console.log(this.formData);
        this.rememberMe = rememberMe === undefined ? false : true;
      },
      getCode() {
        getCodeImg().then(res => {
          this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
          if (this.captchaEnabled) {
            this.codeUrl = 'data:image/gif;base64,' + res.img
            this.formData.uuid = res.uuid
          }
        })
      },

      handleSubmit() {
        this.$refs.form.validate().then(res => {
          let data = this.formData
          this.mobileLogin(data)

          // uni.login({
          //   provider: 'weixin',
          //   success: res => {
          //     let data = this.formData
          //     // data.socialType = 34 //WECHAT_MINI_APP 先指定固定值
          //     // data.socialCode = res.code
          //     // data.socialState = Math.random() // 该参数没有实际意义暂时传随机数
          //     this.mobileLogin(data)
          //   },
          //   fail: res => {
          //     this.mobileLogin(this.formData)
          //   }
          // })
        })
      },
      rememberPassword() {
        if (this.rememberMe) {
          uni.setStorageSync('username', this.formData.username);
          uni.setStorageSync('password', encrypt(this.formData.password));
          uni.setStorageSync('rememberMe', this.rememberMe);
        } else {
          uni.removeStorageSync('username');
          uni.removeStorageSync('password');
          uni.removeStorageSync('rememberMe');
        }
      },
      mobileLogin(data) {
        // return
        console.log("登录信息",data);
        this.$store.dispatch('Login', {
          type: 0,
          data: data
        }).then(res => {
          uni.$u.toast('登录成功');
          //获取全部字典信息 保存至store
          this.rememberPassword()
          this.$store.dispatch('loadDictDatas')
          setTimeout(() => {
            // uni.navigateTo({
            //     url: '/pages/market/total'
            // })
            uni.navigateTo({
              url: '/pages/login/workbench'
            })
          }, 300)
        }).catch(error =>{
          if(error.data.code === 500){
            this.getCode();
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .containers {
    max-width: 375px;
    margin: 0 auto;
  }

  .auth-header {
    height: 600rpx;
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .auth-logo {
      margin: 200rpx 0 0 54rpx;

      .imgCss {
        width: 320rpx !important;
      }

      .welcomeTitleCss {
        margin-top: 80rpx;
        background-color: rgba(255, 255, 255, 0);
        box-sizing: border-box;
        font-family: '苹方 粗体', '苹方 中等', '苹方', sans-serif;
        font-weight: 700;
        color: #333333;
        text-align: left;
        line-height: normal;
        font-size: 48rpx
      }

      .platformCss {
        margin-top: 10rpx;
        background-color: rgba(255, 255, 255, 0);
        box-sizing: border-box;
        font-family: '苹方 中等', '苹方', sans-serif;
        color: #ababab;
        text-align: left;
        line-height: normal;
        font-size: 36rpx
      }
    }
  }

  .auth-box {
    @include flex-center(column);

    .mode-section {
      width: 600rpx;

      .subsection {
        height: 60rpx;
      }
    }

    .btn-group {
      width: 642rpx;

      .auth-btn {
        height: 90rpx;
        font-size: 32rpx;
        padding: 2px 2px 2px 2px;
        border-radius: 60px;
        background-color: #cf000d;
        box-sizing: border-box;
        font-family: '苹方 中等', '苹方', sans-serif;
        color: #ffffff;
        text-align: center;
        line-height: normal;
      }
    }
  }

  .remember-box {
    height: 37rpx;
    margin: 33rpx 0 42rpx 0;
    display: flex;
    align-items: center;

    img {
      width: 30rpx;
      height: 30rpx;
      margin-right: 12rpx;
    }

    .text {
      font-size: 26rpx;
      font-family: '苹方 中等', '苹方', sans-serif;
      color: #666666;
      text-align: left;
      line-height: normal;
    }

    .remember-text {
      color: #333;
    }
  }

  .login-code-img {
    width: 33%;
    height: 98rpx;
    cursor: pointer;
    vertical-align: middle;
  }

  // .u-input {
  //   height: 60rpx;
  //   background: #f5f7f7;
  // }

  /deep/.u-loading-page__warpper__text {
    text-align: center;
  }
</style>
