<script setup lang="ts">
import { ref, computed } from "vue";
import { useAsync } from "/@/hooks";
import { ElForm } from "element-plus";
import { rules, shareTypes } from "./../config/configs";
import {
  httpUserList,
  httpAdd,
  httpDetail,
  httpUpdate
} from "/@/api/interest/userGroup";

const emit = defineEmits(["reload"]);

const id = ref("");
const readonly = ref(false);

const visible = ref(false);
const prop = Object.keys(rules);
const formRef = ref<InstanceType<typeof ElForm>>(null);
const userList = ref<Array<Record<string, string>>>([]);
const isCreate = computed(() => !id.value);

const title = computed(() => {
  if (readonly.value) return "查看用户组";
  return isCreate.value ? "创建用户组" : "编辑用户组";
});

//编辑或创建后进行的操作
const onBeforeAction = () => {
  visible.value = false;
  emit("reload");
};

const {
  run: userlistRun,
  data: userlist,
  loading: userlistLoading
} = useAsync<Array<Record<string, string>>>({
  initalData: []
});

const {
  run: userGroupDetailRun,
  data: userGroupDetail,
  loading: userGroupLoading
} = useAsync<Record<string, any>>({
  initalData: {},
  success: () => {
    const { type, title, remark, user_list } = userGroupDetail.value;

    userList.value = user_list;

    formData.value = {
      type,
      title,
      remark,
      users: user_list.map(({ uid }) => uid)
    };
  }
});

const { run: createUserGroupRun, loading: createLoaidng } = useAsync({
  success: () => onBeforeAction()
});
const { run: updateUseGroupRun, loading: updateLoading } = useAsync({
  success: () => onBeforeAction()
});

const formData = ref<Record<string, any>>({});

function createUserGroup() {
  const { users, ...otherParams } = formData.value;

  createUserGroupRun(
    httpAdd({
      ...otherParams,
      uids: users.map(uid => ({ uid }))
    })
  );
}

function updateUserGroup() {
  const { users, ...otherParmas } = formData.value;

  const delUsers = userList.value
    .filter(({ uid, id }) => !users.includes(uid))
    .map(({ uid, id }) => ({
      uid,
      id,
      is_del: 1
    }));

  const originUsers = userList.value
    .filter(({ uid, id }) => users.includes(uid))
    .map(({ uid, id }) => ({
      uid,
      id,
      is_del: 0
    }));

  const addUsers = users
    .filter(
      _uid =>
        !originUsers.find(({ uid }) => uid === _uid) &&
        !delUsers.find(({ uid }) => uid === _uid)
    )
    .map(uid => ({
      uid,
      id: null,
      is_del: 0
    }));

  updateUseGroupRun(
    httpUpdate({
      id: id.value,
      ...otherParmas,
      uids: [...delUsers, ...originUsers, ...addUsers]
    })
  );
}

function handleConfirm() {
  formRef.value.validate(isValid => {
    if (!isValid) return;

    if (isCreate.value) return createUserGroup();

    updateUserGroup();
  });
}

defineExpose({
  onDisplay(_id = "", _readonly = false) {
    id.value = _id;
    visible.value = true;
    readonly.value = _readonly;
    userlistRun(httpUserList());
    if (!id.value) return prop.forEach(key => (formData.value[key] = ""));
    userGroupDetailRun(httpDetail({ id: _id }));
  }
});
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="title"
    :close-on-click-modal="false"
    center
  >
    <el-form
      label-width="80px"
      :rules="rules"
      ref="formRef"
      :model="formData"
      :disabled="readonly"
      v-loading="userlistLoading || userGroupLoading"
    >
      <el-form-item label="组名称" :prop="prop[0]">
        <el-input
          :placeholder="rules[prop[0]].message"
          v-model="formData[prop[0]]"
        />
      </el-form-item>
      <el-form-item label="组成员" :prop="prop[1]">
        <el-select
          :placeholder="rules[prop[1]].message"
          v-model="formData[prop[1]]"
          multiple
          w-full
        >
          <el-option
            v-for="item in userlist"
            :key="item.id"
            :value="item.id"
            :label="item.nickname"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="共享类型" :prop="prop[2]">
        <el-select
          :placeholder="rules[prop[2]].message"
          v-model="formData[prop[2]]"
          w-full
        >
          <el-option
            v-for="item in shareTypes"
            :key="item.value"
            v-bind="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" :prop="prop[3]">
        <el-input
          :placeholder="rules[prop[3]].message"
          v-model="formData[prop[3]]"
        />
      </el-form-item>

      <el-form-item>
        <div w-full flex justify-end>
          <el-button
            type="primary"
            @click="() => handleConfirm()"
            :loading="createLoaidng || updateLoading"
            >提交</el-button
          >
          <el-button @click="() => (visible = false)">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
