<script lang="ts" setup>/**
 * @Name: NoticeDialog.vue
 * @Description: 变更通知弹窗
 * @Author: Cheney
 */
import { ElMessage } from 'element-plus';
import { useResponse } from '/@/utils/useResponse';
import * as api from '../api';
import { Close, Finished } from '@element-plus/icons-vue';


const props = defineProps({
  rowData: Object
});
const { rowData } = props;

const dialogVisible = defineModel({ default: false });

const noticeDialog = <Ref>useTemplateRef('noticeDialog');

const staffSelect = ref('');
const staffOptions: any = ref([]);
const staffTags: any = ref([]);
const staffLoading = ref(false);
const currentRow: any = ref(null);

onBeforeMount(() => {
  fetchStaffsOptions();
  fetchExistingStaff();
});

function handleClose(done: any) {
  staffSelect.value = '';
  staffTags.value = [];
  done();
}

function addStaffChange() {
  const selectedOption: any = staffOptions.value.find((option: any) => option.id === staffSelect.value);
  if (selectedOption && !staffTags.value.some((tag: any) => tag.id === selectedOption.id)) {
    // 如果选中的项不在 staffTags 中，则添加到 staffTags
    staffTags.value.push({
      id: selectedOption.id,
      username: selectedOption.username
    });
  }
}

function isOptionDisabled(id: any) {
  return staffTags.value.some((tag: any) => tag.id === id);
}

function removeTag(tag: any) {
  staffTags.value = staffTags.value.filter((t: any) => t.id !== tag.id);
  staffSelect.value = '';
}

async function fetchStaffsOptions() {
  const res = await useResponse(api.getStaffsOptions);
  staffOptions.value = res.data;
}

async function fetchExistingStaff() {
  const resp = await useResponse(api.getExistingStaffs, {
    id: rowData?.id ? rowData?.id : rowData?.rowid
  });
  staffTags.value = resp.data;
}

async function addStaffs() {
  const body = {
    id: rowData?.id,
    user_ids: staffTags.value.map((tag: any) => tag.id)
  };
  try {
    const resp = await useResponse(api.postStaffs, body, staffLoading);
    if (resp.code === 2000) {
      ElMessage.success({ message: '操作成功', plain: true });
      fetchExistingStaff();
    }
  } catch (error) {
    ElMessage.error('操作失败！');
  } finally {
    staffSelect.value = '';
  }
}

function cancelDialog() {
  staffSelect.value = '';
  staffTags.value = [];
  noticeDialog.value.visible = false;
}
</script>

<template>
  <div>
    <el-dialog
        ref="noticeDialog"
        v-model="dialogVisible"
        :before-close="handleClose"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        class="notice-dialog"
        title="变更通知"
        width="35%"
    >
      <el-row class="mb-2">
        <el-col>
          <span class="mr-2 font-medium">人员选择</span>
          <el-select v-model="staffSelect" filterable placeholder="输入搜索" style="width: 200px;"
                     @change="addStaffChange">
            <el-option
                v-for="item in staffOptions"
                :key="item.id"
                :disabled="isOptionDisabled(item.id)"
                :label="item.username"
                :value="item.id">
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mb-4">
        <el-col :span="2">
        </el-col>
        <el-col :span="20" class="ml-4" style="color: #909399">
          <i class="bi bi-info-circle"></i>
          <span class="ml-1">仅可添加已绑定邮箱的用户</span>
        </el-col>
      </el-row>
      <div class="flex flex-wrap gap-1.5 min-h-14">
        <el-tag
            v-for="tag in staffTags"
            :key="tag.id"
            closable
            effect="plain"
            round
            @close="removeTag(tag)">
          {{ tag.username }}
        </el-tag>
      </div>

      <el-divider style="margin: 12px 0 20px 0"></el-divider>
      <template #footer>
        <el-button :icon="Close" @click="cancelDialog">取 消</el-button>
        <el-button :icon="Finished" :loading="staffLoading" type="primary" @click="addStaffs">确 定</el-button>
      </template>
      <!--<span slot="footer" class="dialog-footer">-->
      <!--  -->
      <!--</span>-->
    </el-dialog>
  </div>
</template>

<style scoped>
:deep(.notice-dialog .el-dialog__footer) {
  padding-top: 0;
}
</style>
