<template>
  <div class="page-wrap page-finacial">
    <tool-bar
      :text="['advertiser_id']"
      :label="['账户名称']"
      :placeholder="['请输入账户名称或ID']"
      v-model:loading="inSearching"
      @confirm="onSearch"
    >
      <template #picker>
        <p class="label">日期</p>
        <a-range-picker
          :ranges="rangePick"
          format="YYYY/MM/DD"
          v-model:value="pickered"
        />
      </template>
    </tool-bar>

    <a-table
      :columns="columns"
      :data-source="list"
      :scroll="{ x: 1500, y: 600 }"
      size="small"
      @change="handleTableChange"
      rowKey="id"
      bordered
      :pagination="tablePageOptions"
    >
      <template #advertiser="{ record }">
        <p class="small-font single-line">{{ record.advertiser_name }}</p>
        <p class="small-font single-line">ID:{{ record.advertiser_id }}</p>
      </template>
      <template #agent="{ record }">
        <p class="small-font single-line">{{ record.agent_name }}</p>
        <p class="small-font single-line">ID:{{ record.agent_id }}</p>
      </template>
    </a-table>
  </div>
</template>

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

import ToolBar from "@/components/tool-bar/index.vue";
import usePagination from "@/hooks/usePagination";
import { getFinanceList, getFinanceSum } from "@/api";
import { picker } from "@/helper/config/range";
import { PageOptions, FinanceData } from "#/api";
import moment from "moment";
import { TableColumnOfFinancial } from "../_pageOptions/table_financial";

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

    const state = reactive({
      inSearching: false,
      open: false,
      fields: ref<any>({}),
      inConfirm: false,
      list: ref<FinanceData[]>([]),
      rangePick: picker,
      cost_order: 0,
      balance_order: 0,
      cash_cost_order: 0,
      pickered: [moment().subtract(30, "d"), moment()],
      columns: ref<any[]>([]),
    });

    const onSearch = (fields: Record<string, string>) => {
      const { advertiser_id } = fields;
      state.fields = fields;
      getData({ current: 1 });
    };

    const getData = async (query?: { current: number }) => {
      try {
        loading.value = true;
        let [begin_dates, end_dates] = state.pickered;
        let start_ymd = moment(begin_dates).format("YYYY-MM-DD");
        let end_ymd = moment(end_dates).format("YYYY-MM-DD");
        let parmas = Object.assign(
          {
            cost_order: state.cost_order,
            balance_order: state.balance_order,
            cash_cost_order: state.cash_cost_order,
          },
          {
            start_ymd,
            end_ymd,
            page: query?.current ?? 1,
            advertiser_id: state.fields?.advertiser_id ?? "",
          }
        );
        const { data } = await getFinanceList(parmas);
        const { data: taotals } = await getFinanceSum(parmas);
        let sortList = ["cost", "balance", "cash_cost"];
        let newlist = TableColumnOfFinancial.map((r: any) => {
          r.children = [
            {
              title: taotals[r.dataIndex],
              dataIndex: r.dataIndex,
              width: r.width,
              ellipsis: true,
              sorter: sortList.includes(r.dataIndex) ? true : false,
              sortDirections: ["descend", "ascend", false],
              slots: r.slots ?? "",
            },
          ];
          if (r.dataIndex == "date") {
            r.children[0].title = "总计";
          }
          return r;
        });
        state.columns = newlist;
        state.list = data.list as Array<FinanceData>;
        meta.value = data.meta;
        console.log("TABLE", tablePageOptions);
      } catch (error) {
        console.log("on get books list error");
      } finally {
        state.inSearching = false;
      }
    };

    const setSateSwitch = (val: string, name: string) => {
      state.cost_order = 0;
      state.balance_order = 0;
      state.cash_cost_order = 0;
      switch (val) {
        case "ascend":
          (state as any)[name] = 2;
          break;
        case "descend":
          (state as any)[name] = 1;
          break;
        default:
          (state as any)[name] = 0;
      }
    };

    const handleTableChange = (
      pagination: PageOptions,
      filters: any,
      sorter: any
    ) => {
      if (sorter.columnKey == "cost") {
        setSateSwitch(sorter.order, "cost_order");
      }
      if (sorter.columnKey == "balance") {
        setSateSwitch(sorter.order, "balance_order");
      }
      if (sorter.columnKey == "cash_cost") {
        setSateSwitch(sorter.order, "cash_cost_order");
      }
      const { current, pageSize, total } = pagination;
      getData({ current: current });
    };

    onMounted(getData);

    return {
      ...toRefs(state),
      loading,
      tablePageOptions,
      onSearch,
      handleTableChange,
    };
  },
  methods: {
    moment,
  },
});

export default Finance;
</script>
