<template>
  <div>
    <Search :search="search" :reset="resetQuery">
      <template v-slot:body>
        <el-form-item label="短剧" prop="name">
          <el-input v-model="query.videoName" placeholder="请输入短剧名称" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="updateType">
          <el-select v-model="query.updateType" filterable clearable placeholder="请选择状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="频道" prop="categoryId">
          <el-cascader v-model="selectType" :options="cooperations" filterable clearable :change-on-select="true"
            @change="handleCascaderChange" />
        </el-form-item>
        <el-form-item label="微信审核状态" prop="wechatPass">
          <el-select v-model="query.wechatPass" filterable clearable placeholder="请选择微信审核状态">
            <el-option v-for="item in wxstatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </template>
    </Search>
    <div class="table-default">
      <!-- <div class="set-warpper">
        <el-button type="primary" @click="mulSet" size="default" v-action="'video.video.mulSet'">批量操作</el-button>
      </div> -->
      <Operate :show="open" v-action="'video.video.add'" />
      <el-table :data="tableData" class="mt-3" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" />
        <el-table-column prop="id" label="剧号" />
        <el-table-column label="封面" show-overflow-tooltip>
          <template #default="scope">
            <div class="flex flex-col items-start justify-center wrapper">
              <el-popover placement="top" :width="200" trigger="click">
                <template #reference>
                  <el-image :src="scope.row.cover_image" class="cursor-pointer" style="width:48px;height:48px;"
                    fit="contain" :lazy="true"></el-image>
                </template>
                <el-image :src="scope.row.cover_image" style="width:100%;" fit="contain"></el-image>
              </el-popover>
              <el-button type="primary" link size="default" @click="dowload(scope.row)">下载</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="短剧名称" min-width="250">
          <template #default="scope">
            <el-tooltip placement="top" v-if="scope.row.wechat_pass">
              <template #content> 当前短剧已通过微信审核<br /> </template>
              <div>
                <div class="wrapper">
                  <span class="text-lg font-bold text-blue-400 cursor-pointer content"
                    @click="openType('videoDetailVisible', scope.row)">
                    {{ scope.row.name }}
                  </span>
                  <span>
                    【 {{ scope.row.update_type_str }} 】
                  </span>
                </div>
                <div class="wrapper">
                  <span class="label">上架时间:</span>
                  <span class="content">{{ scope.row.shelf_at }}</span>
                </div>
                <div class="ml-2">
                  <el-image style="width: 20px; height: 20px" class="mt-1" :src="scope.row.wechat_pass_img"
                    fit="contain" />
                </div>
              </div>
            </el-tooltip>
            <div v-else>
              <div class="wrapper">
                <span class="text-lg font-bold text-blue-400 cursor-pointer content"
                  @click="openType('videoDetailVisible', scope.row)">
                  {{ scope.row.name }}
                </span>
                <span>
                  【 {{ scope.row.update_type_str }} 】
                </span>
              </div>
              <div class="wrapper">
                <span class="label">上架时间:</span>
                <span class="content">{{ scope.row.shelf_at }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="total_episode_num" label="集数">
          <template #default="scope">
            <div class="flex wrapper">
              <div v-if="scope.row.update_type == 1">
                <span class="content">
                  {{ scope.row.updated_episode_num }}
                </span>
                <span>/</span>
              </div>
              <div>
                <span class="content">
                  {{ scope.row.total_episode_num }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category_str" label="频道" />
        <el-table-column prop="shelf_type_str" label="上架状态" v-if="!rolesIdentify.includes('company')" />
        <el-table-column prop="charge_sequence" label="起始集" v-if="!rolesIdentify.includes('company')" />
        <el-table-column prop="charge_coin" label="定价" v-if="!rolesIdentify.includes('company')">
          <template #header>
            <div class="flex items-center">
              <span>定价</span>
              <el-tooltip placement="top">
                <template #content> 定价为所需看剧币<br />1元等于100币 </template>
                <el-icon>
                  <InfoFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <template #default="scope">
            <span>{{ scope.row.charge_coin }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="openType('uploadVisible', scope.row)"
              v-action="'video.episode.add'">上传视频</el-button><br />
            <el-button @click="open(scope.row)" link type="primary" size="small"
              v-action="'video.video.update'">编辑</el-button><br />
            <el-button @click="openType('takeVisible', scope.row)" link type="primary" size="small"
              v-action="'video.video.setChargeConfig'">订阅设置</el-button><br />
            <el-button link type="primary" size="small" @click="openType('videoDLVisible', scope.row)"
              v-action="'video.episode.downloadList'">视频下载</el-button>
            <br />
            <el-button link type="primary" size="small" v-if="isShowCreatePromotion" v-action="'tuiguang.Promotion.add'"
              @click="openType('videoDetailVisible', scope.row)">生成推广链接</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Paginate />
    </div>

    <Dialog v-model="visible" :title="title" destroy-on-close>
      <Create @close="close(search)" :primary="id" :eidapi="addApi" :addapi="addApi" :ismulSet="ismulSet" />
    </Dialog>
    <Dialog v-model="videoDLVisible" width="80%" title="视频下载" destroy-on-close>
      <videoDL @close="closeType('videoDLVisible')" :primary="depotsData"></videoDL>
    </Dialog>
    <Dialog v-model="takeVisible" width="50%" title="订阅设置" destroy-on-close>
      <subscribeSet @close="closeType('takeVisible')" :primary="takeData"></subscribeSet>
    </Dialog>
    <Dialog v-model="uploadVisible" width="50%" title="上传视频" destroy-on-close>
      <uploadVideo @close="closeType('uploadVisible')" :primary="uploadData"></uploadVideo>
    </Dialog>
    <el-dialog draggable v-action="'video.video.list'" align-center append-to-body v-model="videoDetailVisible" width="50%" title="短剧详情"
      destroy-on-close>
      <videoDetail @close="closeType('videoDetailVisible')" :primary="videoDetailData"></videoDetail>
    </el-dialog>
    <!-- <Dialog v-action="'video.video.list'" v-model="videoDetailVisible" width="50%" title="短剧详情" destroy-on-close>
      <videoDetail @close="closeType('videoDetailVisible')" :primary="videoDetailData"></videoDetail>
    </Dialog> -->
  </div>
</template>

<script lang="ts" setup>
import { downloadImage } from '@/utils/index'
import { InfoFilled } from '@element-plus/icons-vue';
import { provide } from 'vue'
import Create from './form/create.vue';
import videoDL from './form/videoDL.vue';
import videoDetail from './detail.vue';
import subscribeSet from './form/subscribeSet.vue';
import uploadVideo from './form/uploadVideo.vue';
import { useGetList } from '@/hook/curd/useGetList';
import { useDestroy } from '@/hook/curd/useDestroy';
import { useOpen } from '@/hook/curd/useOpen';
import { shortcuts } from '@/utils/shortcuts';
import moment from 'moment';
import { videoStockVideoUpdate, videoStockVideoAdd, videoStockVideoCategoryList } from '@/api/video/index'
import { useUserStore } from '@/stores/modules/user/index'
import Cache from '@/support/cache';
import { fa } from 'element-plus/es/locale';
const ismulSet = ref(false)
const api = 'videoStock/video/list';
const addApi = 'contentManage/book/edit_author';
const multipleSelection = ref([]);
const { data, query, search, reset, loading } = useGetList(api);
const { deleted } = useDestroy();
const uploadBooksVisible = ref(false)
const videoDLVisible = ref(false)
const depotsData = ref({})
const uploadVisible = ref(false)
const uploadData = ref({})
const takeVisible = ref(false)
const takeData = ref({})
const videoDetailVisible = ref(false)
const videoDetailData = ref({})
const current = ref({})
const selectType = ref([])
const statusOptions = ref([{ label: '连载中', value: '1' }, { label: '完结', value: '2' }]);
const wxstatusOptions = ref([{ label: '未通过', value: 0 }, { label: '已通过', value: 1 }]);
const cooperations = ref([]);
const rolesIdentify = ref([]);
const isShowCreatePromotion = computed(() => JSON.parse(Cache.get('nav_data'))?.advertiser?.miniProgramIds && JSON.parse(Cache.get('nav_data'))?.app)


const userStore = useUserStore()

const handleCascaderChange = (val: any) => {
  console.log(val, 'valval');
  if (val) {
    // 获取最后一级选项的值
    const lastOptionValue = val[val.length - 1];
    console.log('最后一级选项的值：', lastOptionValue, selectType.value);
    // 更新 selectedOptions 的值
    query.value.categoryId = lastOptionValue;
  } else {
    delete query.value.categoryId
  }
}

const resetQuery = () => {
  reset()
  selectType.value = []
}
const openType = (type: string, data: object) => {
  current.value = data;
  switch (type) {
    case 'videoDLVisible':
      videoDLVisible.value = true
      depotsData.value = data
      break;
    case 'takeVisible':
      takeVisible.value = true
      takeData.value = data
      break;
    case 'uploadVisible':
      uploadVisible.value = true
      uploadData.value = data
      break;
    case 'videoDetailVisible':
      videoDetailVisible.value = true
      videoDetailData.value = data
      break;
  }
}
provide('video', current)
const initType = () => {
  videoStockVideoCategoryList().then(res => {
    console.log(res);
    cooperations.value = res.data
  })
}
// 下载封面
const dowload = (e: object) => {
  downloadImage(e.cover_image, e.name)
}

const tableData = computed(() => data.value?.data);
const { open, close, title, visible, id } = useOpen();

const handleSelectionChange = (val: []) => {
  console.log(toRaw(val));
  multipleSelection.value = val;
};

const closeType = (type) => {
  console.log(type, 'typetype');
  switch (type) {
    case 'videoDLVisible':
      videoDLVisible.value = false
      break;
    case 'takeVisible':
      takeVisible.value = false
      break;
    case 'uploadVisible':
      uploadVisible.value = false
      break;
    case 'videoDetailVisible':
      videoDetailVisible.value = false
      break;
  }
  search()
}

const mulSet = () => {
  if (multipleSelection.value.length <= 0) {
    return ElMessage.warning({
      message: '至少选择一条数据',
      type: 'warning'
    });
  } else {
    ElMessageBox({
      title: '提示',
      message: h('p', null, [
        h('span', null, `确认批量设置`),
        h(
          'span',
          { style: 'color:red' },
          multipleSelection.value.map(el => el.name).join(',')
        ),
        h('span', null, `吗？`)
      ]),
      showCancelButton: true,
      confirmButtonText: '确定',
      type: 'warning',
      cancelButtonText: '取消',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          ismulSet.value = true
          let ids = multipleSelection.value.map(el => el.id);
          console.log(ids);
          open(ids);
        }
        done();
      }
    });
  }
};
onMounted(() => {
  rolesIdentify.value = userStore.getRoles?.map(el => el?.identify)
  console.log(rolesIdentify.value, 'rolesroles');
  if (userStore.getRoles?.some(el => (el?.identify == 'company'))) {
    query.value.operateUserId = JSON.parse(Cache.get('nav_data'))?.advertiser?.id;
  }
  initType()
  search();
});
</script>

<style scoped lang="scss">
.table-default {
  .set-warpper {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .wrapper {
    margin: 8px;

    .label {
      margin-right: 6px;
    }

    .content {
      font-size: 15px;
    }
  }
}
</style>
