<script lang="ts" setup>
/**
 * @Name: AttributeManage.vue
 * @Description: 属性管理
 * @Author: Cheney
 */

import { usePagination } from '/@/utils/usePagination';
import { useTableData } from '/@/utils/useTableData';
import * as api from '../api';
import { AttributeManageColumns } from '/@/views/sku-manage/Columns';
import { Delete, InfoFilled, Operation, Plus, Position, Refresh } from '@element-plus/icons-vue';
import { getTagType } from '/@/utils/useTagColor';
import PermissionButton from '/@/components/PermissionButton/index.vue';
import AttributeManageEdit from '/@/views/sku-manage/product-category/component/AttributeManageEdit.vue';
import { useResponse } from '/@/utils/useResponse';
import { ElMessage } from 'element-plus';
import AttributeManageCreate from '/@/views/sku-manage/product-category/component/AttributeManageCreate.vue';
import { hasPermission } from '/@/utils/hasPermission';


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

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

const emit = defineEmits([ 'refresh' ]);

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

const { tableOptions, handlePageChange } = usePagination(fetchList);

const gridRef = ref();
const gridOptions: any = reactive({
  id: 'product-attribute-table',
  keepSource: true,
  size: 'small',
  border: false,
  round: true,
  stripe: true,
  currentRowHighLight: true,
  height: '100%',
  customConfig: {
    storage: true
  },
  toolbarConfig: {
    size: 'large',
    custom: true,
    slots: {
      buttons: 'toolbar_buttons',
      tools: 'toolbar_tools'
    }
  },
  rowConfig: {
    isHover: true
  },
  columnConfig: {
    resizable: true
  },
  pagerConfig: {
    total: tableOptions.value.total,
    page: tableOptions.value.page,
    limit: tableOptions.value.limit
  },
  loading: false,
  loadingConfig: {
    icon: 'vxe-icon-indicator roll',
    text: '正在拼命加载中...'
  },
  columns: '',
  data: ''
});

const editOpen = ref(false);
const createOpen = ref(false);
const editRow = ref({});

onBeforeMount(() => {
  fetchList();
});

async function fetchList(isQuery = false) {
  if (isQuery) {
    gridOptions.pagerConfig.page = 1;
  }

  gridOptions.data = [];
  gridOptions.columns = [];

  const query = {
    kind: rowData.id
  };

  await useTableData(api.getAttributeManageData, query, gridOptions);
  await gridRef.value.loadColumn(AttributeManageColumns);
  gridOptions.showHeader = Boolean(gridOptions.data?.length);
}

function handleRefresh() {
  fetchList();
}

function handleEdit(row: any) {
  editOpen.value = true;
  editRow.value = row;
}

async function onConfirm(row: any) {
  const res = await useResponse(api.deleteProductAttr, row.id);
  if (res.code === 2000) {
    ElMessage.error({ message: '已删除!', plain: true, icon: 'Delete' });
    handleRefresh();
  }
}

async function handleCreate() {
  createOpen.value = true;
}

async function handleRelease() {
  const query = {
    id: rowData.id,
    partial: 1,
    status: 3
  };

  const res = await useResponse(api.release, query);
  if (res.code === 2000) {
    ElMessage.success({ message: '发布成功', plain: true, icon: 'Position' });
    closeDrawer();
    emit('refresh');
  }
}

async function handleUpdate(row: any) {
  const query = {
    id: row.id,
    attr: row.attr.id,
    order: row.order,
    kind: row.kind.id,
    section: row.section,
    status: row.status
  };

  const res = await useResponse(api.updateOrder, query);
  if (res.code === 2000) {
    ElMessage.success({ message: '修改成功', plain: true, icon: 'EditPen' });
    handleRefresh();
  }
}

function closeDrawer() {
  editDrawer.value.handleClose();
}

function refreshOuter() {
  closeDrawer();
  emit('refresh');
}

const gridEvents = {
  custom({ type }: any) {
    if (type == 'confirm') {
      fetchList();
    }
  }
};

</script>

<template>
  <div class="drawer-container">
    <el-drawer ref="editDrawer"
               v-model="visible"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               direction="btt"
               size="80%"
    >
      <template #title>
        <div class="font-medium text-xl flex">
          产品属性管理：
          <el-check-tag :checked="true" class="italic" style="pointer-events: none;" type="primary">
            <span style="font-size: 1.1rem">
              {{ rowData.name }}
            </span>
          </el-check-tag>
        </div>
      </template>
      <div class="h-full p-3">
        <vxe-grid ref="gridRef"
                  v-bind="gridOptions"
                  v-on="gridEvents">
          <template #toolbar_buttons>
            <div class="flex gap-2">
              <div v-if="hasPermission('SkuKindAttrCreate')">
                <PermissionButton :icon="Plus" plain round type="primary" @click="handleCreate">
                  新 增
                </PermissionButton>
              </div>
              <div v-else-if="hasPermission('SkuKindPublish')">
                <el-popconfirm :icon="InfoFilled" icon-color="#626AEF" title="发布后将无法更改, 是否继续?"
                               width="230" @confirm="handleRelease">
                  <template #reference>
                    <PermissionButton :color="'#6466F1'" :icon="Position" plain round>
                      发 布
                    </PermissionButton>
                  </template>
                  <template #actions="{ confirm, cancel }">
                    <el-button size="small" @click="cancel">No!</el-button>
                    <el-button :color="'#6466F1'" size="small" @click="confirm">Yes?</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </template>
          <template #toolbar_tools>
            <el-button circle class="toolbar-btn mr-3" @click="handleRefresh">
              <el-icon>
                <Refresh />
              </el-icon>
            </el-button>
          </template>
          <template #pager>
            <vxe-pager
                v-model:currentPage="gridOptions.pagerConfig.page"
                v-model:pageSize="gridOptions.pagerConfig.limit"
                :total="gridOptions.pagerConfig.total"
                class="mt-1.5"
                @page-change="handlePageChange"
            />
          </template>
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
          <template #placement="{ row }">
            <el-tag :type=getTagType(row.section) effect="plain" round>
              第{{ row.section }}部分
            </el-tag>
          </template>
          <template #attribute="{ row }">
            <el-tag :type=getTagType(row.attr.name)>
              {{ row.attr.name }}
            </el-tag>
          </template>
          <template #order="{ row }">
            <el-input-number v-model="row.order" :max="100" :min="1" size="small" @change="handleUpdate(row)" />
          </template>
          <template #update_datetime="{ row }">
            {{ row.update_datetime }}
          </template>
          <template #create_datetime="{ row }">
            {{ row.create_datetime }}
          </template>
          <template #operate="{ row }">
            <div class="flex justify-center gap-2">
              <div v-if="hasPermission('SkuKindAttrUpdate')">
                <PermissionButton :disabled="row.is_competitors" circle plain type="warning" @click="handleEdit(row)">
                  <el-icon>
                    <Operation />
                  </el-icon>
                </PermissionButton>
              </div>
              <div v-if="hasPermission('SkuKindAttrDelete')">
                <el-popconfirm
                    :icon="InfoFilled"
                    icon-color="#626AEF"
                    title="你确定要删除此项吗?"
                    width="220"
                    @confirm="onConfirm(row)"
                >
                  <template #reference>
                    <PermissionButton circle plain type="danger">
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </PermissionButton>
                  </template>
                  <template #actions="{ confirm, cancel }">
                    <el-button size="small" @click="cancel">No!</el-button>
                    <el-button
                        size="small"
                        type="danger"
                        @click="confirm"
                    >
                      Yes?
                    </el-button>
                  </template>
                </el-popconfirm>
              </div>
              <div v-if="!hasPermission('SkuKindAttrUpdate') && !hasPermission('SkuKindAttrDelete')">
                <el-tag type="warning">暂无权限</el-tag>
              </div>
            </div>
          </template>
        </vxe-grid>
      </div>
    </el-drawer>
    <AttributeManageEdit v-if="editOpen" v-model="editOpen" :row-data="editRow" @refresh="handleRefresh" />
    <AttributeManageCreate v-if="createOpen" v-model="createOpen" :row-data="rowData" @refresh="refreshOuter" />
  </div>
</template>

<style scoped>
.drawer-container :deep(.el-drawer__header) {
  border-bottom: none;
  font-weight: 500;
}

.drawer-container :deep(.el-drawer__title) {
  font-size: 18px;
}
</style>
