<template>
  <el-container class="gva-table-box">
    <el-header>
      <el-row>
        <el-col :span="2">
          <el-button
            type="primary"
            @click="centerDialogVisible = true"
          >
            添加部门
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button
            type="primary"
            @click="handleDistributionDep"
          >
            分配部门
          </el-button>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-table :data="depTableData">
        <el-table-column
          prop="name"
          label="部门名称"
        />
        <el-table-column
          prop="desc"
          label="部门描述"
        />
        <el-table-column
          prop="principal.nickName"
          label="部门负责人"
        />
        <el-table-column
          prop="isStart"
          label="是否启用"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.isStart"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              @change="handleSwitchChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              icon="edit"
              type="primary"
              link
              @click="handleEditDep(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              icon="delete"
              type="primary"
              link
              @click="handleDeleteDep(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          label="展开"
          width="100px"
          type="expand"
        >
          <template #default="props">
            <el-table
              :data="props.row.users"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                width="55"
              />
              <el-table-column
                prop="ID"
                label="编号"
                align="center"
              />
              <el-table-column
                label="头像"
                align="center"
              >
                <template #default="scope">
                  <CustomPic
                    style="margin-top:8px"
                    :pic-src="scope.row.headerImg"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="userName"
                label="用户名"
                align="center"
              />
              <el-table-column
                prop="nickName"
                label="昵称"
                align="center"
              />
              <el-table-column
                prop="email"
                label="邮箱"
                align="center"
              />
              <el-table-column
                label="操作"
                align="center"
              >
                <template #default="scope">
                  <el-button
                    icon="edit"
                    type="primary"
                    link
                    @click="handleDistributionDep(scope.row)"
                  >分配</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <!--    新增-->
    <el-dialog
      v-model="centerDialogVisible"
      title="新增部门"
      width="500"
      align-center
    >
      <el-form
        :model="depFromData"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="部门名称">
          <el-input
            v-model="depFromData.name"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="部门描述">
          <el-input
            v-model="depFromData.desc"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="部门负责人">
          <el-select
            v-model.number="depFromData.principalId"
            style="width: 240px"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.ID"
              :label="item.nickName"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleAddDep"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--    修改-->
    <el-dialog
      v-model="updateDialogVisible"
      title="修改部门"
      width="500"
      align-center
    >
      <el-form
        :model="updateDepFromData"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="部门名称">
          <el-input
            v-model="updateDepFromData.name"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="部门描述">
          <el-input
            v-model="updateDepFromData.desc"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="部门负责人">
          <el-select
            v-model.number="updateDepFromData.principalId"
            style="width: 240px"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.ID"
              :label="item.nickName"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleUpdateDep"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--    分配-->
    <el-dialog
      v-model="distributionDialogVisible"
      title="分配"
      width="500"
      align-center
    >
      <warning-bar title="注：只提供开启了的部门" />
      <el-select
        v-model.number="distributionDepData.id"
        style="width: 240px"
      >
        <el-option
          v-for="item in depOptions"
          :key="item.ID"
          :label="item.name"
          :value="item.ID"
        />
      </el-select>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="distributionDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="distributionDep"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
  createDep,
  deleteDep,
  getAllDep,
  getDepByStart,
  updateDep,
  updateDepStatus,
  updateUserDep,
} from '@/api/department'
import CustomPic from '@/components/customPic/index.vue'
import WarningBar from '@/components/warningBar/warningBar.vue'
import { getAllUsers } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'

const depTableData = ref([])

const queryData = async() => {
  await getAllDep().then(res => {
    depTableData.value = res.data
    console.log(depTableData.value)
  })
  await getAllUsers().then(res => {
    userOptions.value = res.data
    depFromData.value.principalId = res.data[0].ID
  })
  await getDepByStart().then(res => {
    depOptions.value = res.data
    distributionDepData.value.id = res.data[0].ID
  })
}

// 部门是否启用
const handleSwitchChange = async(row) => {
  await updateDepStatus(row).then(res => {
    if (res.code === 0) {
      ElMessage.success('更新成功')
      queryData()
    }
  })
}

// 修改
const updateDialogVisible = ref(false)

const updateDepFromData = ref({
  id: 0,
  name: '',
  desc: '',
  principalId: 0
})
const handleEditDep = (row) => {
  updateDepFromData.value.id = row.ID
  updateDepFromData.value.name = row.name
  updateDepFromData.value.desc = row.desc
  updateDepFromData.value.principalId = row.principalId
  updateDialogVisible.value = true
}

const handleUpdateDep = async() => {
  console.log(updateDepFromData.value)
  await updateDep(updateDepFromData.value).then(res => {
    if (res.code === 0) {
      ElMessage.success('更新成功')
      queryData()
    }
  })
  updateDialogVisible.value = false
}

const handleDeleteDep = (row) => {
  ElMessageBox.confirm(
    '确定删除吗？',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      await deleteDep(row.ID).then(res => {
        console.log(res)
        if (res.code === 0) {
          ElMessage.success('删除成功')
          queryData()
        } else if (res.msg === '当前部门下存在用户') {
          ElMessage.error('当前部门下存在用户')
        }
      })
      await queryData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 分配
const depOptions = ref()

const distributionDialogVisible = ref(false)

const distributionDepData = ref({
  ids: [],
  id: 0
})

const handleDistributionDep = (row) => {
  if (row.ID !== undefined) {
    distributionDepData.value.ids = []
    distributionDepData.value.ids[0] = row.ID
  }
  distributionDialogVisible.value = true
}

const handleSelectionChange = async(val) => {
  distributionDepData.value.ids = []
  for (const key in val) {
    console.log(val[key].ID)
    distributionDepData.value.ids.push(val[key].ID)
  }
}
const distributionDep = async() => {
  if (distributionDepData.value.ids.length === 0) {
    ElMessage.error('请选择用户')
    return false
  }
  await updateUserDep(distributionDepData.value).then(res => {
    if (res.code === 0) {
      ElMessage.success('更新成功')
    }
  })
  await queryData()
  distributionDialogVisible.value = false
}

// 新增部门
const userOptions = ref()

const depFromData = ref({
  name: '',
  desc: '',
  principalId: 0
})

const centerDialogVisible = ref(false)
const handleAddDep = async() => {
  if (depFromData.value.name === '') {
    ElMessage.error('请输入部门名称')
    return false
  }
  await createDep(depFromData.value).then(res => {
    if (res.code === 0) {
      ElMessage.success('新增成功')
    }
  })
  await queryData()
  centerDialogVisible.value = false
}

onMounted(() => {
  queryData()
})
</script>

<style scoped>

</style>
