<template>
  <div>
    <el-row :gutter="0" v-if="isLinkDisabled" style="margin-top: 15px">
      <el-col :span="2" align="left">
        <img v-if="logo" :src="logo" class="sidebar-logo"/>
      </el-col>

      <div>
        <el-form :model="formData" class="order-el-form" ref="formData" label-width="120px" >

          <el-col :span="18" style="margin-left: 0px" >
              <span style="font-size: 16px;color: #409EFF">当前工位:&nbsp&nbsp&nbsp&nbsp<span style="font-size: 16px;color: #000000">{{this.formData.workplaceName}}</span>
              &nbsp&nbsp&nbsp&nbsp
<!--                <span :style="{ color: formData.workplaceStatus === 0 ? 'green' : 'red' }"> ({{ formData.workplaceStatus === 0 ? '服务中' : '服务暂停' }} ) </span>-->
<!--                <el-button type="primary" @click="toggleWorkplaceStatus" style="margin-left: 10px;" >切换状态</el-button>-->
              </span>

              <span style="font-size: 16px;color: #409EFF;margin-left: 20px">当前业务类型:&nbsp&nbsp&nbsp&nbsp<span style="font-size: 16px;color: #000000">{{this.formData.busName}}</span>
              &nbsp&nbsp&nbsp&nbsp <el-button type="primary" @click="toggleBusType" style="margin-left: 10px;" >切换业务</el-button>
            </span>

          </el-col>

        </el-form>
      </div>

      <el-col :span="4" align="right" style="margin-top: 10px">
        <div class="inv-hos-title">
            <span
              style="margin: 10px;color: #2d8cf0;font-size: 14px;"
            >部门&nbsp:&nbsp{{ this.userInfo.deptName }}</span>
          <span
            style="font-weight: 500;color:rgb(51 48 48); font-size: 14px; margin-right: 20px"
          >&nbsp&nbsp&nbsp&nbsp(用户&nbsp:&nbsp{{
              this.userInfo.userName
            }})</span>
        </div>
      </el-col>

    </el-row>

    <el-row class="tac">
      <el-col :span="2">
        <!--      <h5>默认颜色</h5>-->
        <el-menu
          :default-active="menuActive"
          class="el-menu-vertical-demo"
          @open="handleOpen">
          <el-menu-item :index=0 @click="clickMenuItem(0)">
            <i class="el-icon-edit-outline"></i>
            <span slot="title">处理单据</span>
          </el-menu-item>

          <el-menu-item :index=4 @click="clickMenuItem(4)">
            <i class="el-icon-s-order"></i>
            <span slot="title">待处理单</span>
          </el-menu-item>
          <el-menu-item :index=5 @click="clickMenuItem(5)">
            <i class="el-icon-s-claim"></i>
            <span slot="title">已完成单</span>
          </el-menu-item>
          <el-menu-item :index=6 @click="clickMenuItem(6)">
            <i class="el-icon-upload"></i>
            <span slot="title">单据上传</span>
          </el-menu-item>
          <el-menu-item :index=1 @click="clickMenuItem(1)">
            <i class="el-icon-s-unfold"></i>
            <span slot="title">工位上货</span>
          </el-menu-item>
          <el-menu-item :index=2 @click="clickMenuItem(2)">
            <i class="el-icon-s-fold"></i>
            <span slot="title">工位退货</span>
          </el-menu-item>
          <el-menu-item :index=3 @click="clickMenuItem(3)">
            <i class="el-icon-s-platform"></i>
            <span slot="title">工位库存</span>
          </el-menu-item>
          <el-menu-item :index=7 @click="clickMenuItem(7)">
            <i class="el-icon-s-help"></i>
            <span slot="title">拆零管理</span>
          </el-menu-item>
          <el-menu-item :index=8 @click="clickMenuItem(8)">
            <i class="el-icon-warning"></i>
            <span slot="title">存量预警</span>
          </el-menu-item>
        </el-menu>
      </el-col>

      <el-col :span="22">
        <el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab"
                 @tab-click="upodateMenuActive"  @contextmenu.native.prevent="handleContextMenu">
          <el-tab-pane
            v-for="(item, index) in editableTabs"
            :key="item.name"
            :label="item.title"
            :name="item.name"
            @contextmenu.stop.prevent="handleTabContextMenu($event, item)"
            style="background-color: white"
          >
            <ul v-if="showContextMenu" class="context-menu" :style="contextMenuPosition">
              <li @click="closeAllTabs">关闭所有</li>
            </ul>
            <div >
              <component v-if="showChild" :is="item.component" v-bind="item.componentProps" :reset-key="resetKeys[item.name]" @parent-method="parentMethod" />
            </div>
          </el-tab-pane>
        </el-tabs>

      </el-col>
    </el-row>


    <el-dialog
      title="选择业务类型"
      :visible.sync="selectBusTypeDisabled"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      v-if="selectBusTypeDisabled"
      width="65%"
      append-to-body
    >
      <el-row>
        <!--          <el-button v-for="(item, index) in busTypeList" :key="index" type="primary" plain @click="selectBusType(item.code)">{{ item.name }}</el-button>-->

        <el-col v-for="(info, index)  in busTypeList" :key="index" :xs="12" :sm="8" :md="8" :lg="6">
          <el-card :body-style="{margin:'20px'}"
                   style="margin:20px 20px 20px 20px;height: 200px;background-color: #e1f3fb;border-radius: 12px; position: relative;"

          >

            <div
              style="display: flex; justify-content: space-between; align-items: center; height: 46px; /* 约为 200px 的 1/3 */"
              @click="selectBusType(info)">
              <p style="font-size: 20px;background-color: #e1f3fb;font-weight: bold;">{{ info.busName }}</p>
              <!-- 假设你的信息对象中包含一个title属性 -->
              <!--            <div style="width: 60px; height: 60px;  display: flex; justify-content: center; align-items: center;">-->
              <!--              &lt;!&ndash; 二维码占位，这里用灰色方块代替 &ndash;&gt;-->
              <!--&lt;!&ndash;              <span>QR</span>&ndash;&gt;-->
              <!--              <div ref="qrcode" :id="'qrcode-'+index" style="width: 60px;height: 60px;"></div>-->

              <!--            </div>-->
            </div>
            <div style="flex: 1; display: flex; flex-direction: column; justify-content: flex-end; padding-top: 10px;"
            >
              <!-- 假设这里有一些信息内容 -->
              <p style="font-size: 14px;background-color: #e1f3fb" @click="selectBusType(info)">
                {{ info.remark }}</p>
              <el-button type="primary" style="position: absolute; bottom: 20px; right: 20px;" icon="el-icon-thumb"
                         @click="selectBusType(info)">开始作业
              </el-button>

            </div>


          </el-card>
        </el-col>
      </el-row>
    </el-dialog>

  </div>


</template>

<script>
import logoImg from '@/assets/logo/logo_dm.png'
import DealOrder from '@/views/collect/DealOrder.vue'
import CollectOrderAllot from '@/views/collect/CollectOrderAllot.vue'
import CollectOrderEnd from '@/views/collect/CollectOrderEnd.vue'
import IoCreateOrderReturn from '@/views/collect/IoCreateOrder.vue'
import IoCreateOrderOut from '@/views/collect/IoCreateOrder.vue'
import ioSplitFifoCode from '@/views/collect/ioSplitFifoCode.vue'
import CollectOrderUpload from '@/views/collect/CollectOrderUpload.vue'
import IoDestroyOrder from '@/views/collect/IoDestroyOrder.vue'
import IoSplitFifoRemind from '@/views/collect/IoSplitFifoRemind.vue'
import {listPage,switchWorkplaceStatus} from "@/api/basic/workPlace/sysWorkplaceManage";
import {getWorkBindBusTypes, removeBusTypeById} from '@/api/basic/workPlace/sysWorkplaceDocuments'

export default {
  components: {
    DealOrder,
    IoCreateOrderReturn,
    IoCreateOrderOut,
    ioSplitFifoCode,
    CollectOrderAllot,
    CollectOrderEnd,
    CollectOrderUpload,
    IoDestroyOrder
  },
  name: 'CollectOrderTabs',
  data() {
    return {
      showContextMenu: false, // 控制上下文菜单的显示
      contextMenuPosition: { x: 0, y: 0 }, // 上下文菜单的位置
      selectBusTypeDisabled: false,
      selectWorkplaceStatusDisabled: false,
      busQuery: {
        busKey: '',
        workplaceCode: null,
        page: 1,
        limit: 100
      },
      formData: {
        busName: null,
        workplaceName: null,
        workplaceStatus: null
      },
      curWorkPlaces: [],
      busTypeList: [],
      logo: logoImg,
      isLinkDisabled: false,
      showChild: true,
      userInfo: {
        inv: this.$store.getters.locInvName,
        deptName: this.$store.getters.locDeptName,
        userName: this.$store.getters.user.employeeName,
        companyName: this.$store.getters.companyName
      },
      tabPosition: 'left',
      editableTabsValue: 'DealOrder',
      componentTables: [
        {
          number: 0,
          title: '处理单据',
          name: 'DealOrder',
          component: DealOrder,
          // 假设你需要传递的参数
          componentProps: {
            // title: '这是单据的标题',
          }
        },
        {
          number: 1,
          title: '工位上货',
          name: 'IoCreateOrderOut',
          component: IoCreateOrderOut,
          // 假设你需要传递的参数
          componentProps: {
            fromSplitType: 'out',
          }
        },
        {
          number: 2,
          title: '工位退货',
          name: 'IoCreateOrderReturn',
          component: IoCreateOrderReturn,
          // 假设你需要传递的参数
          componentProps: {
            fromSplitType: 'return'
          }
        },
        {
          number: 3,
          title: '工位库存',
          name: 'ioSplitFifoCode',
          component: ioSplitFifoCode,
          // 假设你需要传递的参数
          componentProps: {}
        },
        {
          number: 4,
          title: '待处理单',
          name: 'CollectOrderAllot',
          component: CollectOrderAllot,
          // 假设你需要传递的参数
          componentProps: {}
        },
        {
          number: 5,
          title: '已完成单',
          name: 'CollectOrderEnd',
          component: CollectOrderEnd,
          // 假设你需要传递的参数
          componentProps: {}
        },
        {
          number: 6,
          title: '单据上传',
          name: 'CollectOrderUpload',
          component: CollectOrderUpload,
          // 假设你需要传递的参数
          componentProps: {}
        },
        {
          number: 7,
          title: '拆零管理',
          name: 'IoDestroyOrder',
          component: IoDestroyOrder,
          // 假设你需要传递的参数
          componentProps: {}
        },
        {
          number: 8,
          title: '存量预警',
          name: 'IoSplitFifoRemind',
          component: IoSplitFifoRemind,
          // 假设你需要传递的参数
          componentProps: {}
        }],
      editableTabs: [{
        number: 0,
        title: '处理单据',
        name: 'DealOrder',
        component: DealOrder,
        // 假设你需要传递的参数
        componentProps: {
          // title: '这是单据的标题'
        }
      }
      ],
      tabIndex: 0,
      menuActive: 0,
      resetKeys: {}
    }
  },
  methods: {
    toggleWorkplaceStatus() {
      if (this.formData.workplaceStatus == 0){
        this.formData.workplaceStatus = 1
      }else {
        this.formData.workplaceStatus = 0
      }
      switchWorkplaceStatus(this.formData).then(resp => {
        if (resp.code == 20000){
          this.$message.success("切换成功!")

        }else {
          this.$message.error(resp.message)
          if (this.formData.workplaceStatus == 0){
            this.formData.workplaceStatus = 1
          }else {
            this.formData.workplaceStatus = 0
          }
        }
      }).catch(() => {

      })
    },
    toggleBusType() {
      //隐藏下拉框内容
      // this.$refs.selectHeadEmpId.blur();
      this.selectBusTypeDisabled = true
    },
    selectBusType(info) {
      let val = info.documentTypeCode
      this.formData.busType = val
      let newQuery = {...this.$route.query};
      delete newQuery.billNo;
      newQuery.busType = val
      this.$router.push({query: newQuery, path: this.$route.path});
      this.formData.busName = info.busName;
      this.editableTabs = []
      this.clickMenuItem(0)
      this.showChild = false;
      this.$nextTick(() => {
        this.showChild = true;
      });
      this.selectBusTypeDisabled = false
    },
    parentMethod(data) {
      const foundTab = this.findAllTabByName(data)
      this.clickMenuItem(foundTab.number)
      this.showChild = false;
      this.$nextTick(() => {
        this.showChild = true;
      });
    },
    upodateMenuActive(tab, event) {
      const foundTab = this.findTabByName(tab.name)
      if (foundTab) {
        // 如果找到了，执行一些操作
        this.menuActive = foundTab.number
        this.$set(this.resetKeys, foundTab.name, Date.now());
      }
    },
    clickMenuItem(val) {
      //分两种 一种已存在 一种未存在
      let item = this.componentTables[(val)]
      const foundTab = this.findTabByName(item.name)
      if (foundTab) {
        // 如果找到了，执行一些操作
        this.editableTabsValue = foundTab.name
        this.$set(this.resetKeys, foundTab.name, Date.now());
        this.menuActive = foundTab.number
      } else {
        // 如果没有找到，执行其他操作
        this.addTab(item)
      }

    },
    findTabByName(name) {
      // 使用find方法找到ID等于tabId的对象
      const tab = this.editableTabs.find(tab => tab.name === name)
      // 如果找到了，返回该对象；否则返回undefined
      return tab
    },
    findAllTabByName(name) {
      // 使用find方法找到ID等于tabId的对象
      const tab = this.componentTables.find(tab => tab.name === name)
      // 如果找到了，返回该对象；否则返回undefined
      return tab
    },
    addTab(item) {
      ++this.tabIndex
      this.editableTabs.push(item)
      this.editableTabsValue = item.name
      this.menuActive = item.number
    },
    removeTab(targetName) {
      let tabs = this.editableTabs
      let activeName = this.editableTabsValue

      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.name
              this.menuActive = nextTab.number
            }
          }
        })
      }

      this.editableTabsValue = activeName
      this.editableTabs = tabs.filter(tab => tab.name !== targetName)
    },
    //获取当前货位
    findCurWorkPlaces(val) {
      let query = {
        key: val,
        status: 1,
        // invCode: this.formData.invCode,
        page: 1,
        limit: 100,
      }
      listPage(query).then((res) => {
        this.curWorkPlaces = res.data.list || [];
       if (this.$route.query.workplaceId != null){
         let item = this.curWorkPlaces.find(item => item.workplaceId == this.$route.query.workplaceId);
         this.formData.workplaceName = item.workplaceName
         this.formData.workplaceStatus = item.workplaceStatus
       }
      })
    },
    getWorkBindBusTypes(workplaceId) {
      this.busQuery.workplaceCode = workplaceId
      getWorkBindBusTypes(this.busQuery).then(res => {
        if (res.code == 20000) {
          this.busTypeList = res.data.list
          this.busTypeTotal = res.data.total

          if (this.$route.query.busType != null) {
            this.formData.busType = this.$route.query.busType
            this.formData.busName = this.busTypeList.find(item => item.documentTypeCode == this.formData.busType).busName;
          }else  if (this.busTypeList.length == 1) {
              this.formData.busType = this.busTypeList[0].documentTypeCode
             this.$router.push({query: {...this.$route.query, busType: this.formData.busType}, path: this.$route.path})
              this.selectBusTypeDisabled = false
            this.formData.busName = this.busTypeList.find(item => item.documentTypeCode == this.formData.busType).busName;
            } else {
              this.selectBusTypeDisabled = true
              this.formData.busType = null
            }

        }
        return
      })
    },

    handleContextMenu() {
      this.showContextMenu = true;
    },
    handleTabContextMenu(event, tab) {
      this.showContextMenu = true;
      this.contextMenuTab = tab;
      this.contextMenuPosition = { x: event.clientX, y: event.clientY };
    },

    closeContextMenu() {
      this.showContextMenu = false;
      this.contextMenuStyle.display = 'none'; // 隐藏上下文菜单
    },
    closeCurrentTab(index) {
      // 关闭当前标签页的逻辑
      this.editableTabs.splice(index, 1); // 假设这是关闭标签页的方式
      this.editableTabsValue = this.editableTabs.length > 0 ? this.editableTabs[0].name : '';
      this.closeContextMenu();
    },
    closeOtherTabs() {
      // 关闭其他标签页的逻辑
      // ...
      this.closeContextMenu();
    },
    closeAllTabs() {
      // 关闭所有标签页的逻辑
      this.editableTabs = [];
      this.editableTabsValue = '';
      this.closeContextMenu();
    },

  },
  computed: {
    contextMenuPosition() {
      return {
        position: 'fixed', // 使用 fixed 定位确保它浮动在顶层
        left: `${this.contextMenuPosition.x}px`,
        top: `${this.contextMenuPosition.y}px`,
        zIndex: 1000, // 确保它在其他内容之上
        // 其他样式...
      };
    },
  },
  created() {
    this.findCurWorkPlaces();
    if (this.$route.query.workplaceId != null) {
      this.isLinkDisabled = true
      this.formData.workPlaceCode = Number(this.$route.query.workplaceId);
      this.formData.workplaceId = Number(this.$route.query.workplaceId);
      this.getWorkBindBusTypes(this.formData.workPlaceCode);
    }
  }
}
</script>

<style lang="css" scoped>
.sidebar-logo {
  width: 80px;
  height: 60px;
  vertical-align: middle;
  margin-left: 25px;
}
.context-menu {
  zIndex: 100000;
  position: fixed ;
  list-style-type: none;
  padding: 0;
  margin: 0;
  background-color: #f9f9f9;
  border: 1px solid #d4d4d4;
  border-radius: 4px;
  /* 其他样式... */
}

.context-menu li {
  padding: 8px 16px;
  cursor: pointer;
  /* 其他样式... */
}

.context-menu li:hover {
  background-color: #e1e1e1;
}

.rounded-box {
  border-radius: 10px;
  background-color: #f8f9fa; /* 浅灰色背景，可选 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 可选，添加阴影以增加立体感 */
  /*display: flex;*/
  /*flex-direction: column;*/
  /*align-items: center;*/
}


</style>
