<template>
  <view class="common-container">
    <!-- <u-button @click="handleTest">跳转测试</u-button> -->
    <view class="header">
      <image mode="widthFix" class="header-logo" style="width: 80px; margin: 10px auto; display: block" src="/static/logo.png"></image>
      <TabHeader></TabHeader>
      <view class="setting-body" @click="handleUserTaped">
        <u-icon name="list" size="45" class="setting-icon"></u-icon>
        {{ this.vuex_user.nickName }}
      </view>
    </view>
    <view class="common-main">
      <ProdReport v-if="tabIndex === 'PRO'"></ProdReport>
      <GxContent v-else-if="tabIndex === 'GX'"></GxContent>
      <ProContent v-if="tabIndex === 'DV'"></ProContent>
    </view>
    <u-modal width="90%" v-model="showWorkstationFlag" :showConfirmButton="false" :cancelText="$t('取消')" :confirmText="$t('确认')" :showCancelButton="true" :title="$t('请选择工作单元')" :content="$t('操作内容')">
      <view class="station_list">
        <u-empty :text="$t('暂无工作单元')" mode="list" v-if="workUnitList.length == 0" style="margin: 0 auto; display: block; height: 360rpx; padding: 100rpx 0"></u-empty>
        <template v-else>
          <u-row>
            <u-col span="3" v-for="(card, index) in workUnitList" :key="index">
              <u-card class="station_card" :show-foot="false" :title="$t('工作单元') + card.workunitCode">
                <view class="station_card_text" slot="body">
                  <view class="workunitName">{{ $t('工作单元名称：') + card.workunitName }}</view>
                  <u-button type="primary" @click="setWorkUnit(card)" style="margin-top: 30rpx">{{$t('选择')}}</u-button>
                </view>
              </u-card>
            </u-col>
          </u-row>
        </template>
      </view>
    </u-modal>

    <u-modal :cancelText="$t('取消')" :confirmText="$t('确认')" v-model="showLogoutMenu" :showConfirmButton="false" :showCancelButton="true" width="600px" :title="$t('请选择操作')">
      <view class="logoutmenu">
        <u-button shape="circle" class="menu_button" @click="" type="primary">{{$t('更改密码')}}</u-button>
        <u-button shape="circle" class="menu_button" @click="handleCommand('workunit')" type="warning">{{$t('切换工作中心')}}</u-button>
        <u-button shape="circle" class="menu_button" @click="handleCommand('print')" type="error">{{$t('默认打印机')}}</u-button>
        <u-button shape="circle" class="menu_button" @click="handleCommand('exit')" type="error">{{$t('退出登录')}}</u-button>
      </view>
    </u-modal>

    <!-- 	<u-modal
	  title="领料申请"
	  @confirm="materialRequestSave()"
	  show-cancel-button
	  :title-style="{ 
		'background-color': '#1E3770', 
		color: '#FFFFFF', 
		'line-height': '37px', 
		'padding-top': '0px' }"
	  v-model=""
	  width="1300rpx"
	  
	> -->
    <u-modal
      :title="$t('打印机')"
      :confirmText="$t('确认')"
      show-cancel-button
      :show-confirm-button="false"
      :cancel-text="$t('返回')"
      :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
      v-model="showPrintFlag"
      width="1600rpx"
    >
      <view class="list-bar">
        <u-form label-width="100px" :model="curTaskInfo"></u-form>
        <scroll-view scroll-y="true" class="scroll-list" :style="{ height: this.screenHeight - 280 + 'px' }">
          <uni-table ref="materialRequestTable" border stripe :loading="loading" :emptyText="$t('未查询到数据')">
            <uni-tr>
              <uni-th width="100px" align="center">{{$t('打印机类型')}}</uni-th>
              <uni-th width="100px" align="center">{{$t('打印机名称')}}</uni-th>
              <uni-th width="100px" align="center">{{$t('打印机位置')}}</uni-th>
              <uni-th width="60px" align="center">{{$t('型号')}}</uni-th>
              <uni-th width="60px" align="center">{{$t('连接类型')}}</uni-th>
              <uni-th width="10px" align="center">{{$t('操作')}}</uni-th>
            </uni-tr>
            <uni-tr v-for="(line, index) in materialRequestArrays" :key="index">
              <uni-td align="center">{{ line.printerType }}</uni-td>
              <uni-td align="center">{{ line.printerName }}</uni-td>
              <uni-td align="center">{{ line.printerPlace }}</uni-td>
              <uni-td align="center">{{ line.printerModel }}</uni-td>
              <uni-td align="center">{{ line.connectionType }}</uni-td>
              <uni-td align="center">
                <view class="uni-group">
                  <button class="uni-button" v-if="line.userPrinterStatus == '1'" size="mini" type="primary">{{$t('已绑定')}}</button>
                  <button class="uni-button" v-else size="mini" type="primary" @click="materialRequestFormShow(line)">{{$t('绑定')}}</button>
                </view>
              </uni-td>
            </uni-tr>
          </uni-table>
        </scroll-view>
      </view>
    </u-modal>
    <canvas :style="{width: canvasWidth +'px', height: canvasHeight +'px'}" canvas-id="firstCanvas" id="firstCanvas" class="firstCanvas" />
  </view>
</template>

<script>
import i18n from '../../lang/index'

import TabHeader from './TabHeader.vue';
import ProContent from '../mes/pro/index.vue';
import GxContent from '../mes/gx/index.vue';
import ProdReport from '../mes/prodReport/index.vue';
import DictData from '@/components/DictData';
import UButton from '../../uview-ui/components/u-button/u-button.vue';

export default {
  name: 'HomePage',
  components: {
    TabHeader,
    ProContent,
    GxContent,
    ProdReport,
    UButton
  },
  data() {
    return {
      tabIndex: 'PRO',
      showWorkstationFlag: false,
      showPrintFlag: false,
      showLogoutMenu: false,
      activeProcess: null,
      loading: false,
      userInfo: {
        nickName: i18n.t('张三'),
        avatar: require('@/static/images/head.png')
      },
      materialRequestArrays: [],
      processList: [], //工序清单
      workstationList: [], //工作中心清单
      workUnitList: [], //工作中心清单
      curTaskInfo: {}, //打印机的
      screenHeight: 768,
      currentFlag: 0
    };
  },
  async created() {
    uni.$on('switchTab', (indexCode) => {
      this.tabIndex = indexCode;
    });
    uni.$on('changeWorkunit', (indexCode) => {
      this.handleCommand('workunit');
    });
    uni.$on('BLEstatus', (status) => {
      this.BLEBindbyStatus(status);
    });
    await this.getWorkUnitList();
    
    this.$u.api.getTaskConfig().then(res => {
      if (res.code === 200) {
        if (res.msg === 'true') {
          this.setWorkUnit(null)
        } else {
          this.setWorkUnit(this.workUnitList[0])
        }
      }
      uni.$emit('getTaskConfig')
    })
    
  },
  destroyed() {
    uni.$off('switchTab');
    uni.$off('changeWorkunit');
    uni.$off('BLEstatus');
  },
  methods: {
    handleTest() {
      uni.navigateTo({
        url: '/pages/test/test'
      });
    },
    //用户部分点击
    handleUserTaped() {
      console.log('TAPED');
      // this.$refs.menu_dialog.open();
      this.showLogoutMenu = true;
    },
    //获取工序清单
    getProcessList() {
      this.$u.api.getProcessList({}).then((res) => {
        if (res.code === 200) {
          this.processList = res.data;
          this.activeProcess = res.data[0].processCode;
          this.getWorkstationList({ index: 0 });
        } else {
          this.$u.toast(i18n.t('获取工序清单异常') + res.msg);
        }
      });
    },
    //获取工作中心清单
    getWorkstationList(item) {
      this.currentFlag = item.index;
      this.activeProcess = this.processList[item.index].processCode;
      this.$u.api
        .getWorkstationList({
          processCode: this.activeProcess
        })
        .then((res) => {
          if (res.code === 200) {
            this.workstationList = res.data;
          } else {
            this.$u.toast(i18n.t('获取工作中心清单异常') + res.msg);
          }
        });
    },
    async getWorkUnitList(item) {
      this.$u.vuex('vuex_workunitList', null);
      await this.$u.api.getWorkUnitList({}).then((res) => {
        if (res.code === 200) {
          this.workUnitList = res.rows;
          this.$u.vuex('vuex_workunitList', res.rows);
        } else {
          this.$u.toast(i18n.t('获取工作单元清单异常') + res.msg);
        }
      });
    },
    //设置当前触控屏的工作中心
    setWorkUnit(station) {
      this.$u.vuex('vuex_workunit', station);
      this.showWorkstationFlag = false;
      uni.$emit('switchWorkunit', station);
    },
    materialRequestFormShow(row) {
      if(row.connectionType !== 'bluetooth') {
        this.confirmBIND(row)
      } else {
        uni.showLoading({
          title: i18n.t('绑定中')
        })
        this.currentRow = row
        this.initBle()
      }
    },
    confirmBIND(row){
      this.$u.api
        .addUserPrint({
          userId: this.vuex_user.userId,
          userName: this.vuex_user.userName,
          nickName: this.vuex_user.nickName,
          printerId: row.printerId,
          printerName: row.printerName,
          printerIp: row.printerIp,
          printerPort: row.printerPort,
          printerType: row.printerType,
          printerPlace: row.printerPlace,
          printerModel: row.printerModel,
          printerUrl: row.printerUrl,
          printerStatus: row.status,
          brand: row.brand,
          connectionType: row.connectionType,
          enableFlag: row.enableFlag
        })
        .then((res) => {
          if (res.code === 200) {
            if (res.msg === i18n.t('操作成功')) {
              this.$u.toast(i18n.t('绑定成功'));
              this.$u.api.getUserPrintInfo().then((res) => {
                // console.log(res, 'res888')
                if (res.code === 200) {
                  this.$u.vuex('vuex_printerInfo', {
                    hostUrl: 'http://' + res.data.printerIp + ':' + res.data.printerPort,
                    printerName: res.data.printerName,
                    connectionType: res.data.connectionType
                  });
                  if (res.data.connectionType !== 'bluetooth') {
                    this.createSocket()
                  }
                }
              });
              this.getPrint();
            } else {
              this.$u.toast(res.msg);
            }
          }
        });
    },
    BLEBindbyStatus(status) {
      if(!this.currentRow) return
      if(status && this.cuDevice.name === this.currentRow.printerName) {
        uni.hideLoading()
        this.confirmBIND(this.currentRow)
      } else if (!status) {
        uni.hideLoading()
        this.currentRow = null
        this.$u.toast(i18n.t('蓝牙连接失败'))
      }
    },
    handleCommand(command) {
      if (command === 'exit') {
        this.loading = true;
        this.$u.api.logout().then((res) => {
          this.loading = false;
          if (res.msg) {
            this.$u.toast(res.msg);
          }

          if (res.code === 200) {
            setTimeout(() => {
              DictData.logout();
              uni.reLaunch({
                url: '/pages/sys/login/login'
              });
            }, 500);
          }
        });
      } else if (command == 'workunit') {
        this.showLogoutMenu = false;
        this.showWorkstationFlag = true;
        this.getWorkUnitList();
      } else if (command == 'print') {
        this.showPrintFlag = true;
        this.getPrint();
      }
    },
    getPrint() {
      this.$u.api.getUserPrint({userId: Number(this.vuex_user.userId)}).then((res) => {
        if (res.code == 200) {
          this.materialRequestArrays = res.rows;
        }
      });
    }
  }
};
</script>

<style lang="scss">
.common-container {
  width: 100vw;
  height: 100vh;
  display: flex;
}

.common-head {
  height: 40px;
  background-color: rgb(3, 26, 60);
  display: flex;
  align-items: center;
  padding: 0 15px;
  box-sizing: border-box;
}

.header {
  width: 90px;
  background-color: #132138;
  color: aliceblue;
  font-size: 25px;
  font-family: 华文楷体;
  line-height: 80rpx;
  height: inherit;

  .header-logo {
    width: 200rpx;
    height: auto;
    margin: 40rpx auto;
    display: block;
  }
}

.header .divItem {
  height: 100%;
  align-items: center;
}

.header .workstation {
  text-align: center;
  flex-grow: 1;
}

.header .user {
  width: 30%;
}

.header .user .user-icon {
  float: right;
}

img {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  margin-left: 10px;
}

.header .user .user-text {
  float: right;
}

.logoutmenu {
  width: 100%;
  display: flex;
  justify-content: center;
}

.menu_button {
  width: 100px;
  margin: 10px;
}

.station_modal {
}

.station_list {
  /* display: flex;
  flex-wrap: wrap; */
}

.station_card {
  /* width: 250px; */
  height: 170px;
  
}
.workunitName {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  height:38px;
}
.common-main {
  flex: 1;
  height: 100%;
  padding: 6px 6px 6px 0;
  margin: 0;
  width: 100%;
  overflow: auto;
  background-image: linear-gradient(to top right, rgb(19, 26, 56), rgb(33, 64, 128));
}

.setting-body {
  position: absolute;
  bottom: 20rpx;
  width: 200rpx;
  margin: 0 auto;
  font-size: 36rpx;
  font-weight: initial;
  text-align: center;

  .setting-icon {
    margin: 10rpx 10rpx;
  }
}
.firstCanvas {
  position: absolute;
  // z-index: 99999999;
  pointer-events: none ;
  left: -99999px;
}
</style>
