<template>
  <basic-container>
    <el-tabs v-model="tabPosition" class="demo-tabs" @tab-change="tabPositionChange">
      <el-tab-pane label="库房设置" name="warehouseSetup">
        <avue-crud
          height="460px"
          :option="warehouseOption"
          :table-loading="loading"
          :data="data"
          v-model="form"
          v-model:page="page"
          ref="crud"
          @row-del="rowDel"
          @row-save="rowSave"
          @row-update="rowUpdate"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
        >
          <!-- <template #menu="{ row }">
            <el-button type="text" v-if="tabPosition == 'warehouseSetup'"
              >管理员设置</el-button
            >
          </template> -->
        </avue-crud>
      </el-tab-pane>
      <el-tab-pane label="库管设置" name="inventorySetup"></el-tab-pane>
      <el-tab-pane label="库位设置" name="storageSetup">
        <avue-crud
          height="460px"
          :option="storageOption"
          :table-loading="loading"
          :data="storageData"
          v-model="form"
          v-model:page="storagePage"
          ref="crud"
          @row-del="rowDel"
          @row-save="rowSave"
          @row-update="rowUpdate"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
        >
          <template #menu-left>
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </template>
          <!-- <template #menu="{ row }">
            <el-button type="text" v-if="tabPosition == 'warehouseSetup'">管理员设置</el-button>
          </template> -->
        </avue-crud>
      </el-tab-pane>
    </el-tabs>
    
    <div v-if="tabPosition == '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>
    <add-edit-dialog v-if="showDialog" :showDialog="showDialog" :title="dialogTitle"
    @closeDialog="closeDialog"></add-edit-dialog>
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import treeTransfer from 'tree-transfer-vue3' // 引入
// import treeTransfer from "./components/treeTransfer.vue";
import warehouseMain from "./js/warehouseMain";
import addEditDialog from "./components/addEditDialog.vue"
import {warehouseOption,storageOption} from "./js/warehouseMain";
import {getWareList,addWare,editWare,deleteWare,getLocationList,delLocation,
editLocation,getUserByRoleAlias,getWareByUser,getWareSelect,getUserByWare,saveUserWare,getAllUser,
saveWareUser} from "@/api/storeManagement/warehouseMaintenance";
export default {
  components: { addEditDialog,treeTransfer },
  data() {
    return {
      loading: false,
      tabPosition: "warehouseSetup",
      data: [],
      chooseWare:[],    //已选库房
      noChooseWare:[],  //未选库房
      noChooseUser:[],  //未选人员
      chooseUser:[],    //已选人员
      form: {},
      query:{},
      dialogTitle:'新增',
      checkUser:'',
      checkWare:"",
      selectLoading:false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      showDialog:false,
      storageData:[],
      warehouseOption:warehouseOption,
      storageOption:storageOption,
      storagePage:{
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        columnSort: true,
        tip: false,
        height: "auto",
        align: "center",
        calcHeight: 32,
        simplePage: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: true,
        selection: true,
        viewBtn: false,
        addBtn: true,
        delBtn: true,
        editBtn: true,
        editBtnIcon: " ",
        delBtnIcon: " ",
        labelWidth: 120,
        menu: true,
        menuWidth: 200,
        dialogWidth: 920,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: true,
        gridBtn: false,
        searchShowBtn: false,
        showOverflowTooltip: true,
        searchLabelPosition: "left",
        searchLabelPosition: "left",
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: "left",
        gridBtn: false,
        searchMenuPosition: "right",
        addBtnIcon: " ",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        column: [],
      },
      oldChooseUser:[],
      keepList:[],
      wareList:[],
      isUser: 1,
      localQuery:{},
    };
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  mounted() {
    console.log("this.userInfo",this.userInfo)
    this.option.delBtn = true;
    this.option.editBtn = true;
    this.option.column = warehouseMain[this.tabPosition];
    this.$nextTick(() =>{
      this.tabPositionChange()
    })
  },
  methods: {
    searchChange(params, done){
      if(this.tabPosition == "warehouseSetup"){
        this.query = params
        this.page.currentPage = 1;
        this.getWare()
        done()
      }else if(this.tabPosition == "storageSetup"){
        this.localQuery = params
        this.page.currentPage = 1;
        this.getLocation()
        done()
      }
    },
    searchReset(){
      if(this.tabPosition == "warehouseSetup"){
        this.query = {}
        this.getWare()
      }else if(this.tabPosition == "storageSetup"){
        this.localQuery = {}
        this.getLocation()
      }
    },
    currentChange(currentPage) {
      if(this.tabPosition == "warehouseSetup"){
        this.page.currentPage = currentPage;
        this.getWare()
      }else if(this.tabPosition == "storageSetup"){
        this.storagePage.currentPage = currentPage;
        this.getLocation()
      }
    },
    sizeChange(pageSize) {
      if(this.tabPosition == "warehouseSetup"){
        this.page.pageSize = pageSize;
        this.getWare()
      }else if(this.tabPosition == "storageSetup"){
        this.storagePage.pageSize = pageSize;
        this.getLocation()
      }
    },
    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) {
      this.isUser = val;
      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
        })
      }
    },
    addUser(fromData,toData,obj){
      console.log('fromData:', fromData)
      console.log('toData:', toData)
      console.log('obj:', obj)
    },
    
    // 选择人员
    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)
            })
          }
        })
      }
    },
    handleAdd() {
      this.dialogTitle = '新增'
      this.showDialog = true
    },
    getWare(){
      getWareList({
        current:this.page.currentPage,
        size:this.page.pageSize,
        ...this.query
      }).then(res =>{
        res.data.data.records.map(item =>{
          item.type = (item.type || item.type == 0)  ? item.type + '' : item.type
          item.toolingType = (item.toolingType || item.toolingType == 0)  ? item.toolingType + '' : item.toolingType
        })
        this.data = res.data.data.records
        this.page.total = res.data.data.total;
      })
    },
    getLocation(){
      getLocationList({
        current:this.storagePage.currentPage,
        size:this.storagePage.pageSize,
        ...this.localQuery
      }).then(res =>{
        this.storageData = res.data.data.records
        this.storagePage.total = res.data.data.total;
      })
    },
    tabPositionChange(val) {
      this.option.delBtn = false;
      this.option.editBtn = false;
      if (this.tabPosition == "warehouseSetup") {
        this.option.delBtn = true;
        this.option.editBtn = true;
        this.option.column = warehouseMain[this.tabPosition];
        this.getWare()
      } else if (this.tabPosition == "storageSetup") {
        this.option.delBtn = true;
        this.option.editBtn = true;
        this.option.column = warehouseMain[this.tabPosition];
        this.getLocation()
      }else if(this.tabPosition == "inventorySetup"){
        this.checkUser = ''
        getUserByRoleAlias({
          roleAlias:"保管员",
          current:1,
          size:99999
        }).then(res =>{
          this.keepList = res.data.data
        })
      }
    },
    rowDel(row) {
      this.$confirm("确定删除此条数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if(this.tabPosition == "warehouseSetup"){
          deleteWare({
            ids:row.id
          }).then(res =>{
            if(res.data.code == 200){
              this.$message.success('删除成功')
              this.getWare()
            }
          })
        }else if(this.tabPosition == "storageSetup"){
          delLocation({
            ids:row.id
          }).then(res =>{
            if(res.data.code == 200){
              this.$message.success('删除成功')
              this.getLocation()
            }
          })
        }
      });
    },
    rowSave(row, done, loading){
      if(this.tabPosition == "warehouseSetup"){
        addWare(row).then(res =>{
          if(res.data.code == 200){
            this.$message.success('新增成功')
            done()
            this.getWare()
          }
        }).catch(() =>{
          // loading()
          done()
        })
      }
    },
    rowUpdate(row, index, done, loading) { 
      if(this.tabPosition == "warehouseSetup"){
        console.log('row',row)
        editWare(row).then(res =>{
          if(res.data.code == 200){
            this.$message.success('修改成功')
            done()
            this.getWare()
          }
        })
      }else if(this.tabPosition == "storageSetup"){
        editLocation(row).then(res =>{
          if(res.data.code == 200){
            this.$message.success('修改成功')
            done()
            this.getLocation()
          }
        })
      }
    },
    closeDialog(val){
      console.log('val',val)
      this.showDialog = false
      if(val){
        this.getLocation()
      }
    },
    // onLoad() {
    //   this.data = [
    //     {
    //       id: 1,
    //       shCode: "001",
    //       shName: "名称一",
    //       memo: "",
    //       toolingTypeStr: "001",
    //       typeStr: "",
    //       shLevel: "",
    //       userName: "",
    //     },
    //     {
    //       id: 1,
    //       shCode: "001",
    //       shName: "名称一",
    //       memo: "",
    //       toolingTypeStr: "001",
    //       typeStr: "",
    //       shLevel: "",
    //       userName: "",
    //     },
    //     {
    //       id: 1,
    //       shCode: "001",
    //       shName: "名称一",
    //       memo: "",
    //       toolingTypeStr: "001",
    //       typeStr: "",
    //       shLevel: "",
    //       userName: "",
    //     },
    //   ];
    //   this.page.total = this.data.length;
    // },
  },
};
</script>
<style lang="scss" scoped>
::v-deep.trans_ware{
  .el-transfer-panel {
    width: 44.5% !important;

    .el-transfer-panel__body{
      height: 494px !important;
    }
  }
}


// ::v-deep.el-transfer {
//     .el-transfer-panel {
//         width: 44% !important;
//     }
// }

.setup-height {
  height: calc(100vh - 54px - 40px - 40px - 56px - 37px);
  ::v-deep .tree-transfer-vue3{
    height: 535px !important;

    .el-tree{
      height: 422px !important;
    }
  }
}
</style>
