<template>
  <div class="pda-login">
    <div class="login-card">
      <!-- 语言切换 -->
      <div class="lang-switch">
        <el-dropdown trigger="click">
          <span class="lang-text">
            {{ $t('home.locale') }}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="lang in languageList"
              :key="lang.languageCode"
              @click.native="switch_the_language(lang.languageCode)"
            >
              {{ lang.languageName }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>

      <div class="logo-area">
        <svg viewBox="0 0 100 80" width="90" height="72">
          <!-- 立体货架左侧 -->
          <polygon points="20,30 20,70 50,80 50,40" fill="#2B2523"/>
          <!-- 立体货架右侧 -->
          <polygon points="50,40 50,80 90,70 90,30" fill="#23201E"/>
          <!-- 立体货架顶面 -->
          <polygon points="20,30 50,20 90,30 50,40" fill="#3A3532"/>
          <!-- 横向货架层（左） -->
          <polyline points="20,40 50,48" stroke="#fff" stroke-width="2" opacity="0.7"/>
          <polyline points="20,50 50,56" stroke="#fff" stroke-width="2" opacity="0.7"/>
          <polyline points="20,60 50,64" stroke="#fff" stroke-width="2" opacity="0.7"/>
          <!-- 横向货架层（右） -->
          <polyline points="90,40 50,48" stroke="#fff" stroke-width="2" opacity="0.7"/>
          <polyline points="90,50 50,56" stroke="#fff" stroke-width="2" opacity="0.7"/>
          <polyline points="90,60 50,64" stroke="#fff" stroke-width="2" opacity="0.7"/>
          <!-- 纵向货架分隔线 -->
          <polyline points="35,25 35,75" stroke="#fff" stroke-width="2" opacity="0.5"/>
          <polyline points="65,25 65,75" stroke="#fff" stroke-width="2" opacity="0.5"/>
          <!-- #17B3A3色系货箱（在货架格子里） -->
          <rect x="53" y="44" width="8" height="6" fill="#17B3A3" rx="1" />
          <rect x="73" y="54" width="8" height="6" fill="#17B3A3" rx="1" />
          <rect x="33" y="62" width="8" height="6" fill="#17B3A3" rx="1" />
        </svg>
        <h1>{{ $t('home.pdaName') }}</h1>
      </div>

      <el-form class="login-form" @keyup.enter.native="dataFormSubmit()">
        <!-- 用户名 -->
        <div class="input-group" :class="{focus: usernameFocus}">
          <input placeholder="Username"
                 type="text"
                 v-model="dataForm.userName"
                 @focus="usernameFocus=true"
                 @blur="handleUsernameBlur"
                 required />
        </div>

        <!-- 密码 -->
        <div class="input-group" :class="{focus: passwordFocus}">
          <input placeholder="Password"
                 :type="showPassword ? 'text' : 'password'"
                 v-model="dataForm.password"
                 @focus="passwordFocus=true"
                 @blur="passwordFocus=false"
                 required />
        </div>

        <!-- 工厂下拉框（site） -->
        <el-select
          v-if="siteList.length"
          v-model="selectedSite"
          placeholder="请选择工厂"
          style="width: 100%; margin-bottom: 1.5rem"
          :popper-append-to-body="false">
          <el-option
            v-for="item in siteList"
            :key="item.siteCode"
            :label="item.siteName"
            :value="item.siteCode" />
        </el-select>

        <!-- 登录按钮 -->
        <button type="submit" class="login-btn" :disabled="loading" @click.prevent="dataFormSubmit">
          <span v-if="!loading">Login</span>
          <span v-else class="loading-dots">•••</span>
        </button>
      </el-form>
    </div>
  </div>
</template>


<script>
import {searchSysLanguage} from "@/api/sysLanguage.js"
import {getUserAuthorizedSites, getUserAuthorizedSubSiteCodes} from "@/api/factory/accessSite.js"

export default {
  data() {
    return {
      dataForm: {
        userName: '',
        password: '',
        uuid: ''
      },
      usernameFocus: false,
      passwordFocus: false,
      showPassword: false,
      loading: false,
      siteList: [],
      languageList: [],
      selectedSite: ''
    };
  },
  created() {
    this.getLanguageList();
  },
  methods: {
    // 获取多语言列表
    getLanguageList() {
      searchSysLanguage({languageCode: this.$i18n.locale}).then(({data}) => {
        this.languageList = data.rows
      })
    },
    switch_the_language(val) {
      localStorage.setItem('locale', val)
      this.$i18n.locale = val; // 修改当前语言
      location.reload()
    },
    handleUsernameBlur() {
      // 用户名输入完成后，获取该用户授权的工厂列表
      if (this.dataForm.userName && this.dataForm.userName.trim()) {
        this.getUserSiteList(this.dataForm.userName);
      } else {
        this.siteList = [];
        this.selectedSite = '';
      }
      this.usernameFocus = false;
    },
    // 根据用户名获取授权的工厂列表
    getUserSiteList(userName) {
      if (!userName || !userName.trim()) {
        this.siteList = [];
        this.selectedSite = '';
        return;
      }

      this.siteLoading = true;
      getUserAuthorizedSites({ userName: userName.trim() }).then(({data}) => {
        this.siteLoading = false;
        if (data && data.code === 0) {
          this.siteList = data.data || data.list || [];
          // 清空之前选择的工厂
          this.selectedSite = '';
          // 如果只有一个工厂，自动选中
          if (this.siteList.length === 1) {
            this.selectedSite = this.siteList[0].siteCode;
          }
        } else {
          this.siteList = [];
          this.selectedSite = '';
          this.$message.error(data.msg || '获取工厂列表失败');
        }
      }).catch(error => {
        this.siteLoading = false;
        this.siteList = [];
        this.selectedSite = '';
        console.error('获取工厂列表失败:', error);
        this.$message.error('获取工厂列表失败');
      })
    },
    // 登录后缓存用户子site编码集合，供后续页面按需使用
    cacheUserAuthorizedSubSiteCodes(userName, site) {
      if (!userName || !userName.trim() || !site) {
        this.$store.commit('user/updateSubSiteCodeList', [])
        localStorage.setItem('userSubSiteCodeList', JSON.stringify([]))
        return Promise.resolve([])
      }
      return getUserAuthorizedSubSiteCodes({ userName: userName.trim(), site: site }).then(({data}) => {
        const sourceList = (data && data.code === 0) ? (data.data || []) : []
        const subSiteCodeList = Array.from(new Set((sourceList || []).filter(item => !!item)))
        this.$store.commit('user/updateSubSiteCodeList', subSiteCodeList)
        localStorage.setItem('userSubSiteCodeList', JSON.stringify(subSiteCodeList))
        return subSiteCodeList
      }).catch(error => {
        console.error('缓存子site编码失败:', error)
        this.$store.commit('user/updateSubSiteCodeList', [])
        localStorage.setItem('userSubSiteCodeList', JSON.stringify([]))
        return []
      })
    },
    dataFormSubmit() {
      if (!this.selectedSite) {
        this.$message.error('请选择工厂');
        return;
      }
      this.loading = true;
      this.$http({
        url: this.$http.adornUrl('/sys/login'),
        method: 'post',
        data: this.$http.adornData({
          username: this.dataForm.userName,
          password: this.dataForm.password,
          uuid: this.dataForm.uuid,
          site: this.selectedSite
        })
      }).then(({ data }) => {
        this.loading = false;
        if (data && data.code === 0) {
          // 设置Cookie过期时间为8小时，与后端token同步 - rqrq
          this.$cookie.set('token', data.token, { expires: '8h' });
          localStorage.setItem('userName', this.dataForm.userName);
          localStorage.setItem('site', this.selectedSite);

          this.$store.commit('user/updateSite', this.selectedSite);
          this.cacheUserAuthorizedSubSiteCodes(this.dataForm.userName, this.selectedSite).finally(() => {
            this.$router.replace({ name: 'home' });
          })
        } else {
          this.$alert(data.msg, '错误', {
            confirmButtonText: '确定'
          });
        }
      });
    }
  }

}
</script>

<style scoped>
.pda-login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f5f5; /* 修改为与 index.vue 一致的背景色 */
  font-family: 'Segoe UI', sans-serif;
}

.login-card {
  position: relative;
  width: 90%;
  max-width: 400px;
  padding: 2rem;
  background: white;
  border-radius: 16px;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.1);
}

.lang-switch {
  position: absolute;
  top: 18px;
  right: 20px;
}

.lang-text {
  cursor: pointer;
  font-size: 14px;
  color: #17B3A3;
}

.logo-area {
  text-align: center;
  margin-bottom: 1.5rem;
}

.logo-area svg {
  width: 64px;
  height: 64px;
  filter: drop-shadow(0 2px 4px rgba(23, 179, 163, 0.3)); /* 修改阴影颜色 */
}

h1 {
  color: #333;
  font-size: 1.5rem;
  margin-top: 1rem;
}

.input-group {
  position: relative;
  margin-bottom: 1.2rem;
  border-bottom: 1px solid #ccc;
  transition: all 0.3s ease;
}

.input-group.focus {
  border-color: #17B3A3;
}

.input-group input {
  width: 100%;
  padding: 10px 0;
  border: none;
  outline: none;
  font-size: 15px;
}

.input-group.site-select {
  border: none;
  padding-top: 8px;
}

.pwd-toggle {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #17B3A3;
  font-size: 12px;
  cursor: pointer;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: #17B3A3;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  margin-top: 1.2rem;
  transition: all 0.3s;
}
.loading-dots {
  letter-spacing: 2px;
  animation: blink 1.2s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 0.2 }
  50% { opacity: 1 }
}
</style>
