<template>
  <div
    id="playerMap"
    ref="playerMap"
    class="app-container yunMapDiv"
    style="height: 200%"
  >
    <!-- 全屏 -->
    <el-row :gutter="20" class="rowCls">
      <div class="headerBg">
        <h2>现场工控端</h2>
        <div class="battonDiv">
          <el-tooltip
            v-if="!isFullSreen"
            class="item"
            effect="dark"
            :content="$t('largeScreen.common.screening')"
            placement="top-start"
          >
            <a @click="fullPing()"><i class="el-icon-full-screen"></i></a>
          </el-tooltip>
          <el-tooltip
            v-else
            class="item"
            effect="dark"
            :content="$t('largeScreen.common.cancel')"
            placement="top-start"
          >
            <a @click="exitFullPing()"><i class="el-icon-switch-button"></i></a>
          </el-tooltip>
        </div>
      </div>      
    </el-row>

    <!-- 区域模块 -->
    <div style="text-align: left; margin-left: 5%">
      <!-- 搜索-部分 -->
      <div class="defaultRow noBorder">
        <span :span="2" style="margin-left: 2%; color:white;">
           当前日期: {{currentDate}}
        </span> 

        <span :span="2" style="margin-right: 5%; float: right">
          <el-button
            plain
            type="primary"
            icon="el-icon-view"
            size="medium"
            @click="navigator"
          >
            我的任务
          </el-button>
        </span>
      </div>

      <el-tabs style="text-align: left; margin-top: 25px" @tab-click="tabClick">
        <el-tab-pane label="任务打卡">
          <span class="tabTitle" slot="label"
            ><el-badge :value="taskCount" class="badge"
              ><i class="el-icon-date"></i>任务打卡</el-badge
            >
          </span>
          <el-row :gutter="20" v-show="hasTask">
            <el-col :span="20">
            <div class="tag-group">
              <el-badge :value="assignTask.startTime?'完成':''" class="bItem">
              <el-tag 
                   size="medium"
                   class="input-new-tag"                   
                    effect="dark">
                    上班{{assignTask.planStartTime? assignTask.planStartTime.substring(0,5):''}} 
                      <span class="tagTip">{{assignTask.startTime? assignTask.startTime.substring(10)+'已打卡':''}}</span>                  
                </el-tag>
                
              </el-badge>
             
              <el-badge :value="assignTask.endTime?'完成':''" class="bItem">     
                 <el-tag 
                   size="medium"
                   class="input-new-tag"     
                   :type = "assignTask.startTime?'':'info'"              
                    effect="dark">
                    下班{{assignTask.planEndTime? assignTask.planEndTime.substring(0,5):''}}
                    <span class="tagTip">{{assignTask.endTime? assignTask.endTime.substring(10)+'已打卡':''}}</span>
                </el-tag>  
              </el-badge>              
           </div>
          </el-col> 
          </el-row>
          <el-row :gutter="24" v-show="hasTask">              
              <el-col :span="8" :offset="8">
                <div class="grid-content">
                  <el-button type="success" class="large-round-button"  circle  @click="assign">
                       {{assignTask.startTime?(assignTask.endTime?'':'下班打卡'):'上班打卡'}} {{currentTime}}
                  </el-button>                 
                </div>
              </el-col>              
          </el-row>  
         
        </el-tab-pane>
        <el-tab-pane label="打卡记录">
          <span class="tabTitle" slot="label">
            <i class="el-icon-date"></i> 打卡记录
          </span>
          <div class="tableTransparent">
            <el-table
			        style="height:100%;min-height:80px;"
              :header-cell-style="{ background: '#1890ff', color: '#fff' }"
              :key="tableKey"
              ref="table"
              v-loading="loading"
              :data="tableData.data"
              border
              fit
              row-key="id"
            >
              <el-table-column
                :label="$t('common.serialNo')"
                width="55px"
                align="center"
              >
                <template slot-scope="scope">
                  <div>
                    {{
                      scope.$index +
                      (queryParams.current - 1) * queryParams.size +
                      1
                    }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="date" label="打卡日期" align="center">
              </el-table-column>
              <el-table-column prop="planStartTime" label="计划上班时间" align="center">
              </el-table-column>
              <el-table-column prop="planEndTime" label="计划下班时间" align="center">
              </el-table-column>
              <el-table-column prop="startTime" label="上班开始时间" width="150" align="center">
              </el-table-column>
              <el-table-column prop="endTime" label="下班结束时间" width="150" align="center">
              </el-table-column>
              <el-table-column prop="overTime" label="打卡完成" width="100" align="center">
				          <template slot-scope="{ row }">
                      {{ row.startTime && row.endTime ? "是" : "否" }}
                  </template>
              </el-table-column>              
            </el-table>
            <pagination
              v-show="tableData.total > 0"
              :limit.sync="queryParams.size"
              :page.sync="queryParams.current"
              :total="Number(tableData.total)"
              @pagination="fetch"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>    
  </div>
</template>


<script>
// 【查看】组件
import { fullScreen, exitFullScreen, initQueryParams } from "@/utils/commons";
import stationMgrApi from "@/api/machiningClient/stationMgr";
import taskMgrApi from "@/api/runManageCenter/taskMgr";
import machiningClientApi from "@/api/machiningClient/machiningClient"
import Pagination from "@/components/Pagination"
import moment from 'moment';
export default {
  name: "TouchScreen",
  components: {Pagination},
  props: {},
  data() {
    return {
      tableKey: 0,
      queryParams: initQueryParams({}),
      elTags:[{"label":"上班", "type":""},{"label":"下班", "type":"info"}],      
      currentTime: '',
      currentDate: '',
      hasTask: true,
      assignTask:{},
      options: [
      ],
      currentStationId: "",
      currentStationName: "",
      taskCount: "",
      taskData: [
      ],
      current: 1,
      timer: null,
      confirmDisabled: true,
      tenantViewVisible: false,      
      isFullSreen: false, // 默认不全屏
      loading: false,
      uniqueCode: "",
      tableData: {
        total: 0
      }
    };
  },
  // 实例已经在内存中创建好，此时data和methods已将ok,如果要操作data中的数据或是调用methods中的方法，最早只能在created中操作
  created() {
    this.currentDate = moment().format('YYYY-MM-DD');
    this.getCurrentSchedule();
  },
  watch: {
    'taskData': {
        handler(val, oldVal) {
          // 加载列表数据
          //console.log(val[0])
          //console.log(oldVal[0])
          if(oldVal.length>0 && val.length>0 && val[0].id!=oldVal[0].id){
            window.location.reload()
          }
        },
        deep: true
      }
  },
  computed: {
    currentUser() {
      return this.$store.state.account.user;
    },
  },
  mounted() {
    //setInterval(this.getStation, 2000);
    this.timerTask()
    
  },
  methods: {
    tabClick(e){
      console.log("被选择的tab:", e.index)
      // 待执行-tab
      if(e.index == 0){
        //this.getStation()
        this.timerTask()
      }
      // 已完成-tab
      if(e.index == 1){
        this.clearTimer()
        this.fetch()
      }
    },

    // 全屏
    fullPing() {
      this.$nextTick(() => {
        // 显示【退出全屏】
        this.isFullSreen = true;
        // 如果是退出全屏
        let $playerMap = this.$refs.playerMap;
        if ($playerMap) {
          fullScreen($playerMap);
        }
      });
    },
    //定时器处理
    timerTask(){
       let that = this
       that.timer = setInterval(()=>{
          this.currentTime = new Date().toLocaleTimeString();
       }, 1000)
    },
    clearTimer(){
       if(this.timer){
          clearInterval(this.timer)
          this.timer = null
       }
    },
    // 退出全屏
    exitFullPing() {
      this.$nextTick(() => {
        // 显示【全屏】
        this.isFullSreen = false;
        // 如果是全屏
        exitFullScreen(document.getElementById("playerMap"));
      });
    },
    selectChange(value) {
      console.log(value);
    },
    assign(){
      let ret = this.assignTask.startTime && this.assignTask.endTime
      if(ret) {
        this.$message({
              message: "打卡已完成,请勿重复点击",
              type: 'warning'
            });
            return false
      }
      let onWork = this.assignTask.startTime? false:true
      stationMgrApi.updateSchedule({ id: this.assignTask.id, onWork: onWork })
        .then((res) => {
          res = res.data;
          if (res.isSuccess) {
            this.$message({
              message: "打卡成功",
              type: 'success'
            });
            this.getCurrentSchedule();         
          }
        }).catch(()=>{ });

    },
    getCurrentSchedule() {
      stationMgrApi.getCurrentSchedule({ userId: this.$store.state.account.user.id, date: this.currentDate })
        .then((res) => {
          res = res.data;
          if (res.isSuccess) {
            console.log(res.data)
            this.assignTask = res.data            
          }else{
            this.$message({
              message: "今天没有加工任务",
              type: 'warning'
            });
            this.hasTask = false
            this.clearTimer()
          }
        }).catch(()=>{ });
    },
   
    resolveLogo(logo) {
      return require(`@/assets/yunMap/${logo}`);
    },
    view (item) {
        // let that = this;
        // let current = that.options.filter(function (c, i, a) {
        //   if (c.value == that.currentStationId) {
        //      return c
        //   }
        // })
        // item.procedurePosition = current[0].name;
        // 只有开始中的页面可以点击进入详情页面操作
        console.log("开始")
        item.currentStationName = this.currentStationName
        if(item.exeStatus === '2' && item.interfaceType === '04' && item.step=="1"){
            if(item.taskName == '上料' || item.nodeName == '上料' ){
                this.$refs.view1.setTenant(item)
                this.view1Visible = true
            }else if(item.taskName.indexOf('翻面')>-1){
                item.uniqueCode = this.uniqueCode
                this.$refs.view2.setTenant(item)
                this.view2Visible = true
            }else if(item.taskName.indexOf('下料')>-1){
                if(item.taskName.indexOf('OP')>-1 || item.taskName.indexOf('热处理')>-1){
                  //工序下料
                  item.uniqueCode = this.uniqueCode
                  this.$refs.view6.setTenant(item)
                  this.view6Visible = true
                }else{
                  item.uniqueCode = this.uniqueCode
                  this.$refs.view3.setTenant(item)
                  this.view3Visible = true
                }
            }else if(item.taskName.indexOf('上料')>-1){
                //工序上料或热处理上料
                item.uniqueCode = this.uniqueCode
                this.$refs.view5.setTenant(item)
                this.view5Visible = true
            }
        }
	  },
    viewClose() {
      this.view1Visible = false
      this.view2Visible = false
      this.view3Visible = false
      this.view4Visible = false
      this.view5Visible = false
      this.view6Visible = false
      this.view7Visible = false
    },
    editSuccess(){
      // this.getStation()
      // this.taskData.shift();
      console.log("init query task")
       this.$nextTick(() => {
          this.getStation()
      });
    },
    setPercentage(time, left) {
      return this.formatGap(time, left)[0] > 100
        ? 100
        : this.formatGap(time, left)[0];
    },
    // 设置进度文本内容
    setItemText(time, left) {
      return () => {
        return this.formatGap(time, left)[1];
      };
    },
    //时间差转换
    formatGap(time, left) {
      return [Number(parseInt((100 * left) / time)), "剩余" + left + "分钟"];
    },

    fetch(params = {}) {
      this.loading = true
      if (this.queryParams.timeRange) {
        this.queryParams.map.deliveryTime_st = this.queryParams.timeRange[0]
        this.queryParams.map.deliveryTime_ed = this.queryParams.timeRange[1]
      }

      this.queryParams.current = params.current ? params.current : this.queryParams.current
      this.queryParams.size = params.size ? params.size : this.queryParams.size
      console.log(this.$store.state.account.user.id)
      this.queryParams.model.userId = this.$store.state.account.user.id
      stationMgrApi.schedulePageList(this.queryParams).then(response => {
        const res = response.data
        if (res.isSuccess) {
          this.tableData = res.data
          console.log(this.tableData)
          // 给列表设置条数
          this.$emit('setTabNums', res.data.total, 'tab2')
        }
        // eslint-disable-next-line no-return-assign
      }).finally(() => this.loading = false)
    },
    getFullTime(date) {
      var yy = date.getFullYear(); //年
      var mm = date.getMonth() + 1; //月
      var dd = date.getDate(); //日
      var hh = date.getHours(); //时
      var ii = date.getMinutes(); //分
      var ss = date.getSeconds(); //秒
      var clock = yy + "-";
      if (mm < 10) clock += "0";
      clock += mm + "-";
      if (dd < 10) clock += "0";
      clock += dd + " ";
      if (hh < 10) clock += "0";
      clock += hh + ":";
      if (ii < 10) clock += "0";
      clock += ii + ":";
      if (ss < 10) clock += "0";
      clock += ss;
	  return clock;
    },
    navigator() {     
      this.$store.dispatch('tagsView/delView', this.$route).then(res => {
					this.$router.push({ path: '/machiningClient/touchScreen', query: {userId: this.$store.state.account.user.id}}) //带参跳转
			})
    },
  },
};
</script>


<style lang="scss" scoped>
.tabDiv {
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 100%;
  .battonDiv {
    z-index: 9;
  }
}
.el-tag + .el-tag {
    margin-left: 20px;
  }
  .input-new-tag {
    width: 200px;
    margin-left: 10px;
    vertical-align: bottom;
    height: 50px;
    line-height: 50px;
    padding-top: 0;
    padding-bottom: 0;
  }  
.bItem {
  margin-top: 10px;
  margin-right: 40px;
}  
.grid-content {
   margin-top:100px;
}
.large-round-button {
  width: 250px; /* 设置按钮的宽度 */
  height: 250px; /* 设置按钮的高度 */
  border-radius: 50%; /* 使按钮变成圆形 */
  background-color: #007BFF; /* 设置背景颜色 */
  color: white; /* 设置文字颜色 */
  border: none; /* 移除边框 */
  font-size: 24px; /* 设置文字大小 */
  cursor: pointer; /* 鼠标悬停时显示手指图标 */
  outline: none; /* 移除点击后的轮廓线 */
}
.tagTip{
   color:#444;
   font-size:8px;
   margin-left:15px;
   float:right;
}

.tabTitle {
  font-size: 24px;
  height: 24px;
  line-height: 24px;
}
.card_content {
  padding: 8px;
  width: 100%;
  text-align: left;
  color: #fff;
}
.card_header {
  position: relative;
  border-bottom: 1px solid #fff;
  margin: 10px 0;
}
.indexNo {
  position: absolute;
  top: 25%;
  left: 9%;
  font-size: 24px;
  line-height: 24px;
  height: 24px;
  color: #fff;
  z-index: 999;
}
.indexNo2 {
  position: absolute;
  top: 25%;
  left: 6%;
  font-size: 24px;
  line-height: 24px;
  height: 24px;
  color: #fff;
  z-index: 999;
}
.itemNo {
  font-size: 12px;
  line-height: 12px;
  height: 12px;
  text-align: right;
  color: #fff;
  margin-left: 20%;
  margin-bottom: 10px;
}
.timeprogress >>> .el-progress-bar__outer {
  background-color: #1890ff;
}
.timeprogress .el-progress-bar__inner {
  text-align: center;
}
.el-form-item >>> .el-form-item__label {
  color: #fff;
}
.el-form-item {
  margin-bottom: 0;
}

.tabTitle >>> .el-badge {
  position: relative;
  display: inline-block;
  vertical-align: baseline;
}
.badge {
  margin-top: 10px;
  margin-right: 20px;
}

.tableTransparent >>> .el-table,
.el-table__expanded-cell {
  background-color: transparent;
}
</style>
