<template>
  <div class="group-board">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="分组名称：" prop="name" v-if="props.drawerTitle === '查看人员分组'">
        <el-input
          v-model="ruleForm.name"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 2 }"
          autocomplete="off"
          disabled="true"
        />
      </el-form-item>
      <el-form-item
        label="分组名称："
        prop="name"
        :rules="[{ required: true, message: '分组名称不能为空' }]"
        v-else
      >
        <el-input
          v-model="ruleForm.name"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 2 }"
          autocomplete="off"
          placeholder="请输入15字以内分组名称"
          maxlength="15"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        label="分组描述："
        prop="description"
        v-if="props.drawerTitle === '查看人员分组'"
      >
        <el-input
          v-model="ruleForm.description"
          type="textarea"
          :rows="4"
          autocomplete="off"
          disabled="true"
        />
      </el-form-item>
      <el-form-item label="分组描述：" prop="description" v-else>
        <el-input
          v-model="ruleForm.description"
          type="textarea"
          :rows="4"
          maxlength="50"
          show-word-limit
          autocomplete="off"
          placeholder="请输入50字以内分组描述"
        />
      </el-form-item>
      <el-form-item label="组内成员：" prop="userList" v-if="props.drawerTitle === '查看人员分组'">
        <el-select
          v-model="ruleForm.userList"
          value-key="id"
          multiple
          disabled="true"
        >
          <el-option v-for="user in selectedUser" :key="user.id" :label="user.name" :value="user">
          </el-option>
        </el-select>
        <p
          >共<span>&nbsp;{{ total }}&nbsp;</span>人</p
        >
      </el-form-item>
      <el-form-item
        label="组内成员："
        prop="userList"
        :rules="[{ required: true, message: '组内成员不能为空' }]"
        v-else
      >
        <el-select
          placeholder="请添加组内人员"
          v-model="ruleForm.userList"
          value-key="id"
          multiple
          @click="dialogVisible = true"
        >
          <el-option v-for="user in selectedUser" :key="user.id" :label="user.name" :value="user">
          </el-option>
        </el-select>
        <p
          >共<span>&nbsp;{{ total }}&nbsp;</span>人</p
        >
      </el-form-item>
      <el-form-item
        label="操作人："
        prop="operator"
        v-if="props.drawerTitle === '查看人员分组' || props.drawerTitle === '编辑人员分组'"
      >
        <el-input v-model="ruleForm.operator" disabled="true" />
      </el-form-item>
      <el-form-item label="创建人：" prop="operator" v-else>
        <el-input v-model="ruleForm.operator" disabled="true" />
      </el-form-item>
      <el-form-item class="buttons" v-if="props.drawerTitle === '编辑人员分组'">
        <el-button @click="recoverForm(ruleFormRef)"> 重置 </el-button>
        <el-button type="primary" @click="changeForm(ruleFormRef)">提交</el-button>
      </el-form-item>
      <el-form-item class="buttons" v-if="props.drawerTitle === '新建人员分组'">
        <el-button @click="resetForm(ruleFormRef)"> 重置 </el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      v-model="dialogVisible"
      title="添加人员"
      align-center
      :close-on-click-modal="false"
      style="height: 583px"
      :width="731"
      :destroy-on-close="true"
      class="workShopDialog"
    >
      <SelectTree @cancel="handleCancle" @submit="handleSubmit" :selectedUser="selectedUser" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import SelectTree from './SelectTree.vue';
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/store/modules/user';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { debounce } from 'lodash-es';
import {
  addUserGroup,
  addUserGroupParams,
  modifyUserGroup,
  modifyUserGroupParams,
} from '../api/index';
import { FormData } from '../type';
const useUser = useUserStore();
const { info } = storeToRefs(useUser);
import userGroupList from '../store/index';
const userGroup = userGroupList();
const { getUserGroup } = userGroup;
interface UserList {
  id: string;
  name: string;
  userId: number;
}
const selectedUser = ref<UserList[]>([]);
const dialogVisible = ref<boolean>(false);
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  name: '',
  description: '',
  userList: [] as UserList[],
  operator: info.value.nickname,
});
const handleCancle = () => {
  dialogVisible.value = false;
};
const total = ref<number>(0);
const handleSubmit = (selectedData: UserList[]) => {
  selectedUser.value = selectedData;
  ruleForm.userList = selectedData;
  total.value = ruleForm.userList.length;
  dialogVisible.value = false;
};
const emit = defineEmits(['close']);
const debounceEmit = debounce((addUserGroupParams) => {
  addUserGroup(addUserGroupParams)
    .then(() => {
      ElMessage({
        message: '创建分组成功!',
        type: 'success',
      });
      emit('close');
      getUserGroup();
    })
    .catch((e) => console.error(e));
}, 500);
const debounceChange = debounce((modifyUserGroupParams) => {
  modifyUserGroup(modifyUserGroupParams)
    .then(() => {
      ElMessage({
        message: '更新分组成功!',
        type: 'success',
      });
      emit('close');
      getUserGroup();
    })
    .catch((e) => console.error(e));
}, 500);
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (!valid) return;
    const params = ref<addUserGroupParams>();
    params.value = {
      name: ruleForm.name,
      description: ruleForm.description,
      userIdList: ruleForm.userList.map((user) => user.userId),
      total: total.value,
    };
    debounceEmit(params.value);
  });
};
const changeForm = (formEl: FormInstance | undefined) => {
  ElMessageBox.confirm('更新之后，引用该分组的“推送对象”将同步更新', '请确认是否更新', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    if (!formEl) return;
    formEl.validate((valid) => {
      if (!valid) return;
      const params = ref<modifyUserGroupParams>();
      params.value = {
        userGroupId: props.formData.userGroupId,
        name: ruleForm.name,
        description: ruleForm.description,
        userIdList: ruleForm.userList.map((user) => user.userId),
        total: total.value,
      };
      debounceChange(params.value);
    });
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const userList = ref<UserList[]>();
const recoverForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  ruleForm.name = props.formData.name;
  ruleForm.description = props.formData.description ? props.formData.description : '';
  userList.value = props.formData.userList.map((user) => ({
    id: `u${user.userId}`,
    userId: user.userId,
    name: `${user.loginName}-${user.nickname}`,
  }));
  selectedUser.value = userList.value;
  ruleForm.userList = userList.value;
  total.value = props.formData.userList.length;
};
const props = defineProps<{
  drawerTitle: string;
  formData: FormData;
}>();
watch(
  () => ruleForm.userList,
  (newUserList) => {
    total.value = newUserList.length;
    const ids = newUserList.map((user) => user.id);
    selectedUser.value = selectedUser.value.filter((user) => ids.includes(user.id));
  },
  { immediate: true },
);
watch(
  () => props.formData,
  (newForm) => {
    ruleForm.name = newForm.name;
    ruleForm.description = newForm.description ? newForm.description : '';
    if (props.drawerTitle === '查看人员分组') {
      ruleForm.operator = newForm.operator;
    }
    userList.value = newForm.userList.map((user) => ({
      id: `u${user.userId}`,
      userId: user.userId,
      name: `${user.loginName}-${user.nickname}`,
    }));
    selectedUser.value = userList.value;
    ruleForm.userList = userList.value;
    total.value = newForm.userList.length;
  },
);
</script>

<style lang="scss" scoped>
.el-form {
  display: flex;
  flex-direction: column;
  margin-top: 24px;
  gap: 20px;
  ::v-deep .el-select__selection {
    min-height: 25px;
    max-height: 60px;
    overflow-y: auto;
  }
  p {
    margin-top: 8px;
    font-weight: 400;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
    line-height: 22px;
  }
  span {
    font-weight: 400;
    font-size: 14px;
    color: #1890ff;
    line-height: 22px;
  }
  .buttons {
    display: flex;
    gap: 8px;
    position: absolute;
    bottom: 35px;
    right: 79px;
    .el-button {
      width: 65px;
      height: 32px;
      padding: 5px 16px 5px 16px;
      border-radius: 2px;
    }
  }
}
</style>