<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"
              v-hasPermi="['ma:repair:add']"
            >
              绑定
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-minus"
              size="mini"
              @click="handleNoBind"
              v-hasPermi="['ma:repair:remove']"
            >
              解绑
            </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="typeId"
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
          style="max-height: 650px; overflow: auto"
        >
          <!-- @select-all="handlerSelectAll" -->
          <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="partType"></el-table-column>
          <el-table-column label="配件名称" align="center" show-overflow-tooltip prop="partName"></el-table-column>
          <el-table-column label="规格型号" align="center" show-overflow-tooltip prop="paName"></el-table-column>
          <el-table-column label="计量单位" align="center" show-overflow-tooltip prop="unitName"></el-table-column>
          <el-table-column label="库管员" align="center" prop="keepUserName" show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-if="!scope.row.keepUserName" style="color: red">
                {{ '请绑定' }}
              </div>
              <div v-else>
                {{ scope.row.keepUserName }}
              </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.keepUserName"
              >
                解绑
              </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, getPartTreeApi } from '@/api/ma/base'
import { bindKeeper, noBindKeeper, getRepairIds } from '@/api/ma/typeConfigRepair'
import { getListByPartType, addBindingApi, unBindApi } from '@/api/ma/partType'
import { getUserList } from '@/api/basic/basic'
import { getInfo } from '@/api/login'
import { downloadFile } from '@/utils/download'
export default {
  name: 'PartsConfigRepair',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      tableData: [],
      // 总条数
      total: 0,
      totalTemp: 0,
      countTemp: 1,
      totalAll: 0,
      // 库管员用户数据
      keeperList: null,
      keeperDataRange: [],
      keeperProRange: [],
      keeperMatRange: [],
      keeperNameRange: [],
      roleIdsTemp: [],
      //维修员用户数据
      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'
      },
      userList: [],
      userNoList: [],
      userIdTemp: -1,
      typeIdTemp: -1,
      maxLength: 100, //已选列表上限，防止数据过多请求报错
      // 查询参数
      queryParams: {
        typeName: '',
        level: 0,
        pageNum: 1,
        pageSize: 9999,
        displayBindRelationship: true
      },

      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: {
    renderConent(h, { node }) {
      let iconClass = ''
      // 根据 node 的类型判断图标
      if (node.data.level == 99) {
        iconClass = 'el-icon-user-solid'
      }
      // else if (node.type === 'file') {
      //   iconClass = 'el-icon-document';
      // }

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

    /** 查询新增页面-上级类型下拉树结构 */
    async getTreeData() {
      const itemName = 'wei_xiu_role_ids'
      await getRepairIds(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() {
      getPartTreeApi().then(response => {
        console.log('🚀 ~ getPartTreeApi ~ response:', response)
        this.treeOptionsTwo = response.data
        if (this.treeOptionsTwo && this.treeOptionsTwo.length > 0) {
          const firstNode = this.treeOptionsTwo[0]
          console.log('🚀 ~ getPartTreeApi ~ firstNode:', firstNode)
          this.queryParams.id = firstNode.id
          this.queryParams.level = firstNode.level
          this.getList()
        }
      })
    },
    /** 查询列表 */
    async getList() {
      this.loading = true
      try {
        const res = await getListByPartType(this.queryParams)
        this.loading = false
        if (!res.data || !res.data.rows) {
          this.typeList = []
          this.total = 0
          return
        }
        this.typeList = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log('🚀 ~ getList ~ 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) {
      console.log('🚀 ~ handleNodeClickTwo ~ data:', data)
      this.queryParams.id = data.id
      this.queryParams.level = data.level
      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.pageNum = 1
      this.queryParams.pageSize = 9999
      this.queryParams.level = 0
      this.$refs.tree.setCurrentKey(null)
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log('🚀 ~ handleSelectionChange ~ selection:', selection)
      this.ids = selection.map(item => item.id)
      console.log('🚀 ~ handleSelectionChange ~ this.ids:', this.ids)
      this.selectionRows = selection.map(item => {
        return {
          userId: item.userId,
          typeId: item.id
        }
      })
    },

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

      const params = {
        typeIds: this.ids,
        userId: this.userIdTemp
      }
      console.log('🚀 ~ //addBindingApi ~ params:', params)
      this.$modal.confirm('确定要绑定吗？').then(async () => {
        try {
          const res = await addBindingApi(params)
          console.log('🚀 ~ //addBindingApi ~ res:', res)
          this.$modal.msgSuccess('绑定成功')
          this.ids = null
          this.userIdTemp = -1
          this.getTreeData()
          this.getList()
          this.$refs.multipleTable.clearSelection()
        } catch (error) {
          console.log('🚀 ~ handleBind ~ error:', error)
        }
      })
    },

    /** 解绑按钮操作 */
    handleNoBind() {
      if (this.selectionRows.length == 0) {
        this.$alert('未进行勾选，无法解绑', '提示', {
          type: 'warning',
          confirmButtonText: '确定'
        })
        return
      }
      // 已解绑数据不能重复解绑 提示到具体行
      // 检查是否有已解绑的数据
      const alreadyUnbindRows = this.selectionRows.filter(item => {
        // 判断依据：keepUserName 为空或 null
        const row = this.typeList.find(row => row.id === item.typeId)
        return !row || !row.keepUserName
      })
      if (alreadyUnbindRows.length > 0) {
        // 提示具体行
        const names = alreadyUnbindRows.map(item => {
          const row = this.typeList.find(row => row.id === item.typeId)
          return row ? row.paName : item.typeId
        })
        this.$alert(`以下数据已解绑，不能重复解绑：\n${names.join('、')}`, '提示', {
          type: 'warning',
          confirmButtonText: '确定'
        })
        return
      }
      this.$modal.confirm('确定要解绑吗？').then(async () => {
        try {
          const res = await unBindApi(this.selectionRows)
          console.log('🚀 ~ handleNoBind ~ res:', res)
          this.getTreeData()
          this.getList()
          this.$refs.multipleTable.clearSelection()
        } catch (error) {
          console.log('🚀 ~ handleNoBind ~ error:', error)
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const typeId = row.typeId
      const userId = row.repairUserId
      bindRepair({
        typeId: typeId,
        userId: userId
      }).then(response => {
        this.$modal.msgSuccess('解绑成功')
        this.getList()
      })
    },

    handleUpdateKeep(row) {
      // 弹框提示
      this.$modal.confirm('确定要解绑吗？').then(async () => {
        const params = {
          typeId: row.id,
          userId: row.userId
        }
        try {
          const res = await unBindApi([params])
          console.log('🚀 ~ handleNoBind ~ res:', res)
          this.getTreeData()
          this.getList()
          this.$refs.multipleTable.clearSelection()
        } catch (error) {
          console.log('🚀 ~ handleNoBind ~ error:', error)
        }
      })
    },

    /** 导出按钮操作 */
    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/export4Repair',
        {
          ...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>
