<template>
  <div class="container">
    <div class="container-header">
      <div class="container-header-title" @click="goBack">
        <el-icon><ArrowLeftBold /></el-icon>
        <span>{{ proxy.$route.query.groupName }}</span>
      </div>
      <div class="container-header-btn">
        <el-button type="primary" @click="addMemberDialog = true">新增成员</el-button>
      </div>
    </div>
    <el-table v-loading="loading" :data="userList">
      <el-table-column label="名称" align="center" key="user.name" prop="user.name">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-image referrerpolicy="no-referrer" :src="scope.row.user.avatar" style="width: 30px; height: 30px; border-radius: 50%; margin-right: 10px"></el-image>
            <span>{{ scope.row.user.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column>
        <template #default="scope">
          <span v-if="manages[scope.row.user._id] == 'manage'">管理员</span>
          <span v-else-if="manages[scope.row.user._id] == 'creator'">创建者</span>
          <span v-else>成员</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="handleManage(scope.row, true)" v-if="manages[scope.row.user._id] != 'manage' && manages[scope.row.user._id] != 'creator'">设置管理员</el-button>
          <el-button @click="handleManage(scope.row, false)" v-if="manages[scope.row.user._id] == 'manage'">取消管理员</el-button>
          <el-button @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="params.page" v-model:limit="params.limit" @pagination="getMembers" />
    <el-dialog v-model="addMemberDialog" title="团队信息设置" append-to-body @submit.native.prevent>
      <el-form :modal="memberInfo">
        <el-form-item label="成员名称">
          <el-input v-model="memberInfo.name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addSubmit">确 定</el-button>
          <el-button @click="addMemberDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { getGroupMembers, getGroupInfo, removeGroupMember, getZhiHuiSign, getUserByZhId, getUserId, initGroup, joinCompany, updateUserInfo, updateGroupInfo } from '@/api/zhihui/index.js';
const { proxy } = getCurrentInstance();
const loading = ref(false);
const params = ref({
  team: proxy.$route.query.groupId,
  limit: 20,
  page: 1,
});
const total = ref(0);
const manages = ref({});
const original_manege = ref([]);
const userList = ref([]);
const addMemberDialog = ref(false);
const memberInfo = ref({});
const companyId = ref('');

async function init() {}
async function getInfo() {
  let data = await getGroupInfo({ name: proxy.$route.query.groupName });
  let list = {};
  if (data.statusCode === 200) {
    companyId.value = data.data.company;
    original_manege.value = data.data.manages;
    data.data.manages.map(item => {
      list[item._id] = 'manage';
      if (item._id == data.data.creator._id) {
        list[item._id] = 'creator';
      }
    });
    manages.value = list;
  }
}
//移除成员
async function handleDelete(item) {
  console.log('🚀 ~ file: groupMember.vue:59 ~ handleDelete ~ item:', item);
  let option = {
    appid: import.meta.env.VITE_APP_ZHI_HUI_APPID,
    teamId: item.team,
    userId: item.user._id,
  };
  let result = await getUserByZhId({ zhUserId: item.user._id });
  let sig_data = await getZhiHuiSign(option);
  if (sig_data.code != 200) {
    return proxy.$modal.msgError('获取签名失败！');
  }
  option.sig = sig_data.data;
  let data = await removeGroupMember(option);
  if (data.statusCode != 200) {
    return proxy.$modal.msgError('删除失败失败！' + data.message);
  }
  let zhFirmId = companyId.value;
  let userId = result.data.userId;
  let zhGroupIds = result.data.zhGroupIds;
  let ids = zhGroupIds?.split(',') || [];
  if (ids.length > 0) {
    ids = ids.filter(e => {
      return e != item.team;
    });
  }
  updateUserInfoSys(zhFirmId, userId, ids);
}
async function addSubmit() {
  if (companyId.value == '') {
    proxy.$modal.msgError('请选择公司！');
  }
  let result = await getUserId({ userName: memberInfo.value.name });
  let userId = 0;
  let zhFirmId = '';
  let zhGroupIds = '';
  if (result.code == 200) {
    if (!result.data) {
      proxy.$modal.msgError('该用户不存在！');
    }
    if (!result.data.zhUserId) {
      return proxy.$modal.msgError('该用户未注册智绘！');
    }
    let option = {
      appid: import.meta.env.VITE_APP_ZHI_HUI_APPID,
      companyId: companyId.value,
      userId: result.data.zhUserId,
    };
    let sig_data = await getZhiHuiSign(option);
    if (sig_data.code != 200) {
      return proxy.$modal.msgError('获取签名失败！');
    }
    let sig = sig_data.data;
    option.sig = sig;
    let company = await joinCompany(option);
    // if (company.statusCode != 200) {
    //   return proxy.$modal.msgError('添加失败！' + data.message);
    // }
    option = {
      appid: import.meta.env.VITE_APP_ZHI_HUI_APPID,
      companyId: companyId.value,
      teamId: proxy.$route.query.groupId,
      userId: result.data.zhUserId,
    };
    sig_data = await getZhiHuiSign(option);
    if (sig_data.code != 200) {
      return proxy.$modal.msgError('获取签名失败！');
    }
    sig = sig_data.data;
    option.sig = sig;
    let data = await initGroup(option);
    if (data.statusCode != 200) {
      return proxy.$modal.msgError('添加失败！' + data.message);
    }
    proxy.$modal.msgSuccess('添加成功！');
    zhFirmId = companyId.value;
    userId = result.data.userId;
    zhGroupIds = result.data.zhGroupIds;
    let ids = zhGroupIds?.split(',') || [];
    ids.push(proxy.$route.query.groupId);
    ids = new Set(ids);
    updateUserInfoSys(zhFirmId, userId, ids);
    addMemberDialog.value = false;
  }
}
function updateUserInfoSys(zhFirmId, userId, ids) {
  updateUserInfo({
    zhFirmId: zhFirmId,
    userId: userId,
    zhGroupIds: Array.from(ids).join(','),
  });
  getMembers();
}
async function getMembers() {
  loading.value = true;
  let data = await getGroupMembers(params.value);
  if (data.statusCode === 200) {
    userList.value = data.data;
    total.value = data.pagination.total;
  }
  loading.value = false;
}
async function handleManage(item, add) {
  let manage = Object.keys(manages.value);
  let id = item.user._id;
  if (add) {
    manage.push(id);
  } else {
    manage = manage.filter(e => {
      return e != id;
    });
  }
  let data = await updateGroupInfo({ id: proxy.$route.query.groupId, manages: manage });
  if (data.statusCode != 200) {
    return proxy.$modal.msgError('操作失败！' + data.message);
  }
  getInfo();
  getMembers();
}

function goBack() {
  proxy.$router.go(-1);
}
getInfo();
getMembers();
</script>

<style scoped lang="scss">
.container {
  padding: 30px;
  .container-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .container-header-title {
      margin-bottom: 0;
      font-size: 24px;
      font-weight: 700;
      display: flex;
      align-items: center;
      &:hover {
        cursor: pointer;
        color: #3a2be0;;
      }
    }
  }
}
</style>
