<template>
  <div class="page-box" v-loading="loading">
    <div class="padKittingPackPage">
      <!-- 左侧按钮 -->
      <div class="leftBtns">
        <div 
          v-for="(item,index) of leftButtons" 
          :key="index"
          class="left-button"
          @click="getPageLockList(item)"
          :style="{
            background:(currentKittingInfo && (item.code==currentKittingInfo.code)?'#ff6000':'#409EFF'),
          }"
        >
          <p class="code">{{ item.code }}</p>
          <p class="name">{{ item.name }}</p>
        </div>
      </div>
      <!-- 整个右侧 -->
      <div class="rightBigBox">
        <div class="lockShadow" v-if="isLock">{{lockTip}}</div>
        <!-- 中间底盘号 -->
        <div class="centerChassisContain">
          <div class="title">底盘号</div>
          <ul class="chassisList" v-if="centerChassisList.length > 0">
            <li
              v-for="(item,index) of centerChassisList" 
              :style="{
                color:(item.canSelect?'#000':'#aaa'),
                cursor:(item.canSelect?'pointer':'no-drop'),
                background:(item.isSelect?'#bdddfd':'#fff'),
              }"
              :key="index"
              @click="selectCenterChassis(item,index)"
            >{{ item.chassisNumber }}</li>
          </ul>
          <div class="noDataTipper" v-if="centerChassisList.length <= 0">暂无数据</div>
          <div class="footer-button"><el-button :disabled="isLock" type="primary" @click="createChassisHandle()">创建底盘组</el-button></div>
        </div>
        <!-- 右侧底盘组 -->
        <div class="rightChassisGroup">
          <!-- 右上组 -->
          <div class="rightTopTable">
            <el-table
              :border="true"
              :data="rightTopChassisGroup"
              :height="'100%'"
              :header-cell-style="{ background: '#e3f0ff',color:'#333'}"
              style="width: 100%">
              <el-table-column
                prop="chassisNumber"
                label="底盘组"
              ></el-table-column>
              <el-table-column
                prop="creationTime"
                label="时间"
              >
                <template slot-scope="scope">
                  {{ formatDate(scope.row.creationTime) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 右下bom -->
          <div class="rightBottomBomData">
            <el-table
              :border="true"
              :data="rightBottomBomData"
              :header-cell-style="{ background: '#e3f0ff',color:'#333'}"
              style="width: 100%">
              <el-table-column
                prop="itemCode"
                label="Kitting组别Bom"
              ></el-table-column>
              <el-table-column
                prop="qty"
                label="底盘组物品数量"
              ></el-table-column>
              <!-- todo: Kiting组数量字段确定-->
              <el-table-column
                prop="qty1"
                label="Kiting组数量"
              ></el-table-column>
            </el-table>
          </div>
          <div class="footer-button">
            <el-button :disabled="isLock"  type="success" @click="finishChassisHandle">完成该组底盘</el-button>
            <el-button class="flesh-btn" type="warning" @click="initData">刷新数据</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getPageList,postCreate } from '@/api/wms-api'
import { ChassisGetListWithNextCount,pageLockToLogin,pageLockToLogout } from '@/api/wms-pad'
import { formatTimeStrToStr } from "@/utils/formatTime"
import store  from '@/store'
export default {
  name: "padKittingPack",
  data() {
    return {
      loading:false,
      // 循环数据定时器
      intervalId:false,
      // 当前左侧按钮选择信息
      currentKittingInfo:null,
      // 左侧按钮
      leftButtons:[],
      // 中间底盘号
      centerChassisList:[],
      // 右上方组数据
      rightTopChassisGroup:[],
      // 右下方组bom数据
      rightBottomBomData:[],
      // 是否已经被锁定
      isLock:false,
      // 锁定提示
      lockTip:'该菜单已有用户锁定',
    };
  },
  mounted(){
    this.initData()
    clearInterval(this.intervalId)
    //刷新数据
    this.intervalId = setInterval(() => {
      this.initData()
    }, localStorage.getItem('padKittingPackUpdate') || 180000)
  },
  destroyed() {
    clearInterval(this.intervalId)
  },
  methods:{
    initData(){
      this.getKittingList()
    },
    // 格式化时间
    formatDate (time) {
      if (time == null) {
        return '-'
      }
      return formatTimeStrToStr(time)
    },
    // 左侧按钮点击事件 -获取是否锁定
    getPageLockList(selectItem){
      let _data = {
        condition: {
          filters: [
            {
              logic: "And",
              column: "menuCode",
              action: "==",
              value: this.$route.name + '_' + selectItem.code,
            },
            {
              logic: "And",
              column: "userAccount",
              action: "!=",
              value: store.getters.name.name,
            }
          ]
        },
        Sorting: "",
        SkipCount: 0,
        MaxResultCount: 9999,
      }
      this.loading = true
      getPageList(_data, 'auth/auth/page-lock').then(res => {
        this.currentKittingInfo = selectItem;
        // 未锁定
        if(res.items.length <= 0){
          this.isLock = false
          this.lockUserHandle()
        }
        // 已锁定
        else{
          this.isLock = true
          this.initKittingData()
        }
      }).catch(err => {
        this.loading = false
      })
    },
    // 锁定账号
    lockUserHandle(){
      let _data = {
        menuCode:this.$route.name + '_' + this.currentKittingInfo.code,
        userAccount:store.getters.name.name,
      }
      pageLockToLogin(_data)
        .then(res=>{
          this.initKittingData()
        })
        .catch(err=>{})
    },
    // 退出账号todo:批量将当前账号所有的绑定菜单删除
    async LogoutUserHandle(e){
      let _data = {
        menuCode:this.$route.name + '_' + this.currentKittingInfo.code,
        userAccount:store.getters.name.name,
      }
      pageLockToLogout(_data)
        .then(res=>{})
        .catch(err=>{})
    },
    // 获取kitting
    getKittingList(){
      let _data = {
        condition: {
          filters: []
        },
        Sorting: "code ASC",
        SkipCount: 0,
        MaxResultCount: 9999,
      }
      this.loading = true
      getPageList(_data, 'basedata/kitting',true).then(res => {
        this.leftButtons = res.items
        // 如果有当前选择kitting数据，默认点击重置
        if(this.currentKittingInfo){
          this.getPageLockList(this.currentKittingInfo)
        }else{
          this.loading = false
        }
      }).catch(err => {
        this.loading = false
      })
    },
    // 获取中间数据 及初始化数据
    initKittingData(){
      let _data = {
        count:30,
        kittingCode:this.currentKittingInfo.code
      }
      this.loading = true
      // 获取中间数据
      ChassisGetListWithNextCount(_data).then(res => {
        this.centerChassisList = []
        this.rightTopChassisGroup = []
        // 初始化中间和右侧数据数据：
        // 如果不够chassisQty条，则不分开
        if(res.items.length<Number(this.currentKittingInfo.chassisQty)){
          this.centerChassisList = res.items
        }
        // 如果够chassisQty条:前三条数据，放到右上方，第四条数据开始显示在中间位置
        else{
          res.items.forEach((item,index)=>{
            if(index < Number(this.currentKittingInfo.chassisQty)){
              this.rightTopChassisGroup.push(item)
            }else{
              item.isSelect = false
              item.canSelect = false
              this.centerChassisList.push(item)
            }
          })
        }
        this.centerChassisList[0].canSelect = true
        this.rightBottomBomData = this.currentKittingInfo.details
        this.loading = false
      }).catch(err => {
        this.loading = false
      })
    },
    // 点击选中中间数据
    selectCenterChassis(selectItem,selectIndex){
      for(let i=0;i<this.centerChassisList.length;i++){
        // 选中
        if(selectItem.isSelect == false){
          if(selectIndex == 0 || this.centerChassisList[selectIndex - 1].isSelect){
            this.centerChassisList[selectIndex].isSelect = true
            this.centerChassisList[selectIndex].canSelect = true
            if(this.centerChassisList[selectIndex+1])this.centerChassisList[selectIndex+1].canSelect = true
          }
          return
        }
        // 取消选中
        else{
          this.centerChassisList.forEach((item,index)=>{
            if(Number(index) >= Number(selectIndex)){
              item.canSelect = false
              item.isSelect = false
            }
          })
          this.centerChassisList[selectIndex].canSelect = true
          return
        }
      }
    },
    // 创建底盘组操作
    createChassisHandle(){
      if(this.isLock)return
      let _selectItems = this.centerChassisList.filter(item=>{return item.isSelect})
      if(!_selectItems || _selectItems.length <= 0){
        this.$warningMsg("请选择至少一项")
        return
      }
      let _selectChassisNumber = []
      _selectItems.forEach(item=>{ if(item.isSelect)_selectChassisNumber.push(item.chassisNumber)})
      let _msg = `是否确定将底盘号 (${_selectChassisNumber.join(",")}) 移入底盘组`
      this.$confirm(_msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 中间数据移除已选项
        this.centerChassisList = this.centerChassisList.filter(item => !_selectChassisNumber.includes(item.chassisNumber))
        // 右侧数据添加已选
        this.rightTopChassisGroup = [
          ...this.rightTopChassisGroup,
          ..._selectItems
        ]
      }).catch(() => {
      });
    },
    // 完成该组底盘
    finishChassisHandle(){
      if(this.isLock)return
      this.$confirm('是否确定完成该组底盘', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _data = {
          extraProperties: {},
          worker: store.getters.name.userName,
          kittingCode: this.currentKittingInfo.code,
          depDetails: [],//右上数据
          details: [],//右下数据
        }
        // 右上数据、depDetails
        this.rightTopChassisGroup.forEach(item=>{
          let _item = {
            itemCode: item.itemCode,
            itemName: item.itemName,
            itemDesc1: item.itemDesc1,
            itemDesc2: item.itemDesc2,
            chassisNumber: item.chassisNumber,//底盘组
            kittingCode: this.currentKittingInfo.code,//左侧按钮code
            chassisSortNumber: item.sortNumber,//sortNumber
          }
          _data.depDetails.push(_item)
        })
        // 右下数据、details
        this.rightBottomBomData.forEach(item=>{
          let _item = {
            itemCode: item.itemCode,
            itemName: item.itemName,
            itemDesc1: item.itemDesc1,
            itemDesc2: item.itemDesc2,
            qty: item.qty,
            kittingCode: this.currentKittingInfo.code
          }
          _data.details.push(_item)
        })
        this.finishHandleHttp(_data)
      }).catch(() => {
      });
      
    },
    finishHandleHttp(_data){
      console.log(286,_data)
      return
      this.loading = true
      postCreate(_data, 'wms/store/KittingPackagingNote').then(res => {
        this.initData()
        this.loading = false
      }).catch(err => {
        this.loading = false
      })
    }
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/mainbasicData.scss";
$boxPadding:15px;
$boxBorder:#ddd solid 1px;
$footerBtn_height:60px;
.page-box{
  overflow:auto;
  background:#f8f8f8;
  padding:10px
}
.padKittingPackPage{
  min-width:1000px;
  height:100%;
  display:flex;
  .leftBtns{
    width:15%;
    min-width:150px;
    border:$boxBorder;
    padding:$boxPadding;
    flex-shrink:0;
    height:100%;
    overflow:auto;
    background:#fff;

    .left-button{
      flex-wrap: wrap;
      display:flex;
      width:100%;
      height:90px;
      background:#409EFF;
      color:#fff;
      margin:15px 0;
      border-radius:12px;
      text-align:center;
      cursor:pointer;
      align-content: center;

      &:hover{
        opacity:0.8
      }

      p{
        width:100%;
        flex-shrink:0;
        margin:0;
        padding:0 10px;

        &.code{
          font-size:20px
        }

        &.name{
          overflow: hidden;
          word-break: break-all;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          font-size:14px;
        }
      }
    }
  }
  .rightBigBox{
    display:flex;
    width:100%;
    position:relative;

    .lockShadow{
      position:absolute;
      left:0;
      right:0;
      top:0;
      bottom:0;
      background:rgba(255,255,255,0.7);
      z-index:100;
      text-align:center;
      line-height:50vh;
      cursor:no-drop;
      color:#ff6000
    }
  }
  .centerChassisContain{
    position:relative;
    width:calc(35% - 20px);
    min-width:260px;
    border:$boxBorder;
    padding:$boxPadding;
    height:100%;
    overflow:auto;
    margin:0 10px;
    background:#fff;

    $title_height:40px;
    .title{
      position:absolute;
      top:0;
      left:0;
      right:0;
      text-align:center;
      line-height:$title_height;
      height:$title_height;
      overflow:hidden
    }

    .chassisList,.noDataTipper{
      position:absolute;
      top:$title_height;
      left:0;
      right:0;
      bottom:$footerBtn_height;
      overflow:auto;
      padding:0;
      margin:0;

      li{
        margin:10px;
        padding:5px 15px;
        list-style:none;
      }
    }
    .noDataTipper{
      color:#909399;
      line-height:60px;
      text-align:center;
      font-size:14px;
    }
  }
  .rightChassisGroup{
    position:relative;
    width:65%;
    min-width:600px;
    border:$boxBorder;
    padding:$boxPadding;
    height:100%;
    overflow:auto;
    background:#fff;

    .rightTopTable{
      position:absolute;
      top:0;
      left:0;
      right:0;
      height:40%;
      overflow:auto;
    }

    .rightBottomBomData{
      position:absolute;
      top:calc(40% + 10px);
      left:0;
      right:0;
      bottom:$footerBtn_height;
      overflow:auto;
      border-top:$boxBorder;
    }
  }
  .footer-button{
    position:absolute;
    bottom:0;
    left:0;
    right:0;
    text-align:center;
    border-top:$boxBorder;
    height:$footerBtn_height;

    .el-button{
      width:180px;
      margin-top:10px
    }

    .flesh-btn{
      position:absolute;
      right:15px;
      width:100px
    }
  }
}
</style>