<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="login" />
        </div>
        <div class="item">
          <el-select v-model="userform.role" placeholder="请选择角色" style="width: 100%" @change="getOpName()">
            <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="item">
          <el-select v-model="userform.opName" placeholder="请选择台位号" style="width: 100%">
            <el-option v-for="item in opNameList" :key="item.工位名称" :label="item.工位描述" :value="item.工位名称" />
          </el-select>
        </div>
        <div class="item" style="margin-top: 40px">
          <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 { Lock, Promotion, User } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useAppStore } from "@/store/app.js";
import { storeToRefs } from 'pinia';
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: '',
  role: ''
})

const roleList = [{ label: '进车员', value: '1' }, { label: '其他', value: '2' }]

onMounted(() => {
  // 从cookie中获取上次登录的角色和工位信息
  const lastRoleType = Cookies.get('roleType')
  const lastOpName = Cookies.get('lastOpName')
  const lastApiMesUrl = Cookies.get('API_MES_URL')

  console.log('从cookie中获取的角色类型:', lastRoleType)
  console.log('从cookie中获取的工位:', lastOpName)
  console.log('从cookie中获取的中控接口IP:', lastApiMesUrl)

  // 如果cookie中有中控接口IP，则设置到全局变量
  if (lastApiMesUrl) {
    window.g.API_MES_URL = lastApiMesUrl
  }

  // 如果cookie中有角色信息，则自动选择
  if (lastRoleType) {
    userform.role = lastRoleType
    // 获取对应角色的工位列表
    getOpName()
  }
})

const login = () => {
  if (userform.userName === '' || userform.password === '') {
    ElMessage.warning('用户名或密码不能为空')
    return
  }
  if (userform.role === '') {
    ElMessage.warning('请选择角色')
    return
  }
  if (userform.opName === '') {
    ElMessage.warning('请选择台位号')
    return
  }

  console.log(user)
  var param = []
  param[0] = ['userName', userform.userName]
  param[1] = ['password', userform.password]
  param[2] = ['opName', userform.opName]
  var Data = CreateData('11', '基础表_用户角色_用户登录', 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
      user.value.roleType = userform.role
      
      // 获取工位描述并保存
      const selectedOpInfo = opNameList.find(item => item.工位名称 === userform.opName);
      user.value.opDescription = selectedOpInfo?.工位描述 || userform.opName;

      const userInfo = {
        AID: response.data[0].AID,
        name: response.data[0].姓名,
        classes: response.data[0].班次,
        teamGroup: response.data[0].班组,
        role: response.data[0].用户角色,
        userName: response.data[0].登录密码,
        password: response.data[0].登录账号,
        opName: userform.opName,
        opDescription: selectedOpInfo?.工位描述 || userform.opName,
        roleType: userform.role
      }

      var param2 = []
      param2[0] = ['工位号', userform.opName]
      var Data2 = CreateData('11', 'CRRC_SCADA_CHControl_Moby_工位查询', param2)
      ExecDatabase(Data2).then(response => {
        if (response.data.length > 0 && response.data[0].中控接口IP) {  
          window.g.API_MES_URL = response.data[0].中控接口IP
          window.g.API_MES_ControlCode = response.data[0].中控程序代码
          // 将中控接口IP存入cookie，有效期3天
          Cookies.set('API_MES_URL', response.data[0].中控接口IP, { expires: 3 })
          Cookies.set('API_MES_ControlCode', response.data[0].中控程序代码, { expires: 3 })

          // 生成随机LoginKey
          const loginKey = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
          
          // 存入Cookie
          Cookies.set('loginKey', loginKey, { expires: 3 })
          
          // 调用存储过程保存LoginKey
          var paramKey = []
          paramKey[0] = ['工位号', userform.opName]
          paramKey[1] = ['Key', loginKey]
          var DataKey = CreateData('12', 'CRRC_登陆_Key_登陆', paramKey)
          ExecDatabase(DataKey).then(() => {
            Cookies.set('userInfo', JSON.stringify(userInfo), { expires: 3 })
            // 保存工位号到cookie，有效期3天
            Cookies.set('lastOpName', userform.opName, { expires: 3 })
            // 保存工位描述到cookie，有效期3天
            Cookies.set('lastOpDescription', userInfo.opDescription, { expires: 3 })
            // 保存角色类型到cookie，有效期3天
            Cookies.set('roleType', userform.role, { expires: 3 })

            ElMessage.success('登录成功，跳转主页')
            store.isLoading = true
            router.push('/')
          })
        }else{
          ElMessage.warning('未读取到对应中控IP!')
        }
      })
    } else {
      ElMessage.warning('用户名或密码错误,请重试!')
    }
    console.log(response)
  })
}

const getOpName = () => {
  userform.opName = ''
  opNameList.length = 0
  // 获取当前操作员名称
  var param = []
  param.push(['OPType', userform.role])
  var Data = CreateData('11', 'CRRC_台位_Moby_登录台位列表_查询', param)
  ExecDatabase(Data).then(response => {
    if (response.data.length > 0) {
      opNameList.push(...response.data)

      // 从cookie中获取上次登录的工位号
      const lastOpName = Cookies.get('lastOpName')
      // 如果cookie中有工位号且在列表中，则自动选择
      if (lastOpName && opNameList.some(item => item.工位名称 === lastOpName)) {
        userform.opName = lastOpName
      }
    }
    console.log(response)
  })
}
</script>

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

  .login {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 25vw;
    //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>
