<script lang="tsx">
import { provide, ref } from 'vue';
import { TABS_LIST, RawMaterialType, INITIAL_QUERY, TABLE_COLUMNS } from './constants';

import { Tabs, TabPane, Button, Pagination } from 'ant-design-vue';
import FilterBlock from './components/filter-block/index.vue';
import RawMaterialTable from './components/table/index.vue';
import DeleteRawMaterialModal from './components/table/delete-file-modal.vue';
import TagsManageModal from './components/tags-manage-modal';
import AddRawMaterialDrawer from './components/add-raw-material-drawer';
import EditRawMaterialDrawer from './components/edit-raw-material-modal';

import { useTableSelectionWithPagination } from '@/hooks/useTableSelectionWithPagination';
import { getRawMaterialsPage } from '@/api/all/generationWorkshop';

import icon3 from '@/assets/img/media-account/icon-tag.png';

export default defineComponent({
  setup(_, { attrs, slots, expose }) {
    const {
      dataSource,
      pageInfo,
      onPageChange,
      selectedRowKeys,
      selectedRows,
      handleSelect,
      handleSelectAll,
      resetPageInfo,
    } = useTableSelectionWithPagination({
      onPageChange: () => {
        getData();
      },
    });

    const deleteRawMaterialModalRef = ref(null);
    const tagsManageModalRef = ref(null);
    const addRawMaterialDrawerRef = ref(null);
    const editRawMaterialDrawerRef = ref(null);

    const query = ref(cloneDeep(INITIAL_QUERY));
    const handleSearch = () => {
      getData();
    };
    const getData = async () => {
      const { page, page_size } = pageInfo.value;
      const { code, data } = await getRawMaterialsPage({
        ...query.value,
        page,
        page_size,
      });
      if (code === 200) {
        dataSource.value = data?.data ?? [];
        pageInfo.value.total = data.total;
      }
    };
    const reload = () => {
      pageInfo.value.page = 1;
      getData();
    };
    const handleReset = () => {
      resetPageInfo();
      query.value = cloneDeep(INITIAL_QUERY);
      reload();
    };
    const handleSorterChange = (column, order) => {
      query.value.sort_column = column;
      query.value.sort_order = order;
      reload();
    };

    const handleBatchDelete = () => {
      const ids = selectedRows.value.map((item) => item.id);
      const names = selectedRows.value.map((item) => `"${item.name || '-'}` + '"').join('，');

      deleteRawMaterialModalRef.value?.open({ id: ids, name: names });
    };

    const handleDelete = (item) => {
      const { id, name } = item;
      deleteRawMaterialModalRef.value?.open({ id, name: `“${name}”` });
    };

    const handleEdit = (item) => {
      editRawMaterialDrawerRef.value?.open(item.id);
    };

    const handleTabClick = (key) => {
      query.value.type = key;
      reload();
    };

    const onBatchSuccess = () => {
      selectedRows.value = [];
      selectedRowKeys.value = [];
      getData();
    };

    const handleOpenTagsModal = () => {
      tagsManageModalRef.value?.open();
    };
    const handleAddMaterial = () => {
      addRawMaterialDrawerRef.value?.open();
    };

    onMounted(() => {
      getData();
    });

    return () => (
      <div class="raw-material-wrap h-full flex flex-col">
        <div class="bg-white rounded-t-8px">
          <Tabs
            v-model:activeKey={query.value.type}
            onTabClick={handleTabClick}
            v-slots={{
              rightExtra: () => (
                <div class="flex items-center">
                  <Button
                    type="primary"
                    ghost
                    size="medium"
                    onClick={handleOpenTagsModal}
                    v-slots={{
                      icon: () => <img src={icon3} width="16" height="16" class="mr-8px" />,
                    }}
                  >
                    标签管理
                  </Button>
                  <Button
                    type="primary"
                    size="medium"
                    class="ml-12px"
                    onClick={handleAddMaterial}
                    v-slots={{
                      icon: () => <icon-plus size="16" class="mr-8px" />,
                      default: () => '上传原料',
                    }}
                  />
                </div>
              ),
            }}
          >
            {TABS_LIST.map((item) => (
              <TabPane key={item.value} tab={item.label}>
                {item.label}
              </TabPane>
            ))}
          </Tabs>
        </div>
        <div class="filter-wrap bg-#fff rounded-b-8px  mb-16px">
          <FilterBlock v-model:query={query.value} onSearch={handleSearch} onReset={handleReset} />
        </div>
        <div class="table-wrap bg-#fff rounded-8px px-24px py-24px flex flex-col">
          <div class="flex justify-end mb-12px">
            <Button
              type="primary"
              ghost
              class="w-fit"
              size="medium"
              onClick={handleBatchDelete}
              disabled={!selectedRows.value.length}
            >
              批量删除
            </Button>
          </div>

          <RawMaterialTable
            tableColumns={TABLE_COLUMNS}
            selectedRowKeys={selectedRowKeys.value}
            dataSource={dataSource.value}
            onSorterChange={handleSorterChange}
            onDelete={handleDelete}
            onSelect={handleSelect}
            onSelectAll={handleSelectAll}
            onEdit={handleEdit}
          />
          {pageInfo.value.total > 0 && (
            <div class="pagination-row">
              <Pagination
                total={pageInfo.value.total}
                size="small"
                showTotal={(total: number) => `共 ${total} 条记录`}
                showSizeChanger
                showQuickJumper
                current={pageInfo.value.page}
                pageSize={pageInfo.value.page_size}
                onChange={onPageChange}
              />
            </div>
          )}
        </div>

        <TagsManageModal ref={tagsManageModalRef} />
        <AddRawMaterialDrawer ref={addRawMaterialDrawerRef} onUpdate={getData} />
        <EditRawMaterialDrawer ref={editRawMaterialDrawerRef} onUpdate={getData} />
        <DeleteRawMaterialModal ref={deleteRawMaterialModalRef} onBatchUpdate={onBatchSuccess} onUpdate={getData} />
      </div>
    );
  },
});
</script>

<style scoped lang="scss">
@import './style.scss';
</style>
