<template>
  <div class="page-wrap page-wrap-put-books">
    <tool-bar
      ref="toolbarref"
      :text="['campaign_id', 'advertiser_id']"
      :label="['广告组名称', '所属账户']"
      :placeholder="['请输入广告组名称或ID', '请输入所属账户']"
      :defaultVal="defaultToolvalue"
      v-model:loading="inSearching"
      @confirm="onSearch"
    >
      <div class="tool-bar-item">
        <p class="label">广告组状态</p>
        <a-select class="full-width" v-model:value="is_enable" allowClear>
          <a-select-option :value="1">启用</a-select-option>
          <a-select-option :value="0">不启用</a-select-option></a-select
        >
      </div>
      <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"
        rowKey="id"
        size="small"
        bordered
        :loading="tableLoading"
        :scroll="{ x: 1300, y: scrollY }"
        @change="handleTableChange"
      >
        <template #adgroup="{ record }">
          <p
            class="small-font"
            @click="goAdlgroup(record.advertiser_id, record.campaign_id)"
          >
            <a href="javascript:;">{{ record.campaign_name }} </a>
            <span style="display: block; color: gray; font-size: 12px"
              >ID:{{ record.campaign_id }}</span
            >
          </p>
        </template>
        <template #advertiser="{ record }">
          <p>
            <span style="font-size: 13px; color: gray"
              >{{ record.advertiser_name }}
            </span>
            <span style="display: block; color: gray; font-size: 12px"
              >ID:{{ record.advertiser_id }}</span
            >
          </p>
        </template>
        <template #switch="{ record }">
          <a-switch
            v-model:checked="record.is_enable"
            @change="switchMethod(record)"
          />
        </template>
        <template #budget="{ record }">
          <a href="javascript:;" @click="changeBudget(record)">{{
            record.budget
          }}</a>
        </template>
      </a-table>
    </template>
    <a-modal
      v-model:visible="visibleChange"
      title="修改组预算"
      @ok="popConfirm"
    >
      <div class="flex-box pop-group">
        <label>组预算</label
        ><a-input prefix="￥" v-model:value="tempBudget">
          <template #suffix>
            <a-tooltip
              title="广告组日预算不能低于300元,预算单次修改幅度不能低于100元)"
            >
              元(查看规则)
            </a-tooltip>
          </template>
        </a-input>
      </div>
      <div>无输入则不限预算</div>
    </a-modal>
  </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 { message } from "ant-design-vue";
import { AdgroupCloumn } from "../_pageOptions/table-put";
import useApp from "@/hooks/useApp";
import {
  getAdgroupList,
  setGroupStatus,
  ALLadGroupData,
  changeAdgroupBudget,
} from "@/api";
import usePagination from "@/hooks/usePagination";
import { MutationType } from "@/store/modules/app/_type";
import { AdGroupData, PageOptions, GroupDatas } from "#/api";
import useAuthUser from "@/hooks/composable/useAuthUser";

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

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

    const state = reactive({
      is_enable: "",
      inSearching: false,
      visibleChange: false,
      open: false,
      curentItem: ref<any>({}),
      inConfirm: false,
      list: ref<any[]>([]),
      rangePick: picker,
      cost_order: 0,
      tempBudget: 0,
      convert_order: 0,
      convert_cost_order: 0,
      showTable: false,
      scrollY: 600,
      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[]>([]),
      fields: {},
      tableLoading: false,
      defaultToolvalue: {},
      uids: ref<number[]>([]),
    });
    if (route.query && route.query.advertiser_id) {
      state.defaultToolvalue = {
        advertiser_id: route.query.advertiser_id as string,
      };
      // state.fields = {
      //   advertiser_id: route.query.advertiser_id as string,
      // };
    }

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

    const getData = async (query?: {
      current: number;
      advertiser_id?: any;
      campaign_id?: string;
      is_enable?: any;
    }) => {
      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,
            campaign_id: query?.campaign_id,
            is_enable: query?.is_enable,
            page: query?.current ?? 1,
          },
          {
            cost_order: state.cost_order,
            convert_order: state.convert_order,
            convert_cost_order: state.convert_cost_order,
            uids: state.uids.toString(),
          }
        );
        const { data } = await getAdgroupList(datas);
        const { data: totals } = await ALLadGroupData(datas);

        let mewList = data.list.map((item) => {
          typeof item.is_enable;
          item.is_enable = !!item.is_enable;
          return item;
        });
        let sortList = ["cost", "convert", "convert_cost"];
        let mainCloumn = AdgroupCloumn.map((r) => {
          if (r.dataIndex != "check" && r.dataIndex !== "campaign_name") {
            r.children = [
              {
                title: totals[r.dataIndex],
                dataIndex: r.dataIndex,
                width: r.width,
                sorter: sortList.includes(r.dataIndex) ? true : false,
                sortDirections: ["descend", "ascend", false],
                ellipsis: true,
              },
            ];
            if (r.slots) {
              r.children[0].slots = r.slots;
            }
          }
          if (r.dataIndex == "budget") {
            console.log(r);
          }
          return r;
        });
        state.columns = mainCloumn;
        state.list = mewList;
        meta.value = data.meta;
        state.tableLoading = false;
      } catch (error) {
        console.log("on get books list error");
      } finally {
        state.inSearching = false;
        state.tableLoading = false;
      }
    };
    const changeBudget = (record: any) => {
      state.visibleChange = true;
      state.curentItem = record;
      state.tempBudget = record.budget;
    };
    const setSateSwitch = (val: string, name: string) => {
      state.cost_order = 0;
      state.convert_order = 0;
      state.convert_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
    ) => {
      console.log(1)
      console.log(toolbarref.value);
      if (sorter.columnKey == "cost") {
        setSateSwitch(sorter.order, "cost_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 fields = toolbarref.value.returnFields();
      const { advertiser_id, campaign_id } = fields;
      //加入筛选条件是否启用
      let is_enable = state.is_enable
      let data = Object.assign({ current,advertiser_id,campaign_id,is_enable, ...state.defaultToolvalue });
      getData(data);
    };
    const popConfirm = () => {
      let budget = state.tempBudget;
      let data = {
        campaign_id: state.curentItem.campaign_id,
        budget_mode: "",
        budget: 0,
      };
      if (budget && Number(budget) > 0) {
        data.budget_mode = "BUDGET_MODE_DAY";
        if (budget < 300) {
          message.error("广告预算必须大于300");
          return false;
        }
        if (Math.abs(state.curentItem.budget - budget) < 100) {
          message.error("单次修改幅度不能低于100元");
          return false;
        }
        data.budget = budget;
      } else {
        data.budget_mode = "BUDGET_MODE_INFINITE";
      }
      changeAdgroupBudget(data).then((res: any) => {
        if (!res.code) {
          message.error("修改预算成功！");
          location.reload();
        }
      });
    };
    onMounted(() => {
      getData({
        advertiser_id: route.query?.advertiser_id ?? "",
        current: 1,
      });
    });
    const goAdlgroup = (id: string, campaign_id: string) => {
      let begin_date, end_date;
      if (state.pickered) {
        let [begin_dates, end_dates] = state.pickered;
        if (begin_dates && end_dates) {
          begin_date = moment(begin_dates).format("YYYY-MM-DD");
          end_date = moment(end_dates).format("YYYY-MM-DD");
        }
      }
      router.push({
        path: "/put/datas/ad-plan",
        query: { campaign_id, begin_date, end_date },
      });
    };

    const changeTime = (monent: any, string: string[]) => {
      if (Array.isArray(string) && string.join("")) {
        store.commit(MutationType.setSelectTime, string);
      }
    };

    return {
      ...toRefs(state),
      showDropDownBox,
      available_uids,
      loading,
      tablePageOptions,
      onSearch,
      handleTableChange,
      goAdlgroup,
      changeTime,
      changeBudget,
      popConfirm,
      toolbarref,
    };
  },
  mounted() {
    let winHeight =
      document.documentElement.clientHeight || document.body.clientHeight;
    this.scrollY = winHeight - 237;
    this.showTable = true;
  },
  methods: {
    moment,
    switchMethod(record: any) {
      let data = {
        campaign_id: record.campaign_id,
        status: Number(!record.is_enable) == 1 ? "enable" : "disable",
      };
      setGroupStatus(data).then((res) => {
        this.$message.success("状态修改成功");
      });
    },
  },
});

export default Adgroup;
</script>
<style lang="less" scoped>
.pop-group {
  label {
    width: 100px;
  }
}
</style>
