<script lang="ts" setup>
/**
 * @Name: ShopAuthorize.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 shopSelect = ref('');
const shopOptions: any = ref([]);
const shopTags: any = ref([]);
const loading = ref(false);

const radio = ref('1');

onBeforeMount(async () => {
  await fetchShopOptions();
  await fetchAuthorizedShop();
});

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

function addShopChange() {
  const selectedOption: any = shopOptions.value.find((option: any) => option.id === shopSelect.value);
  if (selectedOption && !shopTags.value.some((tag: any) => tag.id === selectedOption.id)) {
    // 如果选中的项不在 shopTags 中，则添加到 shopTags
    shopTags.value.push({
      id: selectedOption.id,
      name: selectedOption.name
    });
  }
}

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

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

async function fetchShopOptions() {
  const res = await useResponse(api.getShopOptions, { is_all : true});
  shopOptions.value = res.data;
}

async function fetchAuthorizedShop() {
	const resp = await useResponse(api.getAuthorizedShop, { user_id: rowData?.id });
	const authorizedShops = (resp.data.authorized_shops ?? []).filter((item: any) => item !== null);

	if (resp.data.is_authorized_all_shops) {
		radio.value = '2';
	} else if (authorizedShops.length > 0) {
		radio.value = '1';
		shopTags.value = authorizedShops
			.map((id: string) => {
				const selectedOption = shopOptions.value.find((option: any) => option.id === id);
				return selectedOption ? {
					id: selectedOption.id,
					name: selectedOption.name
				} : null;
			})
			.filter(Boolean); // 过滤掉 null 值
	}
}


async function confirmAuthorize() {
  const body = {
    ...(radio.value === '2' ? {} : { authorized_shops: shopTags.value.map((tag: any) => tag.id) }),
    user_id: rowData?.id,
    is_authorized_all_shops: radio.value === '2'
  };
  try {
    const resp = await useResponse(api.postAuthorize, body, loading);
    if (resp.code === 2000) {
      ElMessage.success('编辑成功！');
      fetchAuthorizedShop();
    }
  } catch (error) {
    ElMessage.error('编辑失败！');
  } finally {
    shopSelect.value = '';
  }
}

function cancelDialog() {
  shopSelect.value = '';
  shopTags.value = [];
  noticeDialog.value.visible = false;
}

function radioChange(val: any) {
  if (val == 2) {
    shopSelect.value = '';
  }
}

</script>

<template>
  <div>
    <el-dialog
        ref="noticeDialog"
        class="authorize-dialog"
        v-model="dialogVisible"
        :before-close="handleClose"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        title="店铺授权"
        width="40%"
    >
      <el-row class="mb-2">
        <el-col>
          <el-radio-group v-model="radio" @change="radioChange">
            <el-radio value="1"><span class="mr-2 font-medium">店 铺</span>
              <el-select v-model="shopSelect" :disabled="radio=='2'" filterable placeholder="输入搜索"
                         style="width: 200px;"
                         @change="addShopChange">
                <el-option
                    v-for="item in shopOptions"
                    :key="item.id"
                    :disabled="isOptionDisabled(item.id)"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-radio>
            <el-radio value="2">所有店铺</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mb-4">
        <el-col :span="2">
        </el-col>
      </el-row>
      <div class="flex flex-wrap gap-1.5 min-h-14">
        <el-tag
            v-for="tag in shopTags"
            v-show="radio=='1'"
            :key="tag.id"
            closable
            effect="plain"
            round
            @close="removeTag(tag)">
          {{ tag.name }}
        </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="loading" type="primary" @click="confirmAuthorize">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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