<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="108px">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入电话号码" clearable style="width: 200px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable style="width: 200px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="是否绑定邮箱" prop="emailbind">
            <el-select v-model="queryParams.emailbind" clearable>
              <el-option v-for="dict in common_yes_no" :value="dict.value" :label="dict.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否绑定微信" prop="wxbind">
            <el-select v-model="queryParams.wxbind" clearable>
              <el-option v-for="dict in common_yes_no" :value="dict.value" :label="dict.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header v-if="false">
        <!-- <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['auth:user:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row> -->
      </template>

      <el-table v-loading="loading" :data="userList" border>
        <el-table-column type="index" width="55" align="center" label="序号" />
        <el-table-column label="姓名" align="left" prop="name" width="250">
          <template #default="scope">
            <div style="display: flex;align-items: center;">
              <el-avatar size="small" :src="scope.row.avatar" />
              <div style="margin-left: 10px;">{{ scope.row.name }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="phone" width="150" />
        <el-table-column label="邮箱" align="center" prop="email" width="200" />
        <el-table-column label="绑定微信" align="center" prop="wxbind" width="90">
          <template #default="scope">
            <dict-tag :options="common_yes_no" :value="scope.row.wxbind"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="所在企业" align="center" prop="cpyCount" width="300">
          <template #default="scope">
            <div v-for="item in scope.row.cpyNames?.split(',')">{{ item }}</div>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button size="default" type="primary" @click="handleCpyEdit(scope.row)">修改企业信息</el-button>
            <el-button size="default" type="primary" @click="handleEdit(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <el-dialog :close-on-click-modal="false" title="用户信息修改" v-model="userDialogVisible" width="500px" append-to-body>
      <el-form ref="userFormRef" :model="userForm" :rules="userRules" label-width="108px">
        <UploadAvatar title="头像" v-model="userForm.avatar"></UploadAvatar>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitUser">确 定</el-button>
          <el-button @click="cancelUser">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="企业信息修改" v-model="cpyDialogVisible" width="500px" append-to-body>
      <div style="display: flex;align-items: center;">
        <el-avatar size="small" :src="currentUser?.avatar" />
        <div style="margin-left: 10px;">【{{ currentUser?.name }}】目前已加入企业：</div>
      </div>
      <div class="cpy-container" v-loading="loading">
        <div class="cpy-item" v-for="item in cpyList">
          <span>{{ item.cpyInfo?.cpyName || '无名' }}({{ item.cpyInfo?.creditCode }})</span><el-button type="text"
            icon="close" @click="removeUserCpy(item)"></el-button>
        </div>
      </div>
      <span v-show="cpyList.length == 0">暂未加入任何企业</span>
      <template #footer>
        <div class="center-btn-container">

          <el-button @click="handleCpyAdd" type="primary" :loading="buttonLoading">添加企业<ElIcon>
              <Plus />
            </ElIcon> </el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer v-model="cpySelectVisible" size="40%" :close-on-click-modal="false" v-loading="loading">
      <el-form :model="cpyQueryParams" ref="queryFormRef" label-width="100px" :inline="true">
        <el-form-item label="企业名称" prop="cpyName">
          <el-input v-model="cpyQueryParams.cpyName" placeholder="请输入企业名称" clearable @keyup.enter="handleQueryCpy" />
        </el-form-item>
        <el-form-item label="社会信用代码" prop="creditCode">
          <el-input v-model="cpyQueryParams.creditCode" placeholder="请输入社会信用代码" clearable @keyup.enter="handleQueryCpy" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQueryCpy">搜索</el-button>
          <el-button icon="Refresh" @click="resetQueryCpy">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="recordCompanyList" border>
        <el-table-column type="index" width="55" align="center" label="序号" />
        <el-table-column label="企业名称" align="center" prop="cpyName" />
        <el-table-column label="社会统一信用代码" align="center" prop="creditCode"></el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="text" @click="addCPy(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="cpyTotal > 0" :total="cpyTotal" v-model:page="cpyQueryParams.pageNum"
        v-model:limit="cpyQueryParams.pageSize" @pagination="getCpyList" />
    </el-drawer>
  </div>
</template>

<script setup name="AppUser" lang="ts">
import { listUser, updateUser } from '@/api/auth/user';
import { UserVO, UserQuery, UserForm } from '@/api/auth/user/types';
import { UploadAvatar } from '@/views/components';
import { RecordCompanyVO, RecordCompanyQuery, BindInfoCpyListVo, } from '@/api/enterprise/recordCompany/types';
import { listRecordCompany, listByUserId, removeBindUser, adminAddUserForCpy } from '@/api/enterprise/recordCompany';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userList = ref<UserVO[]>([]);
const loading = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const { common_yes_no } = toRefs<any>(proxy?.useDict('common_yes_no'))


const data = reactive<PageData<any, UserQuery>>({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    phone: undefined,
    emailbind: undefined,
    wxbind: undefined,
    params: {
    }
  },
  rules: {
  }
});

const { queryParams, } = toRefs(data);

/** 查询app用户列表 */
const getList = async () => {
  loading.value = true;
  const res = await listUser(queryParams.value);
  userList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}
/**
 * 用户修改
 */
const userFormRef = ref<ElFormInstance>()
const userDialogVisible = ref(false)
const initUserForm = (): UserForm => ({
  id: undefined,
  name: undefined,
  avatar: undefined,
  phone: undefined,
  email: undefined,
})
const userForm = ref(initUserForm())
const reset = () => {
  userForm.value = initUserForm()
  userFormRef.value?.resetFields()
}
const userRules = {
  name: [{ required: true, trigger: 'blur', message: '姓名不能为空' }],
  phone: [{ required: true, trigger: 'blur', message: '手机号码不能为空' }],
}
const buttonLoading = ref(false)
/** 编辑用户按钮处理 */
const handleEdit = (row: UserVO) => {
  reset()
  Object.assign(userForm.value, row)
  userDialogVisible.value = true
}
/**取消修改用户 */
const cancelUser = () => {
  userDialogVisible.value = false;
}
/**修改用户信息 */
const submitUser = async () => {
  const valid = await userFormRef.value?.validate()
  if (valid) {
    buttonLoading.value = true
    await updateUser(userForm.value).finally(() => buttonLoading.value = false)
    proxy?.$modal.alert("操作成功")
    userDialogVisible.value = false
    getList()
  }
}
const cpyDialogVisible = ref(false)
const cpyList = ref<BindInfoCpyListVo[]>([])
const cpySelectVisible = ref(false)
/** 添加企业处理 */
const handleCpyAdd = () => {
  cpySelectVisible.value = true
  resetQueryCpy()
}
/** 修改企业按钮处理 */
const handleCpyEdit = async (row: UserVO) => {
  currentUser.value = row
  await loadBindCpy()
  cpyDialogVisible.value = true
}
/**
 * 查询用户的企业
 */
const loadBindCpy = async () => {
  const res = await listByUserId(currentUser.value?.id as number)
  cpyList.value = res.data
}
const recordCompanyList = ref<RecordCompanyVO[]>([])
const initCpyParams = (): RecordCompanyQuery => ({
  pageNum: 1,
  pageSize: 10,
  cpyName: undefined,
  creditCode: undefined,
  status: "1",

})
const cpyTotal = ref(0)
const cpyQueryParams = ref(initCpyParams())
/**
 * 查询所有企业
 */
const getCpyList = async () => {
  loading.value = true;
  const res = await listRecordCompany(cpyQueryParams.value);
  recordCompanyList.value = res.rows;
  cpyTotal.value = res.total;
  loading.value = false;
}
/** 搜索按钮操作 */
const handleQueryCpy = () => {
  cpyQueryParams.value.pageNum = 1;
  getCpyList();
}
const currentUser = ref<UserVO | undefined>(undefined)
const cpyQueryParamsRef = ref<ElFormInstance>()
/** 重置按钮操作 */
const resetQueryCpy = () => {
  cpyQueryParamsRef.value?.resetFields();
  cpyQueryParams.value = initCpyParams()
  handleQueryCpy();
}
const addCPy = async (row: RecordCompanyVO) => {
  await proxy?.$modal.confirm(`是否确定将【${currentUser.value?.name}】添加到【${row.cpyName}】?`)
  loading.value = true
  await adminAddUserForCpy({ cpyid: row.id as number, userid: currentUser.value?.id as number }).finally(() => loading.value = false)
  proxy?.$modal.alert("操作成功")
  await loadBindCpy()
  cpySelectVisible.value = false
}
//移除企业
const removeUserCpy = async (row: BindInfoCpyListVo) => {
  await proxy?.$modal.confirm(`是否确定将用户踢出【${row.cpyInfo?.cpyName}】?`)
  loading.value = true
  buttonLoading.value = true
  await removeBindUser({ cpyid: row.cpyInfo?.id as number, userids: [row.cpyInfo?.userid as number] }).catch((e) => {
    loading.value = false;
    throw e
  }).finally(() => { buttonLoading.value = false })
  await loadBindCpy()
  await getList()
  loading.value = false;
}
onMounted(() => {
  getList();
});
</script>
<style scoped lang="scss">
.cpy-container {
  margin-top: 20px;
  margin-bottom: 20px;

  .cpy-item {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    border-bottom: 1px solid green;
  }
}

.center-btn-container {
  display: flex;

  .el-button {
    flex: 1;
  }
}
</style>
