<template>
  <div class="page-wrap page-wrap-put-books">
    <tool-bar
      :text="['official_name', 'book_name']"
      :label="['公众号名称', '书籍名称']"
      v-model:loading="searching"
      @confirm="onSearch"
    />
    <div class="operator-bar">
      <a-button type="primary" @click="open = true">添加</a-button>
    </div>
    <a-table
      row-key="id"
      :pagination="tablePageOptions"
      :loading="loading"
      :columns="columns"
      :data-source="list"
      bordered
      :scroll="{ y: 500 }"
      @change="onBookLoaded"
    >
      <template #official_name="{record}">
        <p @click="goPushData(record)">
          <a href="javascript:;">{{record.official_name}}</a>
        </p>
      </template>
      <template #time="{record}">
        <p>起:{{ record.start_time }}</p>
        <p v-show="record.end_time">止:{{ record.end_time }}</p>
      </template>
      <template #link="{record}">
        <p
          v-clipboard:copy="record.monitor_link"
          v-clipboard:success="copySuccess"
          v-show="record.monitor_link"
        >
          <a>复制监测链接</a>
        </p>
      </template>
      <template #operator="{record}">
        <confirm-button
          :label="record.status ? '停止' : '已停止'"
          :disabled="!record.status"
          type="link"
          confirm-content="确定要停止该条内容吗？"
          @click="onStop(record)"
        />
      </template>
    </a-table>
    <!-- 添加 -->
    <a-modal
      title="投放书籍添加"
      width="400px"
      destroy-on-close
      v-model:visible="open"
      :confirm-loading="inConfirm"
      :after-close="onReset"
      @ok="onAdd"
    >
      <a-form
        :model="addFormState"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-form-item label="公众号名称">
          <a-select v-model:value="addFormState.official_id">
            <a-select-option
              v-for="official in officials"
              :key="official.value"
              :value="official.value"
            >
              {{ official.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="书籍">
          <a-popover :title="addFormState.book.name">
            <template #content>
              <div class="popover-book-info" v-if="addFormState.book.id">
                <p>
                  书籍Bid: <span>{{ addFormState.book.bid }}</span>
                </p>
                <p>
                  书籍Channel: <span>{{ addFormState.book.channel_name }}</span>
                </p>
                <p>
                  上架状态: <span>{{ addFormState.book.is_on_shelf }}</span>
                </p>
                <p>
                  上架时间: <span>{{ addFormState.book.shelf_time }}</span>
                </p>
              </div>
              <p v-else>请先输入要选择的书籍</p>
            </template>
            <a-select
              show-search
              placeholder="请输入要搜索的书名"
              not-found-content="暂无数据"
              :default-active-first-option="false"
              :filter-option="false"
              :show-arrow="false"
              :value="addFormState.book.bid"
              @search="onBookSearch"
              @change="onBookCheck"
            >
              <a-select-option
                v-for="book in addFormState.books"
                :value="book.bid"
                :key="book"
              >
                {{ book.name }}
              </a-select-option>
            </a-select>
          </a-popover>
        </a-form-item>
        <a-form-item label="流量平台">
          <a-select v-model:value="addFormState.platform">
            <a-select-option
              v-for="platform in platforms"
              :key="platform.value"
              :value="platform.value"
            >
              {{ platform.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  reactive,
  ref,
  computed,
  toRefs,
  onMounted,
} from "vue";

import ToolBar from "@/components/tool-bar/index.vue";
import ConfirmButton from "@/components/confirm-button/index.vue";

import useApp from "@/hooks/useApp";
import usePagination from "@/hooks/usePagination";
import useFormLayout from "@/hooks/useFormLayout";
import useDebounceFn from "@/hooks/useDebounceFn";
import useValidate from "@/hooks/useValidate";
import useReset from "@/hooks/useReset";

import {
  getDeliveryBookList,
  getBooksByName,
  addDeliveryBook,
  onStopDeliveryBook,
} from "@/api";
import { TableColumnOfPutBooks } from "../_pageOptions/table-put";
import { IBookSearchResult, IDeliveryBook } from "#/api";

const PutBooks = defineComponent({
  components: {
    ToolBar,
    ConfirmButton,
  },
  setup() {
    let { loading, meta, tablePageOptions } = usePagination();

    const { store, router, route } = useApp();
    const { labelCol, wrapperCol } = useFormLayout();

    const state = reactive({
      officials: computed(() => store.getters.officials),
      platforms: computed(() => store.getters.platforms),
      searching: false,
      open: false,
      inConfirm: false,
      list: ref<IDeliveryBook[]>([]),
      columns: TableColumnOfPutBooks,
      official_name: "",
      book_name: "",
    });
    const addFormState = reactive({
      official_id: "",
      book: ref<Partial<IBookSearchResult>>({}),
      platform: "",
      books: ref<IBookSearchResult[]>([]),
    });

    const onSearch = (fields: Record<string, string>) => {
      const { official_name, book_name } = fields;
      state.official_name = official_name;
      state.book_name = book_name;
      onBookLoaded();
    };

    const onBookLoaded = async (query?: { current: number }) => {
      try {
        loading.value = true;
        const { official_name, book_name } = state;
        const { data } = await getDeliveryBookList({
          official_name,
          book_name,
          page: query?.current ?? 1,
        });
        state.list = data.list;
        meta.value = data.meta;
      } catch (error) {
        console.log("on get books list error");
      } finally {
        state.searching = false;
      }
    };

    // 弹窗书籍搜索
    const onBookSearch = useDebounceFn(async (keywords: string) => {
      addFormState.books.length = 0;
      if (!keywords) return;
      const { data } = await getBooksByName(keywords);
      addFormState.books.push(...data.list);
    }, 500);

    const onBookCheck = (value: number, options: any) => {
      addFormState.book = options.key;
    };
    const goPushData = (record: any) => {
      router.push({
        path: "/put/data",
        query: { official_name: record.official_name },
      });
    };
    onMounted(onBookLoaded);

    return {
      ...toRefs(state),
      addFormState,
      loading,
      tablePageOptions,
      labelCol,
      wrapperCol,
      onBookSearch,
      onSearch,
      onBookCheck,
      onBookLoaded,
      goPushData,
    };
  },
  methods: {
    async onAdd() {
      try {
        // TODO 没做字段校验 字段校验封装
        this.inConfirm = true;
        const { official_id, platform, book } = this.addFormState;
        // useValidate({ official_id, platform });
        await addDeliveryBook(
          useValidate({
            delivery_bid: book.id!,
            official_id,
            platform,
          })
        );
        this.open = false;
        this.$message.success("添加成功");
        this.onBookLoaded();
        this.onReset();
      } catch (error) {
        console.log("error while add delivery book");
        error.message && this.$message.error(error.message);
      } finally {
        this.inConfirm = false;
      }
    },
    copySuccess() {
      this.$message.success("复制成功");
    },
    onReset() {
      this.addFormState = useReset(this.addFormState);
    },
    onStop(data: IDeliveryBook) {
      const { id } = data;
      onStopDeliveryBook(id).then((_) => {
        this.$message.success("停止成功");
        this.onBookLoaded();
      });
    },
  },
});

export default PutBooks;
</script>
