<template>
  <div class="common-table">
    <a-popconfirm :disabled="selectedRowKeys.length === 0" @confirm="onDelete">
      <template #title> <p>确认批量删除所选素材吗</p> </template
      ><a-button
        :disabled="selectedRowKeys.length === 0"
        style="margin-bottom: 10px"
        >批量删除</a-button
      >
    </a-popconfirm>
    <a-button
      :disabled="selectedRowKeys.length === 0"
      style="margin: 0 0 10px 10px"
      @click="onOpenPush"
      >批量推送</a-button
    >
    <a-table
      bordered
      :data-source="list"
      :columns="columns"
      @change="getList"
      rowKey="id"
      :loading="loading"
      :pagination="tablePageOptions"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
      <template #video_name="{ record }">
        <div class="table-view-box">
          <div class="video-view" @click="onOpenPreview(record.url)">
            <i class="iconfont icon-ziyuan"></i>
            <img
              :src="
                record.url + '?x-oss-process=video/snapshot,t_0,f_jpg,m_fast'
              "
              alt=""
            />
          </div>
          <span>{{ record.name }}</span>
        </div>
      </template>
      <template #image_name="{ record }">
        <div class="table-view-box">
          <div class="image-view" @click="onOpenPreview(record.url)">
            <img :src="record.url" alt="" />
          </div>
          <span>{{ record.name }}</span>
        </div>
      </template>
      <template #duration="{ record }">{{ record.duration }}秒</template>
      <template #video_type="{ record }">
        <span v-show="record.video_type === 'S'">竖版视频</span>
        <span v-show="record.video_type === 'H'">横版视频</span>
      </template>
      <template #image_type="{ record }">
        <span v-show="record.image_type === 'S'">竖版大图</span>
        <span v-show="record.image_type === 'H'">横版大图</span>
        <span v-show="record.image_type === 'X'">小图</span>
      </template>
      <template #operation="{ record }">
        <a-button style="padding: 0" @click="onOpenPush(record)" type="link"
          >推送</a-button
        >
        <a-popconfirm
          @confirm="onDelete(record)"
          :disabled="Number(record.is_mine_uploaded) !== 1"
        >
          <template #title>
            <p>确认删除该素材吗</p>
          </template>
          <a-button
            :disabled="Number(record.is_mine_uploaded) !== 1"
            type="link"
            >删除</a-button
          >
        </a-popconfirm>
      </template>
    </a-table>
    <a-modal
      v-model:visible="pushVisible"
      :title="type === 'video' ? '推送视频' : '推送图片'"
      :confirmLoading="pushLoading"
      @ok="onConfirmPush"
      width="40%"
    >
      <span>选择广告主：</span>
      <a-cascader
        style="width: 360px"
        v-model:value="advertiser"
        :options="adList"
        placeholder="请选择"
        :field-names="{
          label: 'advertiser_name',
          value: 'advertiser_id',
          children: 'advertises',
        }"
      />
    </a-modal>
    <!-- <a-modal
      v-model:visible="previewVisible"
      width="40%"
      height="200px"
      :footer="null"
      :mask="true"
      wrapClassName="preview"
      style="max-height: 400px"
    >
      <img
        style="max-width: 100%; max-height: 100%"
        :src="currentUrl"
        alt=""
        v-show="type === 'picture'"
      />
      <video
        v-show="type === 'video'"
        style="max-width: 100%; max-height: 100%"
        :src="currentUrl"
        controls
      ></video>
    </a-modal> -->
    <preview-box
      @close="previewVisible = false"
      :type="type"
      :url="currentUrl"
      v-if="previewVisible"
    ></preview-box>
  </div>
</template>

<script lang="ts">
import usePagination from "@/hooks/usePagination";
import PreviewBox from "./preview.vue";
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  watchEffect,
  watch,
} from "vue";
import {
  TableColumnOfVideo,
  TableColumnOfImage,
} from "../../_pageOptions/table_material";
//getPromotionList
import {
  getVideoList,
  getImageList,
  deleteVideo,
  deleteImage,
  getAdvertiser,
  pushMaterial,
} from "@/api";
import { message } from "ant-design-vue";
const CommonTable = defineComponent({
  components: { PreviewBox },
  props: ["materialType", "searchForm"],
  setup(props) {
    let { meta, tablePageOptions } = usePagination();
    const state = reactive({
      type: "",
      loading: false,
      list: ref<any[]>([]),
      columns: ref<any[]>([]),
      adList: ref<any[]>([]),
      selectedRowKeys: ref<any[]>([]),
      pushVisible: false,
      currentId: 0, // 当前操作的素材id
      advertiser: ref<string[]>([]), // 选择的广告主
      previewVisible: false,
      currentUrl: "",
      pushLoading: false,
    });
    const getList = async (page?: any) => {
      state.loading = true;
      // return message.success("请求接口");
      let api = state.type === "video" ? getVideoList : getImageList;
      let { data } = await api({
        page: page ? page.current : 1,
        ...props.searchForm,
      });
      state.loading = false;
      state.list = data.list;
      meta.value = data.meta;
    };
    // 列表选项改变
    const onSelectChange = (selectedRowKeys: any) => {
      state.selectedRowKeys = selectedRowKeys;
    };
    watch(
      () => props.searchForm,
      (oldVal, newVal) => {
        getList({ current: 1 });
        state.selectedRowKeys = [];
      }
    );
    return { ...toRefs(state), tablePageOptions, getList, onSelectChange };
  },
  mounted() {
    this.type = this.$props.materialType;
    if (this.type === "video") this.columns = TableColumnOfVideo;
    if (this.type === "picture") this.columns = TableColumnOfImage;
    this.getAdList();
  },
  methods: {
    // 获取广告主列表
    async getAdList() {
      let { data } = await getAdvertiser();
      this.adList = data;
      if (this.adList.length === 0) return;
      this.adList.forEach((item) => {
        item.advertiser_id = item.account_id;
        item.advertiser_name = item.account_name;
      });
      this.selectedRowKeys = [];
      console.log("LIST", this.selectedRowKeys);
    },

    async onDelete(val?: any) {
      let arr = [];
      if (val.id) {
        // 单个删除
        arr.push(val.id);
      } else {
        // 多选删除
        arr = this.selectedRowKeys;
      }
      let ids = arr.join(",");
      console.log("删除", val);
      let api = this.type === "video" ? deleteVideo : deleteImage;
      try {
        await api({ ids });
        message.success("删除成功");
      } catch (err) {
        message.error("删除失败");
        console.log("ERR:", err);
      } finally {
        this.getList({ current: 1 });
        this.selectedRowKeys = [];
      }
    },
    // 点击推送
    onOpenPush(item?: any) {
      this.currentId = item.id ?? 0;
      this.advertiser = [];
      this.pushVisible = true;
      this.pushLoading = false;
    },
    // 确定推送
    async onConfirmPush() {
      // if(this.currentId == 0){ return console.log('多个推送')}else {return console.log('单个推送')}
      this.pushLoading = true;
      console.log("IDS", this.currentId, this.advertiser);
      try {
        await pushMaterial({
          material_id:
            this.currentId == 0
              ? this.selectedRowKeys.join(",")
              : this.currentId,
          advertiser_id: this.advertiser[1],
        });
        this.pushVisible = false;
        message.success("推送成功");
      } catch (err) {
        this.pushVisible = false;
        message.error("推送失败");
        console.log(err);
      } finally {
        this.pushLoading = false;
      }
    },
    // 点击预览
    onOpenPreview(url: string) {
      this.currentUrl = url;
      this.previewVisible = true;
    },
  },
  //https://firemanage.oss-cn-hangzhou.aliyuncs.com/material/video/S-20210739163739-E9XA.mp4?x-oss-process=video/snapshot,t_0,f_jpg,m_fast
});

export default CommonTable;
</script>
<style lang="scss" scoped>
@import "@/assets/common-style/frame.scss";
.common-table {
  background: white;
  padding: 10px;
  .table-view-box {
    display: flex;
    align-items: center;
    cursor: pointer;
    .video-view {
      width: 80px;
      height: 60px;
      border: 1px solid gray;
      margin-right: 4px;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgb(94, 93, 93);
      img {
        max-width: 58px;
        max-height: 58px;
      }
      .icon-ziyuan {
        position: absolute;
        top: 18px;
        left: 32px;
        color: white;
      }
    }
    .image-view {
      width: 60px;
      height: 60px;
      border: 1px solid gray;
      margin-right: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
      img {
        max-width: 58px;
        max-height: 58px;
      }
    }
    // &:hover span {
    //   color: rgb(0, 140, 255);
    // }
  }
}
</style>
