<template>
  <div id="screen11" class="allShow">
    <div class="login">
      <div :style="formHeight"
        style="position: absolute;top: 24%; left: 45%; border: 1px solid black;border-radius: 25px; width: 450px;  background-color: white; padding: 10px;">
        <div v-if="count === 1">
          <el-form ref="form1" :model="loginForm" :rules="rules" label-position="left" label-width="80px"
            style="width: 100%;">
            <div style="display: flex;align-items: center;justify-content: center" @click="handleFullScreen">
              <img src="../../assets/image/leftPic.png" height="25px">
              <span style="font-size: 2rem; color:black; line-height: 60px;margin-left: 25px">PLCS生产管控系统</span>
            </div>
            <div style="border: 2px solid #13227a; width: 100%" />
            <div style="width: 430px; margin-top: 10px;">
              <div style="margin-left: 10px">
                <el-form-item style="margin-top: 22px">
                  <span slot="label" style="font-size: 1.5rem;color: #000">工位</span>
                  <el-select v-model="loginForm.station" placeholder="请选择工位"
                    style="width:300px; border: 2px solid black; border-radius:6px" @change="selectOpLinkMqtt">
                    <!--存储过程1-->
                    <el-option v-for="item in stationArrIp" :key="item.value" :label="`【${item.value}】${item.label}`"
                      :value="{ value: item.value, label: item.label, MesWebCode: item.MesWebCode }" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <span slot="label" style="font-size: 1.5rem;color: #000" @dblclick="AdminLogin">卡号</span>
                  <el-input ref="CardCodeInput" v-model="loginForm.password" type="password" auto-complete="on"
                    style="width:300px; border: 2px solid black; border-radius:6px" clearable placeholder="请输入卡号"
                    @keyup.enter.native="handleLoginByCard(loginForm.password)" />
                </el-form-item>
                <el-form-item v-if="loginType === 1">
                  <span slot="label" style="font-size: 1.5rem;color: #000">工号</span>
                  <el-input v-model="loginForm.username" style="width:300px; border: 2px solid black; border-radius:6px"
                    clearable placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item v-if="loginType === 1">
                  <span slot="label" style="font-size: 1.5rem;color: #000">密码</span>
                  <el-input v-model="loginForm.password" type="password" auto-complete="on"
                    style="width:300px; border: 2px solid black; border-radius:6px" clearable placeholder="请输入密码"
                    @keyup.enter.native="handleLogin" />
                </el-form-item>
                <el-form-item>
                  <span slot="label" style="font-size: 1.5rem;color: #000"></span>
                  <el-radio-group v-model="loginType">
                    <el-radio :label="0"><span style="font-size: 1.5rem">刷卡登录</span></el-radio>
                    <!-- <el-radio :label="1"><span style="font-size: 1.5rem">账号登录</span></el-radio> -->
                    <el-button type="primary" circle icon="el-icon-setting" size="mini" @click="editform3()"
                      style="margin-left: 90px;" />
                  </el-radio-group>
                </el-form-item>
                <div v-if="loginType === 1" style="text-align: center;">
                  <el-button :loading="loading" :disabled="this.loginType === 0"
                    style="background-color: #13227a; width: 50%; height: 60px;border-radius: 35px;margin-left: 70px"
                    @click="handleLogin()">
                    <span style="font-size: 1.5rem; color: #ffffff;">登录</span>
                  </el-button>
                  <!--                  <i class="el-icon-edit" style="font-size: 20px; margin-left: 30px" @click="editform2()" />-->
                  <el-button type="primary" circle icon="el-icon-setting" size="mini" @click="editform3()" />
                </div>
              </div>
            </div>
          </el-form>
        </div>
        <div v-if="count === 3">
          <el-form ref="form3" :model="form3" :rules="rules2" label-position="left" label-width="80px"
            style="width: 100%;">
            <div style="margin-left: 6px; width: 100%; height: 60px;">
              <i class="el-icon-setting" style="font-size: xx-large; margin-left: 30px; margin-top: 10px" />
              <span style="font-size: 2rem;  color:black; line-height: 60px; margin-left: 10px">设置管控系统参数</span>
            </div>
            <div style="border: 2px solid #13227a;width: 100%" />
            <div style="width: 430px; margin-top: 10px;">
              <div style="margin-left: 10px">
                <el-form-item style="margin-top: 22px">
                  <span slot="label" style="font-size: 1.5rem;color: #000">工位</span>
                  <el-select v-model="form3.stationID" style="width:300px;border: 2px solid black; border-radius:6px"
                    placeholder="请选择需要登录的工位">
                    <!--存储过程1-->
                    <el-option v-for="item in stationArr" :key="item.value" :label="`【${item.value}】${item.label}`"
                      :value="{ value: item.value, label: item.label, MesWebCode: item.MesWebCode }" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <span slot="label" style="font-size: 1.5rem;color: #000">IP</span>
                  <el-input v-model="form3.severIP" readonly
                    style="width:300px;border: 2px solid black; border-radius:6px" placeholder="请输入服务器IP地址" />
                </el-form-item>
                <el-form-item>
                  <span slot="label" style="font-size: 1.5rem;color: #000">端口</span>
                  <el-input v-model="form3.network" readonly
                    style="width:300px;border: 2px solid black; border-radius:6px" placeholder="请输入服务器端口" />
                </el-form-item>
                <el-form-item>
                  <span slot="label" style="font-size: 24px;color: #000"></span>
                  <div style="font-weight: bolder;line-height: 1.4;padding-right: 35px;">
                    选择需要登录的工位，IP与端口请联系管理管进行后台修改！
                  </div>
                </el-form-item>
                <div style="text-align: center;">
                  <el-button
                    style="background-color: #13227a; width: 50%; height: 60px;border-radius: 35px;margin-left: 70px"
                    @click="submitServiceParameters()">
                    <span style="font-size: 1.5rem; color: #fff;">提交</span>
                  </el-button>
                  <el-button type="primary" circle icon="el-icon-back" size="mini" @click="editform1()" />
                </div>
              </div>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Cookie from 'js-cookie'
import { Mqtt } from '@/utils/mqtt'
import { logAdd } from '@/utils/EventBus'
export default {
  data() {
    return {
      mqttClient: null,
      mqttConnection: {
        host: window.g.mqttIP,
        port: window.g.mqttPortNumber,
        endpoint: '/mqtt',
        clean: true, // 保留会话
        connectTimeout: 3 * 1000, // 超时时间
        reconnectPeriod: 3 * 1000, // 重连时间间隔
        clientId: '', // 同一个ID 无法二次连接
        username: '',
        password: ''
      },
      subscription: {
        topic: '',
        qos: 0
      },
      style: {
        width: '1920',
        height: '1080',
        transform: 'scaleY(1) scaleX(1) translate(-50%, -50%)'
      },
      fullscreen: false,
      isAppendToBodyOther: false,
      count: 1,
      ip: '',
      loading: false,
      class: '',
      classArr: [],
      stationArr: [],
      stationArrIp: [],
      loginType: 0,
      formHeight: {
        // height: '250px'
      },
      loginForm: {
        class: '',
        station: '',
        username: '',
        usernameShow: '',
        password: '',
        CardNo: '',
        checked: true
      },
      form2: {
        user: '',
        oldPassword: '',
        newPassword: '',
        qnewPassword: ''
      },
      form3: {
        stationID: '',
        severIP: window.g.mqttIP,
        network: window.g.mqttPortNumber
      },
      rules1: {
        user: [{ required: true, message: '请输入用户名', trigger: 'change' }],
        oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'change' }],
        newPassword: [{ required: true, message: '请输入新密码', trigger: 'change' }],
        qnewPassword: [{ required: true, message: '请确认新密码', trigger: 'change' }]
      },
      rules2: {
        stationID: [{ required: true, message: '请选择工位', trigger: 'change' }],
        severIP: [{ required: true, message: '请输入服务器ip', trigger: 'change' }],
        network: [{ required: true, message: '请输入服务器端口', trigger: 'change' }]
      },
      rules: {
        class: [{ required: true, message: '请选择班次', trigger: 'change' }],
        station: [{ required: true, message: '请选择工位', trigger: 'change' }],
        user: [{ required: true, message: '请输入用户名', trigger: 'change' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  watch: {
    loginType() {
      if (this.loginType === 1) {
        this.formHeight = {
          height: '465px'
        }
      } else {
        this.formHeight = {
          // height: '250px'
        }
      }
    }
  },
  created() {
    setTimeout(() => {
      this.getIp()
      this.getStation()
      this.$nextTick(() => {
        if (this.$refs.CardCodeInput) {
          this.$refs.CardCodeInput.focus()
        }
      })
    }, (500))
  },
  mounted() {
  },
  beforeDestroy() {
    if (this.mqttClient && this.mqttClient.client && this.mqttClient.client.connected) {
      const destroyConnection = this.mqttClient.destroyConnection()
      if (destroyConnection) {
        this.$message({
          message: 'MQTT断开成功！',
          type: 'success'
        })
      } else {
        this.$message({
          message: 'MQTT断开失败！',
          type: 'error'
        })
      }
    }
  },
  methods: {
    getIp() {
      const Data = this.CreateData('4000', '')
      this.ExecDatabase(Data).then(response => {
        if (response.data) {
          console.log('工控机IP', response.data)
          this.ip = response.data
          this.getStationByIp()
          this.$store.commit('set_stationIp', response.data)
        } else {
          this.$message.error('工控机IP获取失败 ！')
        }
      })
    },
    getStationByIp() {
      this.stationArrIp = []
      const param = []
      param[0] = ['工控机IP', this.ip]
      const Data = this.CreateData('11', 'MES_计划BOM_工位与名称_按工控机IP_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          for (let i = 0; i < response.data.length; i++) {
            this.stationArrIp.push({
              label: response.data[i].工位名称,
              value: response.data[i].工位号,
              MesWebCode: response.data[i].MesWebCode
            })
          }
          this.loginForm.station = this.stationArrIp[0]
          this.connectMqtt(this.loginForm.station.value)
        }
      })
    },
    submitServiceParameters() {
      if (this.form3.stationID.value && this.form3.severIP && this.form3.network) {
        this.$message({
          message: '参数设置成功',
          type: 'success'
        })
        let ss = 0
        for (const responseElement of this.stationArrIp) {
          if (responseElement.value === this.form3.stationID.value) {
            ss = 1
          }
        }
        if (ss === 0) {
          this.stationArrIp.push(this.form3.stationID)
        }
        this.loginForm.station = this.form3.stationID
        this.count = 1
        // const param = []
        // param[0] = ['工位代码', this.form3.stationID.value]
        // param[1] = ['工控机IP', this.ip]
        // param[2] = ['工位号', this.form3.stationID.value]
        // param[3] = ['服务器IP', this.form3.severIP]
        // param[4] = ['通讯端口', this.form3.network]
        // const Data = this.CreateData('12', 'AMES_MES_计划BOM_工位与名称_信息修改', param)
        // this.ExecDatabase(Data).then(response => {
        //   if (response.data[0].result === '1') {
        //     this.$message({
        //       message: '参数设置成功',
        //       type: 'success'
        //     })
        //     let ss = 0
        //     for (const responseElement of this.stationArrIp) {
        //       if (responseElement.value === this.form3.stationID.value) {
        //         ss = 1
        //       }
        //     }
        //     if (ss === 0) {
        //       this.stationArrIp.push(this.form3.stationID)
        //     }
        //     this.loginForm.station = this.form3.stationID
        //     this.count = 1
        //   } else {
        //     this.$message.error('参数设置失败')
        //   }
        // })
      } else {
        this.$message.error('请输入全参数！')
      }
    },
    selectOpLinkMqtt(value) {
      this.connectMqtt(value.value)
    },
    async connectMqtt(opCode) {
      if (this.mqttClient && this.mqttClient.client && this.mqttClient.client.connected) {
        this.subscription.topic = window.g.mqttSubscriptionTopic + opCode + '/login'
        this.mqttClient.doSubscribe(this.subscription)
        return
      }
      this.mqttConnection.clientId = 'MES_WEB_CLIENT_' + opCode + '_login' // 同一个ID 无法二次连接
      this.mqttConnection.username = 'MES_WEB_CLIENT_' + opCode + '_login'
      this.mqttClient = new Mqtt(this.mqttConnection)
      this.mqttClient.createConnection()
      this.subscription.topic = window.g.mqttSubscriptionTopic + opCode + '/login'
      this.mqttClient.doSubscribe(this.subscription)
      // 使用过程中的报错 断开连接 服务端出问题
      this.mqttClient.client.on('connect', () => {
        console.log('MQTT Connection succeeded!')
      })
      this.mqttClient.client.on('disconnect', () => {
        console.log('MQTT disconnect!')
      })
      this.mqttClient.client.on('offline', () => {
        console.log('MQTT offline!')
      })
      this.mqttClient.client.on('close', () => {
        console.log('MQTT close!')
      })
      this.mqttClient.client.on('error', error => {
        console.log('Connection failed', error)
      })
      this.mqttClient.client.on('message', (topic, message) => {
        const arrays_signal = message.toString().split('|')
        console.log(message.toString())
        const m_Source = arrays_signal[0]
        const m_Command = arrays_signal[1]
        // const m_Opname = arrays_signal[2]
        const m_Value = arrays_signal[3]
        switch (m_Source) {
          case 'BarCode':
            switch (m_Command) {
              case 'login':
                this.handleLoginByCard(m_Value)
                break
            }
            break
        }
      })
    },
    getStation() {
      this.stationArr = []
      const Data = this.CreateData('11', '工位与名称_视图_查询')
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.stationArr.push({
            label: response.data[i].工位名称,
            value: response.data[i].工位号,
            MesWebCode: response.data[i].MesWebCode
          })
        }
      })
    },
    handleLogin() {
      if (!this.loginForm.station.value) {
        this.$message.error('请设置工位！')
      } else {
        this.row = null
        this.loading = true
        this.$store.dispatch('Login', this.loginForm).then(res => {
          if (res.data.length === 1 && res.data[0].考勤编号 === this.loginForm.username && res.data[0].密码 === this.loginForm.password) {
            if (this.mqttClient && this.mqttClient.client && this.mqttClient.client.connected) {
              this.mqttClient.destroyConnection()
            }
            this.loginForm.usernameShow = res.data[0].姓名
            const param = []
            param[0] = param[0] = ['工位号', this.loginForm.station.value]
            param[1] = param[1] = ['操作者工号', this.loginForm.username]
            param[2] = param[2] = ['班次名称', 'A'] // this.loginForm.class]
            const Data = this.CreateData('12', '测量数据工位_监控系统_操作者工号_增加', param)
            this.ExecDatabase(Data).then(() => { })
            this.$message({
              message: '登录成功',
              type: 'success'
            })
            this.setStation()
            this.loading = false
            this.$router.push({ path: '/layout' })
            this.$router.push({
              name: 'OperationGuide',
              params: {
                id: 123
              }
            })
          } else {
            this.$message.error('登录失败！')
          }
        }).catch(() => {
          this.loading = false
        })
        if (this.loginForm.checked === true) { // 传入账号名，密码，和保存天数3个参数
          this.setCookie(this.loginForm.username, this.loginForm.password, this.loginForm.checked)
        } else {
          this.clearCookie()
        }
      }
    },
    handleLoginByCard(CardNo) {
      this.loginForm.CardNo = CardNo
      if (!this.loginForm.station.value) {
        this.$message.error('请设置工位！')
      } else {
        this.row = null
        this.loading = true
        this.$store.dispatch('LoginByCard', this.loginForm).then(res => {
          this.loginForm.username = res.data[0].考勤编号
          this.loginForm.password = res.data[0].密码
          if (res.data.length === 1) {
            if (this.mqttClient && this.mqttClient.client && this.mqttClient.client.connected) {
              this.mqttClient.destroyConnection()
            }
            this.loginForm.usernameShow = res.data[0].姓名
            const param = []
            param[0] = param[0] = ['工位号', this.loginForm.station.value]
            param[1] = param[1] = ['操作者工号', this.loginForm.username]
            param[2] = param[2] = ['班次名称', 'A'] // this.loginForm.class]
            const Data = this.CreateData('12', '测量数据工位_监控系统_操作者工号_增加', param)
            this.ExecDatabase(Data).then(() => { })
            this.$message({
              message: '登录成功',
              type: 'success'
            })
            this.setStation()
            this.loading = false
            this.$router.push({ path: '/layout' })
            this.$router.push({
              name: 'OperationGuide',
              params: {
                id: 123
              }
            })
          } else {
            this.$message.error('登录失败！')
            this.loading = false
          }
        }).catch(() => {
          this.loading = false
        })
        if (this.loginForm.checked === true) { // 传入账号名，密码，和保存天数3个参数
          this.setCookie(this.loginForm.username, this.loginForm.password, this.loginForm.checked)
        } else {
          this.clearCookie()
        }
      }
    },
    setStation() {
      console.log('setStation', this.loginForm.station)
      this.$store.commit('set_MesWebCode', this.loginForm.station.MesWebCode)
      this.$store.commit('set_stationNumber', this.loginForm.station.value)
      this.$store.commit('set_stationName', this.loginForm.station.label)
      this.$store.commit('set_classesID', 'A')
      this.$store.commit('set_classes', '白班')
      this.$store.commit('set_serverIP', this.form3.severIP)
      this.$store.commit('set_serverPort', this.form3.network)
      this.$store.commit('set_stationUserName', this.loginForm.usernameShow)
      this.$store.commit('set_stationUserCount', this.loginForm.username)
      logAdd(this, {
        stationNumber: this.loginForm.station.value,
        msgType: 'INFO',
        operationType: 'LOGIN',
        Content: `${this.loginForm.usernameShow}【${this.loginForm.username}】登录成功`
      })
    },
    setCookie(username, password, checked) {
      Cookie.set('username', username, { expires: 7 })
      Cookie.set('password', password, { expires: 7 })
      Cookie.set('checked', checked, { expires: 7 })
    },
    clearCookie() {
      Cookie.remove('username')
      Cookie.remove('password')
      Cookie.remove('checked')
    },
    routeJump2() {
      this.count = 1
    },
    editform2() {
      this.count = 2
    },
    editform3() {
      this.count = 3
    },
    editform1() {
      this.count = 1
    },
    handleFullScreen() {
      const element = document.documentElement
      if (this.fullscreen) {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen()
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen()
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen()
        }
      } else {
        if (element.requestFullscreen) {
          element.requestFullscreen()
        } else if (element.webkitRequestFullScreen) {
          element.webkitRequestFullScreen()
        } else if (element.mozRequestFullScreen) {
          element.mozRequestFullScreen()
        } else if (element.msRequestFullscreen) {
          // IE11
          element.msRequestFullscreen()
        }
      }
      this.fullscreen = !this.fullscreen
    },
    AdminLogin() {
      this.handleLoginByCard('2222')
    }
  }
}
</script>

<style scoped>
.allShow {
  height: 100vh;
  width: 100vw;
  background-color: #17214e;
}

.login {
  height: 100%;
  background-position: 20% 40%;
  background-repeat: no-repeat;
  background-image: url("../../../public/login.png");

  ::v-deep .el-radio,
  .el-radio__input {
    line-height: 2;
  }

  ::v-deep .el-radio__label {
    font-size: 1.5rem;
  }

  ::v-deep .el-radio__inner {
    width: 20px;
    height: 20px;
  }
}
</style>
