<template>
  <basic-container>
    <el-tabs v-model="activeName" @tab-change="tabPositionChange">
      <el-tab-pane label="库房设置" name="warehouseSetup"></el-tab-pane>
      <el-tab-pane label="库管设置" name="inventorySetup"></el-tab-pane>
      <el-tab-pane label="库位设置" name="storageSetup"></el-tab-pane>
    </el-tabs>
    <warehouse v-if="activeName == 'warehouseSetup'"></warehouse>
    <inventory v-if="activeName == 'storageSetup'"></inventory>
    <div v-if="activeName == 'inventorySetup'" class="setup-height">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="selectFn(1)">按人员设置</el-button>
        <el-button type="primary" @click="selectFn(2)">按库房设置</el-button>
      </div>
      <el-select
        v-model="checkUser"
        filterable
        remote
        reserve-keyword
        placeholder="请输入人员名称"
        :remote-method="remoteMethod"
        :loading="selectLoading"
        v-if="isUser == 1"
        @change="changeUser"
      >
        <el-option v-for="item in keepList" :key="item.id" :label="item.realName" :value="item.id">
        </el-option>
      </el-select>
      <el-select
        style="margin-bottom: 10px"
        v-model="checkWare"
        placeholder="请选择库房"
        v-if="isUser == 2"
        @change="changeWare"
      >
        <el-option v-for="item in wareList" :key="item.id" :label="item.shName" :value="item.id">
        </el-option>
      </el-select>
      <el-transfer
        class="trans_ware"
        v-if="isUser == 1"
        style="margin-top: 10px"
        filterable
        :titles="['未选择', '已选择']"
        :filter-method="filterMethod"
        filter-placeholder="请输入库房"
        v-model="chooseWare"
        :data="noChooseWare"
      >
      </el-transfer>
      <tree-transfer
        class="trans_ware"
        style="margin-top: 10px"
        v-if="isUser == 2"
        ref="transferRef"
        :titleList="['未选择', '已选择']"
        v-model:fromData="noChooseUser"
        v-model:toData="chooseUser"
        :defaultProps="{
          id: 'id', // 节点id
          parentId: 'parentId', // 父节点id
          label: 'label',
          children: 'children',
          disabled: 'disabled',
        }"
        rootPid="0"
      />
      <!-- <transferTree v-if="isUser == 2"></transferTree> -->
      <!-- <treeTransfer :noChoose="noChooseUser" :choose="chooseUser" style="margin-top:10px;" v-if="isUser == 2"></treeTransfer> -->
      <div style="margin-top: 10px; display: flex; justify-content: center; align-items: center">
        <el-button type="primary" @click="handleSubmit">保 存</el-button>
      </div>
    </div>
  </basic-container>
</template>

<script>
import warehouse from './components/warehouse.vue';
import inventory from './components/inventory.vue';
import { mapGetters } from 'vuex';
import treeTransfer from 'tree-transfer-vue3'; // 引入
import {
  getWareList,
  addWare,
  editWare,
  deleteWare,
  getLocationList,
  delLocation,
  editLocation,
  getUserByRoleAlias,
  getWareByUser,
  getWareSelect,
  getUserByWare,
  saveUserWare,
  getAllUser,
  saveWareUser,
  getMaterialSelect,
} from '@/api/storeManagement/warehouseMaintenance';
export default {
  components: { warehouse, inventory, treeTransfer },
  data() {
    return {
      activeName: 'warehouseSetup',
      loading: false,
      tabPosition: 'warehouseSetup',
      data: [],
      chooseWare: [], //已选库房
      noChooseWare: [], //未选库房
      noChooseUser: [], //未选人员
      chooseUser: [], //已选人员
      goodsList: [],
      goodsLoading: false,
      form: {},
      query: {},
      dialogTitle: '新增',
      checkUser: '',
      checkWare: '',
      selectLoading: false,
      showDialog: false,
      storageData: [],
      oldChooseUser: [],
      keepList: [],
      wareList: [],
      isUser: 1,
      localQuery: {},
    };
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  mounted() {},
  methods: {
    tabPositionChange(val) {
      console.log('11111111111111111111111111111111',val)
      this.activeName = val;
      if (val == 'inventorySetup') {
        // this.isUser = 1;
        // this.chooseWare = [];
        // this.noChooseWare = [];
        // this.checkUser = '';
        // getUserByRoleAlias({
        //   roleAlias: '保管员',
        //   current: 1,
        //   size: 99999,
        // }).then(res => {
        //   this.keepList = res.data.data;
        // });
        this.selectFn(1)
        console.log('this.activeName', this.activeName)
      }
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectLoading = true;
        getUserByRoleAlias({
          current: 1,
          size: 9999,
          realName: query,
          roleAlias: '保管员',
        }).then(res => {
          this.keepList = res.data.data;
          this.selectLoading = false;
        });
      } else {
        // this.options = [];
        getUserByRoleAlias({
          current: 1,
          size: 9999,
          roleAlias: '保管员',
        }).then(res => {
          this.keepList = res.data.data;
        });
      }
    },
    selectFn(val) {
      console.log('val-------------',val)
      this.isUser = val;
      console.log('isUser', this.isUser)
      if (val == 1) {
        this.checkUser = '';
        this.chooseWare = [];
        this.noChooseWare = [];
        getUserByRoleAlias({
          current: 1,
          size: 999999,
          roleAlias: '保管员',
        }).then(res => {
          this.keepList = res.data.data;
        });
      } else {
        this.checkWare = '';
        this.chooseUser = [];
        this.noChooseUser = [];
        getWareSelect().then(res => {
          this.wareList = res.data.data.records;
        });
      }
    },
    // 选择人员
    changeUser(val) {
      getWareByUser(val).then(res => {
        let chooseData = res.data.data.Choose;
        let noChooseData = res.data.data.NoChoose;
        chooseData.map(item => {
          item.key = item.id;
        });
        noChooseData.map(item => {
          item.key = item.id;
        });
        this.noChooseWare = [...chooseData, ...noChooseData];
        console.log('NoChoose------------', this.noChooseWare);
        this.chooseWare = chooseData.map(item => item.key);
        console.log('chooseWare------------', this.chooseWare);
      });
    },
    processTree(nodes, isRootLevel = true) {
      return nodes.map(item => {
        // 第一层：parentId = 0；其他层：parentId = item.pid
        const parentId = isRootLevel ? 0 : item.pid;

        const newItem = {
          ...item,
          parentId, // 添加 parentId 字段
          // 注意：保留原有的 pid 字段，除非你不需要
        };

        // 递归处理 children，下一层不再是根层
        if (Array.isArray(item.children)) {
          newItem.children = this.processTree(item.children, false);
        }

        return newItem;
      });
    },
    // 选择仓库
    changeWare(val) {
      getUserByWare(val).then(res => {
        this.chooseUser = this.processTree(res.data.data.Choose);
        // this.oldChooseUser = JSON.parse(JSON.stringify(this.chooseUser))
        // console.log('oldChooseUser------------',this.oldChooseUser)
        this.noChooseUser = this.processTree(res.data.data.NoChoose);
      });
    },
    getLeafIds(nodes) {
      const leafIds = [];

      function traverse(items) {
        if (!Array.isArray(items)) return;

        items.forEach(item => {
          // 判断是否为叶子节点
          const hasChildren = Array.isArray(item.children) && item.children.length > 0;

          if (!hasChildren) {
            // 是叶子节点，收集 id
            leafIds.push(item.id);
          } else {
            // 有子节点，继续递归
            traverse(item.children);
          }
        });
      }

      traverse(nodes);
      return leafIds;
    },
    handleSubmit() {
      if (this.isUser == 1) {
        let params = {
          userId: this.checkUser,
          shIdList: this.chooseWare,
        };
        saveUserWare(params).then(res => {
          if (res.data.code == 200) {
            this.$message.success('保存成功');
            getWareByUser(this.checkUser).then(res => {
              let chooseData = res.data.data.Choose;
              let noChooseData = res.data.data.NoChoose;
              chooseData.map(item => {
                item.key = item.id;
              });
              noChooseData.map(item => {
                item.key = item.id;
              });
              this.noChooseWare = [...chooseData, ...noChooseData];
              this.chooseWare = chooseData.map(item => item.key);
            });
          }
        });
      } else {
        let userArr = this.getLeafIds(this.chooseUser).map(item => item.replace('user-', ''));
        userArr.push(this.userInfo && this.userInfo.userId);
        // let oldUserArr = this.getLeafIds(this.oldChooseUser).map(item => item.replace('user-',""))
        // console.log('userArr',userArr)
        // console.log('oldUserArr',oldUserArr)
        // // 将 arr1 转为 Set，提高查找效率
        // const set1 = new Set(oldUserArr);

        // // 过滤 arr：只保留不在 set1 中的元素
        // const result = userArr.filter(item => !set1.has(item));
        // console.log('result---------',result)
        let params = {
          shId: this.checkWare,
          userIdList: userArr.join(','),
        };
        console.log('choos---------', this.getLeafIds(this.chooseUser));
        console.log('params==========', params);
        saveWareUser(params).then(res => {
          if (res.data.code == 200) {
            this.$message.success('保存成功');
            getUserByWare(this.checkWare).then(res => {
              this.chooseUser = this.processTree(res.data.data.Choose);
              // this.oldChooseUser = JSON.parse(JSON.stringify(this.chooseUser))
              this.noChooseUser = this.processTree(res.data.data.NoChoose);
            });
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep.trans_ware {
  .el-transfer-panel {
    width: 44.2% !important;

    .el-transfer-panel__body {
      height: calc(100vh - 54px - 40px - 40px - 56px - 37px - 140px) !important;
      min-height: 300px !important;
      max-height: calc(100vh - 54px - 40px - 40px - 56px - 37px - 140px) !important;

      .el-transfer-panel__list {
        height: 100% !important;
      }
    }
  }
}

.setup-height {
  height: calc(100vh - 54px - 40px - 40px - 56px - 37px);
  min-height: 500px;

  ::v-deep .tree-transfer-vue3 {
    height: calc(100vh - 54px - 40px - 56px - 37px - 140px) !important;
    min-height: 320px !important;
    max-height: calc(100vh - 54px - 40px - 56px - 37px - 140px) !important;

    .el-tree {
      height: 100% !important;
      max-height: calc(100% - 20px) !important;
    }
  }
}
</style>