<template>
  <div class="main">
    <div class="login">
      <div class="title">Login</div>
      <div class="logeType">
        <div class="item">用户名登录</div>
      </div>
      <div class="logFrom">
        <div class="item">
          <el-input v-model="userform.userName" :prefix-icon="User" clearable placeholder="请输入用户名" style="height: 40px"
            type="text" @input="userform.password = ''" />
        </div>
        <div class="item">
          <el-input v-model="userform.password" :prefix-icon="Lock" clearable placeholder="请输入密码" show-password
            style="height: 40px" type="password" @keyup.enter.native="login" />
        </div>
        <div class="item" style="margin-top: 30px">
          <el-button :prefix-icon="Promotion" style="width: 100%" type="danger" @click="login">
            登录
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { inject, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from "@/store/app.js";
import { storeToRefs } from 'pinia';
import { encrypt, cryptoDecrypt, generateSalt } from "../../utils/AES-Pkcs7";
import Cookies from 'js-cookie'

const router = useRouter()
const CreateData = inject('CreateData')
const ExecDatabase = inject('ExecDatabase')
const store = useAppStore();
// storeToRefs 响应式解构赋值 pinia
const { user, isLoading } = storeToRefs(store);

const opNameList = reactive([])
const userform = reactive({
  userName: '',
  password: '',
  opName: ''
})

onMounted(() => {
  getOpName()
})


// const login = () => {
//   console.log(user)
//   let cost = generateSalt().slice(-16)
//   var param = []
//   param[0] = ['userName', userform.userName]
//   param[1] = ['password', encrypt(userform.password, cost)]
//   param[2] = ['opName', userform.opName]
//   var Data = CreateData('11', 'PDA_用户角色_用户登录', param)
//   ExecDatabase(Data).then(response => {
//     if (response.data.length > 0) {
//       user.value.AID = response.data[0].AID
//       user.value.name = response.data[0].姓名
//       // user.value.classes = response.data[0].班次
//       // user.value.teamGroup = response.data[0].班组
//       user.value.role = response.data[0].用户角色
//       user.value.userName = response.data[0].登录密码
//       user.value.password = response.data[0].登录账号
//       user.value.opName = userform.opName
//       ElMessage.success('登录成功，跳转主页')
//       store.isLoading = true
//       router.push('/')
//     } else {
//       ElMessage.warning('用户名或密码错误,请重试!')
//     }
//   })
// }

const login = () => {
  console.log(user)
  let cost = generateSalt().slice(-16)
  var param = []
  param.push(['用户名', userform.userName])
  // param.push(['Password', encrypt(userform.password, cost)])
  param.push(['密码', userform.password])
  // param.push(['cost', cost])
  var Data = CreateData('11', '菜单模块系统_用户名密码_查询数据_改造新增', param)
  ExecDatabase(Data).then(response => {
    const data = response.data
    if (data.length === 0 || data.result === '0' || data[0].result === '0') {
      ElMessage.warning('账号或密码错误，请重试!')
    } else {
      // 检查用户是否有绑定PDA权限
      if (!data[0].PDA权限) {
        ElMessage.warning('请先维护此用户PDA角色后再操作')
        return
      }

      if (!opNameList.some(item => item.工位号 === data[0].PDA权限)) {
        ElMessage.warning('您绑定的PDA权限不在可用工位列表中，请联系管理员维护')
        return
      }

      // 设置工位号并提示
      userform.opName = data[0].PDA权限
      ElMessage.success(`检测到您已绑定PDA权限：${opNameList.find(item => item.工位号 === data[0].PDA权限)?.工位名称 || data[0].PDA权限}`)

      // 获取工位对应的工位名称 一起存入
      let opName = opNameList.find(item => item.工位号 === userform.opName)

      if (opName.线体类型 != 0) {
        const param2 = []
        param2[0] = ['工位号', userform.opName]
        param2[1] = ['操作者工号', data[0].姓名]
        param2[2] = ['班次名称', '1']
        const Data = CreateData('12', '测量数据工位_监控系统_操作者工号_增加', param2)
        ExecDatabase(Data).then(() => {
        })
      }

      Cookies.set('token', data[0].token, { expires: 1 })
      Cookies.set('AID', data[0].人员编号, { expires: 1 })
      Cookies.set('name', data[0].姓名, { expires: 1 })
      Cookies.set('role', data[0].角色编号, { expires: 1 })
      Cookies.set('userName', data[0].考勤编号, { expires: 1 })
      Cookies.set('opName', userform.opName, { expires: 1 })
      Cookies.set('opNameTxt', opName.工位名称, { expires: 1 })

      user.value.token = response.data[0].token
      user.value.AID = response.data[0].人员编号
      user.value.name = response.data[0].姓名
      user.value.role = response.data[0].角色编号
      user.value.userName = response.data[0].考勤编号
      user.value.opName = userform.opName
      user.value.opNameTxt = opName.工位名称

      ElMessage.success('登录成功')
      store.isLoading = true
      router.push('/')
    }
    if (response.data.length > 0) {
    } else {
      ElMessage.warning('用户名或密码错误,请重试!')
    }
  })
}

const getOpName = () => {
  opNameList.length = 0
  // 获取工位数据（用于验证用户绑定的PDA权限是否存在）
  var param = []
  var Data = CreateData('11', 'MES_计划BOM_工位与名称_查询', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      opNameList.push(...response.data)
    }
    console.log(response)
  })
}

</script>

<style lang="scss" scoped>
.main {
  position: relative;
  height: 100vh;
  width: 100vw;
  background-image: url("/public/login.png");
  background-size: 300% 150%;

  .login {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 80vw;
    //height: 40vh;
    background-color: rgba(255, 255, 255, 0.8);
    border: 2px solid #730215;
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.8);

    .title {
      color: #f50107;
      font-size: 40px;
      text-align: center;
      font-weight: bold;
      margin-top: 3vh;
    }

    .logeType {
      width: 80%;
      display: flex;
      border-bottom: 3px solid #bcbcbc;
      margin: 30px auto;
      height: 30px;

      .item {
        color: #e43852;
        font-size: 20px;
        line-height: 20px;
        border-bottom: 2px solid #ff123a;
      }
    }

    .logFrom {
      width: 80%;
      margin: 0px auto;

      .item {
        margin: 20px 0;
      }
    }
  }
}
</style>
