<template>
  <div class="page-wrap page-wrap-put-books">
    <tool-bar
      :text="['advertiser_id']"
      :label="['账户信息']"
      :placeholder="['请输入账户名称或ID']"
      v-model:loading="inSearching"
      @confirm="onSearch"
    >
      <template #picker>
        <p class="label">日期</p>
        <a-range-picker
          v-model:value="pickered"
          :ranges="rangePick"
          format="YYYY/MM/DD"
          @change="changeTime"
        />
      </template>
      <template v-if="!!showDropDownBox">
        <div class="tool-bar-item">
          <p class="label">推广员</p>
          <a-select
            mode="multiple"
            v-model:value="uids"
            placeholder="请选择推广员"
            style="width: 300px"
          >
            <a-select-option
              v-for="user in available_uids"
              :key="user.id"
              :value="user.id"
            >
              {{ user.nickname }}
            </a-select-option>
          </a-select>
        </div>
      </template>
    </tool-bar>
    <template v-if="showTable">
      <a-table
        :columns="columns"
        :data-source="list"
        :pagination="tablePageOptions"
        bordered
        :loading="tableLoading"
        :scroll="{ y: scrollY, x: 1200 }"
        size="small"
        @change="handleTableChange"
        rowKey="id"
      >
        <template #info="{ record }">
          <p
            @click="goAdlgroup(record.advertiser_id)"
            class="small-font single-line"
          >
            <a href="javascript:;">{{ record.advertiser_name }}</a>
          </p>
          <p
            @click="goAdlgroup(record.advertiser_id)"
            class="small-font single-line"
          >
            <a style="color: rgb(160, 160, 160)" href="javascript:;"
              >ID：{{ record.advertiser_id }}</a
            >
          </p>
        </template>

        <template #budget="{ record }">
          <editable-cell
            :text="
              record.budget_mode == 'BUDGET_MODE_INFINITE'
                ? '不限'
                : record.budget
            "
            title="预算"
            :minValue="1000"
            :muliteType="true"
            customTitle="不限"
            customValue="不限"
            @change="(val) => onCellChange(record, 'budget', val)"
          />
        </template>
        <template #operte="{ text, record }">
          <editable-cell
            :text="`${text}`"
            :minValue="0"
            title="回传最小金额设置"
            @change="(val) => onCellChange(record, 'min_amout', val)"
          />
        </template>
      </a-table>
    </template>
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  onMounted,
  computed,
} from "vue";
import { picker } from "@/helper/config/range";
import ToolBar from "@/components/tool-bar/index.vue";
import moment from "moment";
import useApp from "@/hooks/useApp";
import { MutationType } from "@/store/modules/app/_type";
import { AdCoundCloumn } from "../_pageOptions/table-put";
import {
  getAdgroupData,
  setGroupStatus,
  setGroupDay,
  ALLAcountGroupData,
  setBackMinimum,
} from "@/api";
import usePagination from "@/hooks/usePagination";
import EditableCell from "@/components/edit-cell/index.vue";
import { AdgroupList, PageOptions } from "#/api";
import useAuthUser from "@/hooks/composable/useAuthUser";

const Adgroup = defineComponent({
  components: {
    ToolBar,
    EditableCell,
  },
  setup() {
    let { loading, meta, tablePageOptions } = usePagination();
    const { showDropDownBox, available_uids } = useAuthUser();

    const { router, store } = useApp();

    console.log(moment(store.getters.selectTime[0]));
    const state = reactive({
      inSearching: false,
      open: false,
      inConfirm: false,
      list: ref<AdgroupList[]>([]),
      rangePick: picker,
      pickered: computed(() =>
        store.getters.selectTime.length > 0
          ? [
              moment(store.getters.selectTime[0]),
              moment(store.getters.selectTime[1]),
            ]
          : [moment().subtract(30, "d"), moment()]
      ),
      columns: ref<any[]>([]),
      uids: ref<number[]>([]),
      fields: {},
      tableLoading: false,
      cost_order: 0,
      convert_order: 0,
      convert_cost_order: 0,
      balance_order: 0,
      showTable: false,
      scrollY: 600,
    });

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

    const getData = async (query?: {
      current: number;
      advertiser_id?: string;
      account_id?: string;
    }) => {
      try {
        state.tableLoading = true;
        loading.value = true;
        let [begin_dates, end_dates] = state.pickered;
        let begin_date, end_date;
        if (begin_dates && end_dates) {
          begin_date = moment(begin_dates).format("YYYY-MM-DD");
          end_date = moment(end_dates).format("YYYY-MM-DD");
        }
        let datas = Object.assign(
          {
            begin_date,
            end_date,
            advertiser_id: query?.advertiser_id,
            account_id: query?.account_id,
            page: query?.current ?? 1,
          },
          {
            cost_order: state.cost_order,
            convert_order: state.convert_order,
            convert_cost_order: state.convert_cost_order,
            balance_order: state.balance_order,
            uids: state.uids.toString(),
          }
        );
        const { data } = await getAdgroupData(datas);
        const { data: totals } = await ALLAcountGroupData(datas);
        let sortList = ["cost", "convert", "convert_cost", "balance"];
        let mainCloumn = AdCoundCloumn.map((r) => {
          if (
            r.dataIndex != "firle" &&
            r.dataIndex !== "campaign_name" &&
            r.dataIndex !== "back_min_price"
          ) {
            r.children = [
              {
                title: totals[r.dataIndex],
                dataIndex: r.dataIndex,
                width: r.width,
                ellipsis: true,
                sorter: sortList.includes(r.dataIndex) ? true : false,
                sortDirections: ["descend", "ascend", false],
              },
            ];
          }
          return r;
        });
        state.columns = mainCloumn;
        state.list = data.list;
        meta.value = data.meta;
      } catch (error) {
        console.log("on get books list error");
      } finally {
        state.inSearching = false;
        state.tableLoading = false;
      }
    };
    const setSateSwitch = (val: string, name: string) => {
      state.cost_order = 0;
      state.convert_order = 0;
      state.convert_cost_order = 0;
      state.balance_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
    ) => {
      console.log(sorter.columnKey);
      if (sorter.columnKey == "cost") {
        setSateSwitch(sorter.order, "cost_order");
      }
      if (sorter.columnKey == "balance") {
        setSateSwitch(sorter.order, "balance_order");
      }
      if (sorter.columnKey == "convert") {
        setSateSwitch(sorter.order, "convert_order");
      }
      if (sorter.columnKey == "convert_cost") {
        setSateSwitch(sorter.order, "convert_cost_order");
      }
      const { current, pageSize, total } = pagination;
      let data = Object.assign({ current, ...state.fields });
      getData(data);
    };
    const goAdlgroup = (id: string) => {
      router.push({ path: "/put/datas/group", query: { advertiser_id: id } });
    };
    const changeTime = (monent: any, string: string[]) => {
      if (Array.isArray(string) && string.join("")) {
        store.commit(MutationType.setSelectTime, string);
      }
    };
    onMounted(getData);
    return {
      ...toRefs(state),
      showDropDownBox,
      available_uids,
      loading,
      tablePageOptions,
      onSearch,
      handleTableChange,
      goAdlgroup,
      changeTime,
    };
  },
  mounted() {
    let winHeight =
      document.documentElement.clientHeight || document.body.clientHeight;
    this.scrollY = winHeight - 237;
    this.showTable = true;
  },
  methods: {
    moment,
    onCellChange(record: any, dataIndex: string, value: string) {
      if (dataIndex === "budget") {
        let data = {
          advertiser_id: record.advertiser_id,
          budget_mode:
            value == "不限" ? "BUDGET_MODE_INFINITE" : "BUDGET_MODE_DAY",
          budget: value == "不限" ? "0" : Number(value),
        };
        setGroupDay(data).then((res) => {
          this.$message.success("修改成功！");
        });
      } else {
        let data = {
          advertiser_id: record.advertiser_id,
          back_min_price: value,
        };
        setBackMinimum(data).then((res) => {
          this.$message.success("修改成功！");
        });
      }
    },
  },
});

export default Adgroup;
</script>
