<template>
  <div class="page-wrap page-wrap-put-books">
    <tool-bar
      :text="['official_name', 'book_name']"
      :label="['公众号名称', '书名']"
      :defaultVal="defaultToolvalue"
      @confirm="onSearch"
      v-model:loading="inSearching"
    >
      <template #picker>
        <p class="label">日期</p>
        <a-range-picker
          :ranges="rangePick"
          format="YYYY/MM/DD"
          v-model:value="pickered"
          @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>

    <div class="table-filter">
      <div class="item-right">
        <span class="label">自定义天数</span>
        <a-input-number
          id="inputNumber"
          v-model:value="filterNumber"
          :min="1"
          :max="120"
        />
      </div>
      <a-button type="primary" @click="changeNumber"> 修改天数 </a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="list"
      :pagination="tablePageOptions"
      :scroll="{ x: 1200, y: 600 }"
      @change="handleTableChange"
      size="small"
      bordered
    >
      <template #gzh="{ record }">
        <a href="javascript:;" @click="goPlan(record)">{{
          record.official_name
        }}</a>
      </template>
      <template #opertate="{ record }">
        <p @click="goPlan(record)"><a>查看广告计划</a></p>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  reactive,
  toRefs,
  ref,
  onMounted,
} from "vue";
import { picker } from "@/helper/config/range";
import ToolBar from "@/components/tool-bar/index.vue";
import moment from "moment";
import router from "@/router";
import {
  TableColumnOfPutData,
  TableColumnOfMoreStat,
} from "../_pageOptions/table-put";
import { MutationType } from "@/store/modules/app/_type";
import {
  getDeliveryStatList,
  getDeliveryMoreStatList,
  getDesignList,
} from "@/api";
import usePagination from "@/hooks/usePagination";

import { deliveryPlanItem, PageOptions, moreStatPlanItem } from "#/api";
import useApp from "@/hooks/useApp";
import useAuthUser from "@/hooks/composable/useAuthUser";

const PutData = defineComponent({
  components: {
    ToolBar,
  },
  setup() {
    const { router, route, store } = useApp();
    const { showDropDownBox, available_uids } = useAuthUser();
    let { loading, meta, tablePageOptions } = usePagination();
    let listed: any = [];
    const state = reactive({
      list: ref<any>([]),
      fields: {},
      drawerlist: ref<moreStatPlanItem[]>([]),
      pickered: computed(() =>
        store.getters.selectTime.length > 0
          ? [
              moment(store.getters.selectTime[0]),
              moment(store.getters.selectTime[1]),
            ]
          : [moment().subtract(30, "d"), moment()]
      ),
      columns: listed,
      tablePageOptions,
      pickerFilter: [],
      drawercolumns: TableColumnOfMoreStat,
      inSearching: false,
      rangePick: picker,
      defaultToolvalue: {},
      drawerinSearching: false,
      drawermeta: {},
      filterNumber: 7,
      show: false,
      uids: ref<number[]>([]),
    });
    if (route.query && route.query.official_name) {
      state.defaultToolvalue = {
        official_name: route.query.official_name,
      };
      state.fields = {
        official_name: route.query.official_name,
      };
    }
    const getList = (query: any) => {
      let [begin_dates, end_dates] = state.pickered;
      let start_time = moment(begin_dates).format("YYYY-MM-DD");
      let end_time = moment(end_dates).format("YYYY-MM-DD");
      let data = Object.assign(
        { start_time, end_time, uids: state.uids.toString() },
        state.fields,
        query
      );
      getDeliveryStatList(data).then((res) => {
        state.list = res.data.list;
        meta.value = res.data.meta;
      });
    };

    const onSearch = async (fields: Record<string, string>) => {
      try {
        const { official_name, book_name } = fields;
        state.fields = fields;
        getList({ page: 1, day_num: state.filterNumber });
      } catch (e) {
        console.log(e);
      } finally {
        console.log(state.inSearching);
        state.inSearching = false;
      }
    };

    const changeNumber = () => {
      getCloums();
      getList({ page: 1, day_num: state.filterNumber });
    };
    const getCloums = () => {
      getDesignList({ day_num: state.filterNumber }).then((res) => {
        let columns: any[] = [];
        let whiteList = ["official_name", "date", "book_name", "cost"];
        res.data.map((item: { desc: string; name: string }) => {
          let lolumnItem: {
            title: string;
            dataIndex: string;
            slots?: any;
            width?: string | number;
            fixed?: string;
            ellipsis?: boolean;
          } = {
            title: item.desc,
            dataIndex: item.name,
            ellipsis: true,
            width: 120,
          };
          if (whiteList.includes(item.name)) {
            lolumnItem.fixed = "left";
          }

          columns.push(lolumnItem);
        });
        let column = {
          title: "操作",
          dataIndex: "operte",
          ellipsis: true,
          width: 120,
          fixed: "right",
          slots: { customRender: "opertate" },
        };
        columns.push(column);
        columns.forEach((item) => {
          if (item.title === "公众号") {
            item.slots = { customRender: "gzh" };
          }
        });
        state.columns = columns;
      });
    };
    const handleTableChange = (pagination: PageOptions) => {
      const { current, pageSize, total } = pagination;
      let data = Object.assign(state.fields, {
        page: current,
        day_num: state.filterNumber,
      });
      getList(data);
    };
    const changeTime = (monent: any, string: string[]) => {
      if (Array.isArray(string) && string.join("")) {
        store.commit(MutationType.setSelectTime, string);
      }
    };

    onMounted(() => {
      getCloums();
      getList({
        page: 1,
        day_num: state.filterNumber,
        official_name: route.query?.official_name ?? "",
      });
    });
    return {
      ...toRefs(state),
      showDropDownBox,
      available_uids,
      onSearch,
      meta,
      handleTableChange,
      changeNumber,
      changeTime,
    };
  },
  methods: {
    moment,
    goPlan(record: any) {
      const { date, channel_id, book_id } = record;
      router.push({
        path: "/put/datas/ad-plan",
        query: { channel_id, begin_date: date, end_date: date, book_id },
      });
    },
  },
});

export default PutData;
</script>
<style lang="scss">
.table-filter {
  display: flex;
  justify-content: flex-end;
  padding: 5px 0 15px;
  align-items: center;
}
.ant-drawer-content-wrapper {
  width: 80vw !important;
}
.item-right {
  margin-right: 10px;
  display: flex;
  align-items: center;
  .ant-select {
    width: 100px;
  }
  .label {
    display: inline-block;
    min-width: 80px;
  }
}
.hover-content {
  margin: 8px 0 5px;
  display: flex;
  align-items: center;
  .label {
    padding-right: 15px;
    display: inline-block;
    max-width: 72px;
    width: 72px;
  }
  .ant-switch {
    width: 50px;
  }
}
.footer-slot {
  margin-top: 10px;
  button {
    margin-right: 10px;
  }
}
</style>
