<template>
  <!-- 类型管理 -->
  <div class="app-container" id="toolsType">
    <el-row :gutter="20">
      <!--树数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="peopleName"
            placeholder="请输入人员名称"
            clearable
            maxlength="50"
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container" style>
          <div class="grid-content bg-purple-dark" align="left">组织人员树</div>
          <el-tree
            style="height: 700px; overflow: scroll"
            :data="treeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :render-content="renderConent"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          ></el-tree>
        </div>
      </el-col>
      <!--树数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="typeName"
            placeholder="请输入类型名称"
            clearable
            maxlength="50"
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container" style>
          <div class="grid-content bg-purple-dark" align="left">物资类型树</div>
          <el-tree
            style="height: 700px; overflow: scroll"
            :data="treeOptionsTwo"
            :props="defaultPropsTwo"
            :expand-on-click-node="false"
            :filter-node-method="filterNodeTwo"
            ref="treeTwo"
            node-key="id"
            :default-expand-all="false"
            highlight-current
            @node-click="handleNodeClickTwo"
          ></el-tree>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="16" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="关键字" prop="keyword">
            <el-input
              v-model="queryParams.keyword"
              placeholder="请输入关键字"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleBind">绑定</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-minus" size="mini" @click="handleNoBind">解绑</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              >导出
            </el-button>
          </el-col> -->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="typeList"
          ref="multipleTable"
          row-key="rowKey"
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
          @select="handlerSelect"
          @select-all="handlerSelectAll"
          style="max-height: 650px; overflow: auto"
        >
          <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
          <el-table-column width="60" align="center" label="序号" type="index">
            <template slot-scope="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="施工类型" align="center" show-overflow-tooltip prop="typeName"></el-table-column>
          <!-- <el-table-column
            label="物资类型"
            align="center"
            show-overflow-tooltip
            width="100"
            prop="materialType"
          ></el-table-column>
          <el-table-column label="物资名称" align="center" show-overflow-tooltip prop="materialName"></el-table-column>
          <el-table-column label="规格型号" align="center" show-overflow-tooltip prop="typeName"></el-table-column> -->
          <el-table-column label="人员" align="center" prop="keeperUserName" show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-if="scope.row.keeperUserName == null" style="color: red">
                {{ '请绑定' }}
              </div>
              <div v-else>
                {{ scope.row.keeperUserName }}
              </div>
              <!-- <div v-else style="color: red;"></div> -->
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="130">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-user-solid"
                @click="handleUpdateKeep(scope.row)"
                v-if="scope.row.keeperUserName != null"
              >
                库管解绑
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
          :page-sizes="[9999]"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

import { getUserByRoleList, getMaUserList } from '@/api/system/user'
import { getMaTypeList, queryKeeperDataApi, queryKeeperProApi, getListByMaType } from '@/api/ma/base'
import { bindKeeper, noBindKeeper, getKeeperIds } from '@/api/ma/typeConfigKeeper'
import { getPersonSettingListApi, bindPersonSettingApi, unBindPersonSettingApi } from '@/api/ma/person-setting'
import { getUserList } from '@/api/basic/basic'
import { getInfo } from '@/api/login'
import { downloadFile } from '@/utils/download'
export default {
  name: 'TypeConfigKeeper',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totalTemp: 0,
      countTemp: 1,
      totalAll: 0,
      // 库管员用户数据
      keeperList: null,
      keeperDataRange: [],
      keeperProRange: [],
      keeperMatRange: [],
      keeperNameRange: [],
      //维修员用户数据
      repairUserList: null,
      //资产类型数据
      propList: null,
      // 类型名称
      typeName: undefined,
      // 人员名称
      peopleName: undefined,
      // 树选项
      treeOptions: undefined,
      // 树选项
      treeOptionsTwo: undefined,
      //列表数据
      typeList: undefined,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: '',
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      chosenTypeId: '',
      leasePrice: '',

      fileList: [],

      defaultProps: {
        children: 'children',
        label: 'label'
      },
      defaultPropsTwo: {
        children: 'children',
        label: 'label'
      },
      roleIdsTemp: [],
      userList: [],
      userNoList: [],
      userIdTemp: -1,
      typeIdTemp: -1,
      maxLength: 100, //已选列表上限，防止数据过多请求报错
      // 查询参数
      queryParams: {
        typeName: '',
        level: 0,
        pageNum: 1,
        pageSize: 9999,
        displayBindRelationship: true,
        houseId: '',
        keyword: ''
        // phonenumber: undefined,
        // status: undefined,
        // typeId: undefined
      },

      configOpen: false,
      cform: {
        price: '',
        afterPrice: '',
        useDate: ''
      },
      isAllSelect: false,
      selectionRows: []
    }
  },
  // mounted(){
  //   this.selectFirstNode();
  // },
  watch: {
    // 根据名称筛选部门树
    typeName(val) {
      this.$refs.treeTwo.filter(val)
    },
    // 根据名称筛选人员树
    peopleName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getTreeData()
    this.getTreeDataTwo()
  },
  methods: {
    selectFirstNode() {
      const firstNode = this.$refs.treeTwo.getNode(1)
      if (firstNode) {
        this.queryParams.typeId = firstNode.id
        this.queryParams.level = 0
        this.queryParams.houseId = firstNode.id
        this.$refs.treeTwo.setChecked(firstNode, true)
      }
    },

    renderConent(h, { node }) {
      let iconClass = ''
      // 根据 node 的类型判断图标
      if (node.data.level == 99) {
        iconClass = 'el-icon-user-solid'
      }

      return (
        <span>
          <i class={iconClass}></i> {node.label}
        </span>
      )
    },

    /** 查询物资类型 */
    async getKeeperDataList(data) {
      let keepdataRes = await queryKeeperDataApi({
        // typeId:data.keeperData
      })
      this.keeperDataRange = keepdataRes.data.map(item => {
        return {
          label: item.houseName,
          value: item.houseId
        }
      })
      this.form.keeperData = this.keeperDataRange.value
    },

    async getKeeperDataListTemp(data) {
      let keepdataRes = await queryKeeperDataApi({
        // typeId:data.keeperData
      })
      this.keeperDataRange = keepdataRes.data.map(item => {
        return {
          label: item.houseName,
          value: item.houseId
        }
      })
      // this.form.keeperData = this.keeperDataRange.value

      let keepproRes = await queryKeeperProApi({
        houseId: data.keeperDataPro
      })
      this.keeperProRange = keepproRes.data.map(item => {
        return {
          label: item.typeName,
          value: item.typeId
        }
      })
      this.form.keeperDataPro = this.keeperProRange.value
    },
    /** 查询新增页面-上级类型下拉树结构 */
    async getTreeData() {
      const itemName = 'ku_guan_role_ids'
      await getKeeperIds(itemName).then(response => {
        const roleIds = response.rows[response.rows?.length - 1].itemValue.split(',').map(item => Number(item))
        this.roleIdsTemp = roleIds
      })
      await getUserList({ roleIds: this.roleIdsTemp }).then(response => {
        this.treeOptions = response.data
      })
    },
    /** 查询新增页面-上级类型下拉树结构 */
    async getTreeDataTwo() {
      getMaTypeList().then(response => {
        // this.treeOptionsTwo = response.data
        this.treeOptionsTwo = response.data.map(item => this.filterTreeData(item))
        console.log('🚀 ~ getMaTypeList ~ this.treeOptionsTwo:', this.treeOptionsTwo)
        if (this.treeOptionsTwo?.length > 0 && this.treeOptionsTwo[0]?.children?.length > 0) {
          const firstNode = this.treeOptionsTwo[0].children[0]
          this.queryParams.typeId = firstNode.id
          this.queryParams.level = 1
          this.queryParams.houseId = firstNode.houseId
          this.getList()
        }
      })
    },

    filterTreeData(data, maxLevel = 1, currentLevel = 1) {
      if (currentLevel > maxLevel) {
        return { ...data, children: undefined } // 移除子级
      }
      return {
        ...data,
        children: data.children?.map(child => this.filterTreeData(child, maxLevel, currentLevel + 1))
      }
    },
    /** 查询列表 */
    async getList() {
      this.loading = true
      this.queryParams.displayBindRelationship = 'true'
      console.log('queryParams1', this.queryParams)
      await getPersonSettingListApi(this.queryParams)
        .then(response => {
          console.log('response', response)
          this.typeList = response.rows
          this.total = response.total
          this.loading = false
          if (this.typeList.length > 0) {
            this.typeList.forEach((item, index) => {
              item.rowKey = item.typeId + '_' + index
            })
          }
        })
        .catch(error => {
          console.log('🚀 ~ 列表 ~ error:', error)
          this.loading = false
        })
    },
    // 筛选节点 - 左侧树
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件 - 左侧树
    handleNodeClick(data, node) {
      // this.queryParams.level = data.level
      // this.handleQuery();
      this.$refs.multipleTable.clearSelection()
      this.userIdTemp = data.id
      this.queryParams.userId = data.id
      this.handleQuery()
    },
    // 筛选节点 - 左侧树
    filterNodeTwo(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件 - 左侧树
    async handleNodeClickTwo(data, node) {
      if (data.level == 0) {
        this.queryParams.typeId = data.id
        this.queryParams.level = data.level
        this.queryParams.houseId = data.id
      } else {
        this.queryParams.typeId = data.id
        this.queryParams.level = data.level
        this.queryParams.houseId = data.houseId
      }
      this.handleQuery()
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        photoUrl: '',
        photoName: '',
        documentUrl: '',
        documentName: '',
        parentId: ''
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    async handleQuery() {
      // this.queryParams.pageNum = 1;
      this.$refs.multipleTable.clearSelection()
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.queryParams.typeId = undefined
      this.queryParams.userId = undefined
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 9999
      this.queryParams.level = 1
      this.$refs.tree.setCurrentKey(null)
      this.$refs.treeTwo.setCurrentKey(null)
      if (this.treeOptionsTwo.length > 0 && this.treeOptionsTwo[0]?.children?.length > 0) {
        const firstNode = this.treeOptionsTwo[0].children[0]
        this.queryParams.typeId = firstNode.id
        this.queryParams.level = 1
        this.queryParams.houseId = firstNode.houseId
        this.getList()
      }
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.userList = []
      this.userNoList = []
      ;(this.selectionRows = selection), (this.ids = selection.map(item => item.typeId))

      selection.forEach(item => {
        this.userList.push({ typeId: item.typeId, userId: this.userIdTemp })
      })
      selection.forEach(item => {
        if (item.keeperUserId != null) {
          this.userNoList.push({
            typeId: item.typeId,
            userId: item.keeperUserId
          })
        }
      })
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    //单选操作-跨页
    handlerSelect(val, row) {
      if (!row || !row.typeId) return

      this.userList = this.userList || []
      this.userNoList = this.userNoList || []
      this.ids = this.ids || []

      const isSelected = this.ids.indexOf(row.typeId) === -1

      this.updateList(this.userList, row.typeId, this.userIdTemp, isSelected)
      this.updateList(this.userNoList, row.typeId, row.keeperUserId, isSelected)
    },
    updateList(list, typeId, userId, isSelected) {
      const index = list.findIndex(item => item.typeId === typeId)
      if (isSelected) {
        list.push({ typeId, userId })
      } else if (index !== -1) {
        list.splice(index, 1)
      }
    },

    //全选操作-跨页
    handlerSelectAll(val) {
      if (!Array.isArray(val) || !val.length) {
        // 当前页取消全选 & 其他页也无选中
        this.userList = []
        this.userNoList = []
        return
      }

      this.tableData = this.tableData || []
      this.userList = this.userList || []
      this.userNoList = this.userNoList || []
      this.maxLength = this.maxLength || 9999 // 加防御，默认最大数

      const isAllSelect = this.tableData.every(item => val.some(valItem => valItem.typeId === item.typeId))

      const getDiff = (source, compareList) =>
        source.filter(item => !compareList.some(target => target.typeId === item.typeId))

      if (isAllSelect) {
        // ✅ 全选逻辑
        const diff = getDiff(val, this.userList)
        const diffNo = getDiff(val, this.userNoList)

        const addWithLimit = (targetList, diffList, mapFn) => {
          const spaceLeft = this.maxLength - targetList.length
          const toAdd = diffList.slice(0, spaceLeft).map(mapFn)
          const toDeselect = diffList.slice(spaceLeft)
          toDeselect.forEach(item => this.$refs.multipleTable?.toggleRowSelection(item, false))
          return targetList.concat(toAdd)
        }

        this.userList = addWithLimit(this.userList, diff, item => ({
          typeId: item.typeId,
          userId: this.userIdTemp
        }))

        this.userNoList = addWithLimit(this.userNoList, diffNo, item => ({
          typeId: item.typeId,
          userId: item.userId
        }))
      } else {
        // ❌ 当前页取消全选逻辑
        this.userList = this.userList.filter(user => !this.tableData.some(item => item.typeId === user.typeId))
        this.userNoList = this.userNoList.filter(user => !this.tableData.some(item => item.typeId === user.typeId))
      }
    },

    /** 绑定按钮操作 */
    handleBind() {
      if (this.userIdTemp == -1) {
        this.$alert('未勾选绑定人，无法绑定', '提示', {
          type: 'warning',
          confirmButtonText: '确定'
        })
        return
      }

      const params = [
        {
          typeId: this.queryParams.typeId,
          userId: this.userIdTemp
        }
      ]
      bindPersonSettingApi(params).then(response => {
        this.$modal.msgSuccess('绑定成功')
        this.ids = null
        this.userList = null
        this.userIdTemp = -1
        this.getTreeData()
        this.getList()
        this.$refs.multipleTable.clearSelection()
      })
    },

    /** 解绑按钮操作 */
    handleNoBind() {
      if (this.ids.length == 0) {
        this.$alert('未进行勾选，无法解绑', '提示', {
          type: 'warning',
          confirmButtonText: '确定'
        })
        return
      } else {
        unBindPersonSettingApi(this.userNoList).then(response => {
          this.$modal.msgSuccess('解绑成功')
          this.ids = null
          this.userList = null
          this.userNoList = null
          this.getTreeData()
          this.getList()
          this.$refs.multipleTable.clearSelection()
        })
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const typeId = row.typeId
      const userId = row.repairUserId
      bindRepair({
        typeId: typeId,
        userId: userId
      }).then(response => {
        this.$modal.msgSuccess('解绑成功')
        this.getList()
      })
    },

    handleUpdateKeep(row) {
      const typeId = row.typeId
      const userId = row.keeperUserId
      const userTwo = []
      userTwo.push({
        typeId: typeId,
        userId: userId
      })
      unBindPersonSettingApi(userTwo).then(response => {
        this.$modal.msgSuccess('解绑成功')
        this.getList()
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      const formatTime = date => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}${month}${day}_${hours}${minutes}${seconds}`
      }

      const currentTime = formatTime(new Date())
      let queryTemp = this.queryParams
      // queryTemp.level = 0;
      this.download(
        '/material/ma_type/export4Keeper',
        {
          ...queryTemp
        },
        `物资类型信息_${currentTime}.xlsx`
      )
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
  width: 60px !important;
  margin-bottom: 10px;
}

::v-deep .btn-items .el-button + .el-button {
  margin-left: 6px;
}

.btn-items {
  margin-left: 4px;

  .el-button--text {
    font-size: 16px;
  }
}
.grid-content {
  border-radius: 4px;
  min-height: 24px;
}
.bg-purple-dark {
  background: #e5e9f2;
}

::v-deep .el-tree .el-tree-node__expand-icon.expanded {
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
}

::v-deep .el-tree .el-icon-caret-right:before {
  content: '\e783';
  font-size: 16px;
}

::v-deep .el-tree .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
  content: '\e781';
  font-size: 16px;
  color: #1890ff;
}

::v-deep .el-tree-node__content > .el-tree-node__expand-icon {
  color: #1890ff !important;
}

::v-deep .el-tree-node__expand-icon.is-leaf {
  color: transparent !important;
}

::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #8decf1;
}
</style>
