<script setup lang="ts">
import { computed, nextTick, reactive, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';

defineOptions({ name: 'ProductCreateTeamMemberDialog' });

interface DraftMemberInput {
  userId: string;
  roleId: string;
  remark: string;
}

interface Props {
  initial: DraftMemberInput | null;
  userOptions: Api.SystemManage.UserSimple[];
  roleOptions: Api.SystemManage.RoleSimple[];
}

interface Emits {
  (e: 'submit', payload: DraftMemberInput): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', { default: false });

const { formRef, validate } = useForm();
const { createRequiredRule } = useFormRules();

const model = reactive<DraftMemberInput>({ userId: '', roleId: '', remark: '' });

const userLabelMap = computed(() => new Map(props.userOptions.map(item => [String(item.id), item.nickname])));

const selectableRoles = computed(() => props.roleOptions.filter(role => role.visible !== 0));

const rules = computed(
  () =>
    ({
      roleId: [createRequiredRule('请选择角色')]
    }) satisfies Record<string, App.Global.FormRule[]>
);

async function handleConfirm() {
  await validate();
  emit('submit', {
    userId: model.userId,
    roleId: model.roleId,
    remark: model.remark.trim()
  });
}

watch(visible, async value => {
  if (!value) return;
  model.userId = props.initial?.userId || '';
  model.roleId = props.initial?.roleId || '';
  model.remark = props.initial?.remark || '';
  await nextTick();
  formRef.value?.clearValidate();
});
</script>

<template>
  <BusinessFormDialog v-model="visible" title="调整成员角色" preset="sm" @confirm="handleConfirm">
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top" :validate-on-rule-change="false">
      <ElRow :gutter="16">
        <ElCol :span="24">
          <ElFormItem label="成员用户">
            <ElInput
              :model-value="userLabelMap.get(String(model.userId)) || ''"
              readonly
              class="product-create-team-member-dialog__readonly-input"
              placeholder="未获取到成员用户"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem label="目标角色" prop="roleId">
            <ElSelect v-model="model.roleId" class="w-full" placeholder="请选择角色">
              <ElOption v-for="role in selectableRoles" :key="role.id" :label="role.name" :value="role.id">
                <div class="product-create-team-member-dialog__role-option">
                  <span class="product-create-team-member-dialog__role-option-name">{{ role.name }}</span>
                  <ElTooltip v-if="role.remark" :content="role.remark" placement="right" :show-after="120">
                    <icon-ep:info-filled class="product-create-team-member-dialog__role-option-info" @click.stop />
                  </ElTooltip>
                </div>
              </ElOption>
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem label="备注">
            <ElInput
              v-model="model.remark"
              type="textarea"
              :rows="3"
              maxlength="200"
              show-word-limit
              placeholder="请输入备注"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
  </BusinessFormDialog>
</template>

<style scoped>
:deep(.product-create-team-member-dialog__readonly-input .el-input__wrapper) {
  background: linear-gradient(180deg, rgb(241 245 249 / 98%), rgb(226 232 240 / 94%)), rgb(241 245 249);
  box-shadow: 0 0 0 1px rgb(203 213 225 / 96%) inset;
  cursor: default;
}

:deep(.product-create-team-member-dialog__readonly-input .el-input__wrapper:hover),
:deep(.product-create-team-member-dialog__readonly-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px rgb(203 213 225 / 96%) inset;
}

:deep(.product-create-team-member-dialog__readonly-input .el-input__inner) {
  color: rgb(51 65 85 / 96%);
  -webkit-text-fill-color: rgb(51 65 85 / 96%);
  cursor: default;
}

.product-create-team-member-dialog__role-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  width: 100%;
}

.product-create-team-member-dialog__role-option-name {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-create-team-member-dialog__role-option-info {
  flex-shrink: 0;
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  cursor: help;
}

.product-create-team-member-dialog__role-option-info:hover {
  color: var(--el-color-primary);
}
</style>
