<script setup>
import { ref, onMounted, watch, computed } from "vue";

import { raiInterface, resourceVoiceupload, raiVideoApi } from "@/api/api.js";
import ModifyImgDlg from "../../components/addComopnents/modifyImgDlg.vue";
import { ElMessage } from "element-plus";

const $emit = defineEmits();
const props = defineProps({
  addEditdialogReleaseAudio: {
    type: Boolean,
    default: false,
  },
  chartPermissionList: {
    type: Array,
    default: [],
  },
  playDetailsList: {
    default: {},
    type: Object,
  },
});

const addEditAudio = ref({
  audioName: "", //音频名称
  industryId: "", //行业id
  property: "", //产业名称
  audioUrl: "", //视频链接
  AudioSeconds: "", //时长
});
const rules = ref({
  industryId: [{ required: true, message: "请选择行业", trigger: "change" }],
});
const industryArr = ref([]);
const selectedIndustryArr = ref([]);
const percentage = ref(0);
const startUpload = ref(false); //开始上传
const fileListAudio = ref([]);
const videoAndVoiceList = ref([]);
const defaultImage = ref([]);
const modifyImgVisible = ref(false);
const defaultImage = ref("");
const shareImg = ref("");
const dlgTitle = ref("发布问答");

watch(
  () => props.playDetailsList.AskserieVideoId,
  () => {
    if (newval) {
      newVal && newVal > 0 && askserieVideoDetail();
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

function updateSonDate(item) {
  defaultImage.value = item.ImgUrl;
  shareImg.value = item.ShareImg;
}
/* 获取全部的行业 前的判断 */
function industrySelectFocus() {
  if (!addEditAudio.value.industryId) {
    ElMessage.error("请先选择行业");
  }
}
// 行业更改
function selectChangeHandle(value) {
  addEditAudio.value.property = "";
  value ? getIndustry(value) : (selectedIndustryArr.value = []);
  value && getVideoAndImg();
}
/* 获取选择的行业 */
function getIndustry(industryId) {
  if (industryArr.value.length) {
    selectedIndustryArr.value = industryArr.value.filter((item) => item.ChartPermissionId == industryId)[0].List;
    return;
  }
  raiInterface.getListIndustrial().then((res) => {
    if (res.Ret === 200) {
      industryArr.value = res.Data.List || [];
      selectedIndustryArr.value = industryArr.value.filter((item) => item.ChartPermissionId == industryId)[0].List;
    }
  });
}

const ruleFormAudio = ref(null);
//保存或发布
function confirmSubmit(type) {
  ruleFormAudio.value.validate(async (valid) => {
    if (valid) {
      if (!fileListAudio[0].value.url) return ElMessage.error("请上传音频");
      if (!addEditAudio.value.audioName) return ElMessage.error("请输入音频名称");
      let ChartPermissionName = "";
      props.chartPermissionList.forEach((item) => {
        if (item.ChartPermissionId == addEditAudio.value.industryId) {
          ChartPermissionName = item.PermissionName;
        }
      });
      const res = await raiVideoApi.askseriePreserveAndEdit({
        AskserieVideoId: props.playDetailsList.AskserieVideoId ? props.playDetailsList.AskserieVideoId : 0,
        VideoName: addEditAudio.value.audioName,
        ChartPermissionId: addEditAudio.value.industryId,
        ChartPermissionName,
        IndustrialManagementIds: addEditAudio.value.property ? addEditAudio.value.property.join(",") : "",
        VideoUrl: addEditAudio.value.audioUrl,
        VideoDuration: addEditAudio.value.AudioSeconds + "",
        BackgroundImg: defaultImage.value,
        ShareImg: shareImg.value,
      });
      if (res.Ret === 200) {
        ElMessage.success("添加成功");
        cancelHandle();
        $emit("getVideoList");
      }
    } else {
      console.log("error submit!!");
      return false;
    }
  });
}
// 上传音频
async function handleUploadAudio(e) {
  startUpload.value = true;
  let form = new FormData();
  form.append("file", e.file);
  const res = await resourceVoiceupload(form);
  if (res.Ret === 200) {
    let obj = {
      name: res.Data.ResourceName,
      url: res.Data.ResourceUrl,
      PlaySeconds: res.Data.PlaySeconds,
    };
    addEditAudio.value.audioName = res.Data.ResourceName; //音频名称
    addEditAudio.value.audioUrl = res.Data.ResourceUrl; //视频链接
    addEditAudio.value.AudioSeconds = res.Data.PlaySeconds; //时长
    fileListAudio.value = [obj];
  }
  startUpload.value = false;
}
// 封面图
async function getVideoAndImg(isOne = "") {
  const res = await raiInterface.video_and_voiceImgActivityVideo({
    ChartPermissionId: addEditAudio.value.industryId,
  });
  if (res.Ret === 200) {
    isOne == "修改" ? "" : ((defaultImage.value = res.Data.List[0].ImgUrl), (shareImg.value = res.Data.List[0].ShareImg));
    videoAndVoiceList.value = res.Data.List;
  }
}
// 点击修改图片的弹框
function modifyImgHandler() {
  getVideoAndImg("修改");
  modifyImgVisible.value = true;
}
function cancelHandle() {
  ruleFormAudio.value.resetFields();
  addEditAudio.value = {
    audioName: "", //音频名称
    industryId: "", //行业id
    property: "", //产业名称
    audioUrl: "", //视频链接
    AudioSeconds: "", //时长
  };
  fileListAudio.value = [];
  defaultImage.value = "";
  shareImg.value = "";
  dlgTitle.value = "发布问答";
  $emit("update:addEditdialogReleaseAudio", false);
  $emit("update:playDetailsList", {});
}
// 获取详情
async function askserieVideoDetail() {
  const res = await raiVideoApi.askserieVideoDetail({
    AskserieVideoId: props.playDetailsList.AskserieVideoId,
  });
  if (res.Ret === 200) {
    dlgTitle.value = "编辑";
    let { Detail } = res.Data;
    getIndustry(Detail.ChartPermissionId);
    let str = [];
    Detail.ListIndustrial &&
      Detail.ListIndustrial.forEach((item) => {
        str.push(item.IndustrialManagementId);
      });
    addEditAudio.value = {
      audioName: Detail.VideoName, //音频名称
      industryId: Detail.ChartPermissionId, //行业id
      property: str, //产业名称
      audioUrl: Detail.VideoUrl, //视频链接
      AudioSeconds: Detail.VideoDuration, //时长
    };
    defaultImage.value = Detail.BackgroundImg;
    shareImg.value = Detail.ShareImg;
    let obj = {
      name: Detail.VideoName,
      url: Detail.VideoUrl,
      PlaySeconds: Detail.VideoDuration,
    };
    fileListAudio.value = [obj];
  }
}
</script>

<template>
  <div class="container add-edit-release-audio">
    <el-dialog
      draggable
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      center
      width="568px"
      :title="dlgTitle"
      v-model="props.addEditdialogReleaseAudio"
      customClass="add-edit-video-dlg"
      :before-close="cancelHandle"
    >
      <div>
        <el-form :model="addEditAudio" :rules="rules" ref="ruleFormAudio" class="demo-ruleForm">
          <el-form-item prop="audioName">
            <div style="display: flex; justify-content: space-between">
              <el-input style="width: 75%" clearable placeholder="请上传音频" v-model="addEditAudio.audioName"></el-input>
              <el-upload class="upload-demo" action="" :show-file-list="false" :http-request="handleUploadAudio" accept="audio/*" :file-list="fileListAudio">
                <el-button type="primary" :loading="startUpload">上传音频</el-button>
              </el-upload>
              <el-progress type="circle" :percentage="percentage" width="40" style="margin-left: 10px" v-if="startUpload"></el-progress>
            </div>
          </el-form-item>
          <el-form-item prop="industryId">
            <el-select style="width: 100%" placeholder="请选择行业" v-model="addEditAudio.industryId" clearable @change="selectChangeHandle">
              <el-option
                v-for="item in props.chartPermissionList.filter((item) => item.PermissionName != '宏观' && item.PermissionName != '策略' && item.PermissionName != '研选订阅')"
                :label="item.PermissionName"
                :key="item.ChartPermissionId"
                :value="item.ChartPermissionId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="addEditAudio.property" multiple placeholder="请选择产业（可多选）" clearable filterable style="width: 100%" @focus="industrySelectFocus">
              <el-option :label="item.PermissionName" :value="item.ChartPermissionId" v-for="item in selectedIndustryArr" :key="item.ChartPermissionId"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="cover-content" style="margin: 10px 0" v-if="addEditAudio.industryId && defaultImage">
        <span class="text" style="width: 46px; text-align: right">封面：</span>
        <div class="img-content">
          <img :src="defaultImage" alt="" />
          <div class="modify" @click="modifyImgHandler">修改</div>
        </div>
      </div>
      <template #footer></template>
      <span class="dialog-footer">
        <el-button type="primary" @click="confirmSubmit(1)">确定</el-button>
        <el-button @click="cancelHandle">取消</el-button>
      </span>
    </el-dialog>
    <modify-img-dlg v-model:modifyImgVisible="modifyImgVisible" v-model:videoAndVoiceList="videoAndVoiceList" @updateSonDate="updateSonDate" />
  </div>
</template>

<style lang="scss">
.add-edit-release-audio {
  .add-edit-video-dlg {
    .el-input {
      width: 100%;
    }
  }
}
</style>
<style lang="scss" scoped>
.add-edit-release-audio {
  display: flex;
  justify-content: space-between;
  .cover-content {
    display: flex;
    // align-items: stretch;
    // vertical-align: bottom;
    .img-content {
      position: relative;
      height: 200px;
      width: 200px;
      border: 1px solid #ccc;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .modify {
      position: absolute;
      bottom: 0;
      right: -50px;
      height: 20px;
      cursor: pointer;
      color: #409eff;
    }
  }
}
</style>
