<template>
  <div class="page-container row-container">
    <!-- 左侧区域 -->
    <section class="list-part-container" style="flex: 1">
      <!-- 搜索区 -->
      <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item class="section-title" label="部门管理" />
      </el-form>
      <!-- 按钮区 -->
      <div class="list-btns-container">
        <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['system:product:add']">新增</el-button>
        <el-button v-if="!editStatus" type="danger" icon="Delete" @click="handleDelete" v-hasPermi="['system:product:delete']"> 删除</el-button>
      </div>
      <!-- 列表区 -->
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <!-- 列表区 -->
          <!-- <el-table v-loading="loading" :data="deptList" row-key="id" default-expand-all highlight-current-row height="100%" :filter-node-method="filterNode" @selection-change="handleSelectionChange" @current-change="handleUser">
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column label="行号" type="index" width="50" align="center" />
            <el-table-column label="部门名称" prop="label" header-align="center" />
            <el-table-column label="是否为工段" prop="status" width="70" align="center">
              <template #default="scope">
                <dict-tag :options="dept_status" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center">
              <template #default="scope">
                <el-button link type="warning" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:vehicle:edit']">编辑</el-button>
                <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:vehicle:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table> -->
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable prefix-icon="Search" style="margin-bottom: 20px" />
          <el-tree
            :data="deptList"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="deptTreeRef"
            node-key="id"
            highlight-current
            check-strictly
            default-expand-all
            show-checkbox
            @check-change="handleDeptChange"
            @node-click="handleGetUser"
          />
        </div>
      </div>
    </section>

    <!-- 右侧区域 -->
    <section class="list-part-container" style="flex: 3">
      <!-- 搜索区 -->
      <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item class="section-title" label="员工" />
      </el-form>

      <!-- 按钮区 -->
      <div class="list-btns-container">
        <el-button v-if="!editStatus" type="primary" icon="Plus" @click="openUser">新增</el-button>
        <el-button v-if="!editStatus" type="danger" icon="Delete" @click="handleUserDelete"> 删除</el-button>
      </div>

      <!-- 列表区 -->
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table v-loading="loading" :data="userList" height="100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column type="index" label="行号" width="50" align="center" />
            <el-table-column label="员工编码" width="100" prop="userName" align="center" />
            <el-table-column label="员工姓名" width="100" prop="nickName" align="center" />
            <el-table-column label="性别" width="50" prop="sex" align="center" />
            <el-table-column label="手机号码" width="120" prop="phoneNumber" align="center" />
            <el-table-column label="部门负责人" width="90" align="center">
              <template #default="scope">
                <dict-tag :options="yesOrNo" :value="scope.row.isLeader" />
              </template>
            </el-table-column>
            <el-table-column label="调度人员" width="90" align="center">
              <template #default="scope">
                <dict-tag :options="yesOrNo" :value="scope.row.isDispatcher" />
              </template>
            </el-table-column>
            <el-table-column label="工段长" width="90" align="center">
              <template #default="scope">
                <dict-tag :options="yesOrNo" :value="scope.row.isFormman" />
              </template>
            </el-table-column>
            <el-table-column label="调机班长" width="90" align="center">
              <template #default="scope">
                <dict-tag :options="yesOrNo" :value="scope.row.isYardman" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="50" prop="phoneNumber" align="center">
              <template #default="scope">
                <el-button link type="primary" @click="updateUserHandle(scope.row)">修改</el-button>
              </template>
            </el-table-column>
            <el-table-column />
          </el-table>
        </div>
      </div>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleGetUser"
      />
    </section>

    <!-- 表单 -->
    <dept-form ref="deptRef" :get-list="getList" />
    <person ref="personRef" :multiple="multiple" :multiple-selected="handleMultipleSelected" />
  </div>
</template>

<script setup name="Process">
import { getToken } from '@/utils/auth'
import { getUsersByDeptId, saveDeptUser, deptTreeSelect, delDeptUser } from '@/api/system/user'
import { delDept } from '@/api/system/dept'
import useUserStore from '@/store/modules/user'
import deptForm from './form'
import person from '@/views/dialog/person.vue'
import Sortable from 'sortablejs'
const { proxy } = getCurrentInstance()

/** 查询 对象 */
const deptList = ref([])
const editStatus = ref(false)
const userList = ref([])
const loading = ref(true)
const ids = ref([])
const deptName = ref('')
const single = ref(true)
const multiple = ref(true)

//多选员工数据
const deptUser = ref([])
const deptIds = ref([])
const sysDept = ref({})
const total = ref(0)
/** 查询对象 */
const queryParams = ref({
  deptId: 0,
  pageNum: 1,
  pageSize: 10,
  code: null,
  name: null
})

const yesOrNo = [
  { label: '是', value: '1', elTagType: 'primary', elTagClass: '' },
  { label: '否', value: '0', elTagType: 'danger', elTagClass: '' }
]

/***********************  方法区  ****************************/

/** 查询标准工序管理列表 */
function getList() {
  loading.value = true
  deptTreeSelect().then((response) => {
    deptList.value = response.data
    loading.value = false
  })
}
/** 根据名称筛选部门树 */
watch(deptName, (val) => {
  proxy.$refs['deptTreeRef'].filter(val)
})
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

//打开添加人员
function openUser() {
  handleAddBatch()
}
/** 多选添加 */
function handleAddBatch() {
  multiple.value = true
  proxy.$refs.personRef.open()
}

function handleMultipleSelected(selection) {
  const newList = []
  for (var i = 0; i < selection.length; ++i) {
    const newPerson = {}

    newPerson.userId = selection[i].userId
    newPerson.deptId = sysDept.value.id

    userList.value.push(newPerson)
  }
  saveDeptUser(userList.value).then((response) => {
    if (response.code == 200) {
      proxy.$modal.msgSuccess('操作成功')
      handleGetUser(sysDept.value)
    }
  })
}

//部门复选框
function handleDeptChange(row, type) {
  if (type) {
    deptIds.value.push(row.id)
  } else {
    deptIds.value.filter((item) => {
      if (item == row.id) {
        deptIds.value.splice(deptIds.value.indexOf(item), 1)
      }
    })
  }
}

// 多选框选中数据
function handleSelectionChange(selection) {
  console.log(selection)
  for (var i = 0; i < selection.length; ++i) {
    var newDeptUser = {}
    newDeptUser.userId = selection[i].userId
    newDeptUser.deptId = sysDept.value.deptId
    deptUser.value.push(newDeptUser)
  }

  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  proxy.$refs.deptRef.open()
}

/**部门名称表点击事件 */
function handleGetUser(row) {
  if (row) {
    sysDept.value = row
    queryParams.value.deptId = sysDept.value.id
    getUsersByDeptId(queryParams.value).then((response) => {
      if (response.code == 200) {
        userList.value = response.rows
        total.value = response.total
      }
    })
  }
}
/** 修改按钮操作 */
function updateUserHandle(row) {
  const id = row.id
  const userData = row
  userData.sysDept = sysDept.value
  proxy.$refs.updateUser.open(userData)
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delDept(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功！')
    })
    .catch(() => {})
}
/** 人员删除按钮操作 */
function handleUserDelete(row) {
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delDeptUser(sysDept.value)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功！')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'business/Department/export',
    {
      ...queryParams.value
    },
    `process_${new Date().getTime()}.xlsx`
  )
}

onMounted(() => {
  getList()
})
</script>
<style scoped>
.move-handle {
  cursor: move;
  background-color: #eee;
}
</style>
