<script setup>
import { Search } from '@element-plus/icons-vue'
import { downLoadFile } from '~/utils/download'
import { user } from '~/store/index'
import { getFileType } from "~/utils/helper"
import { userDetailStore } from "~/store/detail";
const detailStore = userDetailStore();
const loading=ref(false)
const spjjListRef = ref()
const router = useRouter()
const catalog = ref('')
const params = ref({
  as_shzt: '1',
  limit: '9',
  keyword: '',
})

const status = ref()
const statusData = ref([
  {
    name: '剪辑作品',
    status: '1',
  },
  {
    name: '草稿箱',
    status: '2',
  },
  {
    name: '素材',
    status: '3',
  },
])

const fields = ref()
const checkAll = ref(false)
const checkedData = ref([])

let tab = sessionStorage.getItem('tab');
if (tab) {
  changeStatus(tab)
} else {
  changeStatus('1')
}

function changeStatus(data) {
  status.value = data
  sessionStorage.setItem("tab", status.value)
  
  checkAll.value = false
  checkedData.value = []
  if (data !== '3') {
    params.value.as_shzt = data
    params.value.az_type = undefined
    params.value.create_user_id = user.value.user_id
    catalog.value = 'spjj'
    fields.value = {
      id: 'as_id',
      name: 'as_title',
      img: 'as_img',
      time: 'create_dateline',
      file: 'as_file'
    }
    if(data === '1') {
      fields.value.status = 'as_status';
      fields.value.uploadValue = 'Processing';
      fields.value.audit = 'sh_status';
    }
  }
  else {
    params.value.as_shzt = undefined
    params.value.az_type = ''
    params.value.create_user_id = user.value.user_id;
    catalog.value = 'zyk'
    fields.value = {
      id: 'az_id',
      name: 'az_name',
      img: 'az_img',
      time: 'create_dateline',
      file: 'az_file',
    }
  }
}

function initCheckData(data) {
  checkedData.value = [...data]
}

async function handleCreate() {
  if (checkedData.value.length === 0) {
    ElMessage.error('请先选择数据！')
    return
  }
  const arr = checkedData.value.map((item) => {
    return item[fields.value.id]
  })
  const { code, msg } = await request({ url: `/aimooc/${catalog.value}/submit_check`, data: { as_ids: arr.join(',') } })
  if (code === '1') {
    ElMessageBox.alert('<div class="py-30px">创建成功，跳转到审核页面中</div>', null, {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定',
      center: true,
      showClose: false,
      customStyle: { "border-radius": "24px", "padding": "20px 30px 30px" },
      confirmButtonClass: 'w-full h-48px',
      callback: (action) => {
        ElMessage.success(msg)
        router.push('zysh')
      },
    })
    spjjListRef.value.initData()
  }
}

const dialogVisible = ref(false)
const dialogType = ref(0)
const dialogTitle = ref('')
const currentId = ref('')
const jjFormRef = ref()
const scFormRef = ref()
const jjForm = ref({
  as_title: '',
  as_img: '',
  azz_ssnj_v2:"",
  azz_id_v2:"",
  azz_name_v2:"",
  azb_id_v2:"",
  as_zy_sm_id_v2:"",
  camp_id_v3:"",
  camp_name_v3:""
})
const scForm = ref({
  az_name: '',
  az_img: '',
  az_file: '',
})

const grade_list=$ref([
  {
    grade_id:'1',
    grade_name:"一年级"
  },
  {
    grade_id:'2',
    grade_name:"二年级"
  },{
    grade_id:'3',
    grade_name:"三年级"
  },{
    grade_id:'4',
    grade_name:"四年级"
  },{
    grade_id:'5',
    grade_name:"五年级"
  },{
    grade_id:'6',
    grade_name:"六年级"
  }
])
const form_query = $ref({
  page: 1,
  limit: 999,

});
// 筛选change年级
let major_list=$ref([])
function handleChangeGrade(e) {
  jjForm.value.azz_id_v2 = "";
  major_list = [];
  if (!e) return;
  request({
    url: `/aimooc/zyfl_zy_v2/index`,
    data: { ...form_query, azz_ssnj_v2: e },
  }).then((res) => {
    const { code, data } = res;
    if (code === "1") {
      major_list = data.page_data;
   
    }
  });
}

let tag_list=$ref([])
async function getTagData() {
  const { code, data } = await request({
    url: "/aimooc/zyfl_bq_v2/index",
    data: {
      ...form_query,
    },
  });
  if (code === "1") {
    tag_list = [...data.page_data];
    }
}
getTagData()
let school_list=$ref([])
async function getSchoolData() {
  const { code, data } = await request({
    baseURL: window.GLOBAL_CONFIG.uc,
    url: "/index.php?mod=school&action=main&do=index",
    data: {
      ...form_query,
    },
  });
  if (code === "1") {
    school_list = [...data.page_data];
    }
}
 getSchoolData()


let campusData = $ref([]);
function handleSmChange(e) {
  if (!e) {
    campusData = [];
    return;
  }
   jjForm.value.camp_id_v3 = "";
  request({
    baseURL: window.GLOBAL_CONFIG.uc,
    url: "/school/main/get_camp",
    data: {
      sm_id: e,
    },
  }).then((res) => {
    if (res.code == "1") {
      campusData = res.data.camp;
    }
  });
}



 function zyChange(e){
   major_list.map(item=>{
  if(item.azz_id_v2==e){
    jjForm.value.azz_name_v2=item.azz_name_v2
  }
})
 }
  function campChange(e){
   campusData.map(item=>{
  if(item.camp_id==e){
    jjForm.value.camp_name_v3=item.camp_name
  }
})
 }
const rules = reactive({
  as_title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  as_zy_sm_id_v2: [{ required: true, message: '请选择学校', trigger: 'blur' }],
  camp_id_v3: [{ required: true, message: '请选择学院', trigger: 'blur' }],
   azz_ssnj_v2:[{ required: true, message: '请选择年级', trigger: 'submit' }],
  azz_id_v2:[{ required: true, message: '请选择专业', trigger: 'submit' }],
  az_file: [{ required: true, message: '请上传视频', trigger: 'submit' }],
})

function initDialog(show, title, type) {
  dialogVisible.value = show
  dialogTitle.value = title
  dialogType.value = type
   campusData=[]
  if (!show) {
    currentId.value = ''
   loading.value = false;
    for (const key in jjForm.value)
      jjForm.value[key] = ''

    for (const key in scForm.value)
      scForm.value[key] = ''
  }
}

function handleSubmit() {
  spjjListRef.value.initData()
  if (dialogType.value === 1) {
    jjFormRef.value?.validate(async (valid, fields1) => {
      if (valid) {
         loading.value = true;
        if (currentId.value === '') {
          const { code, data } = await request({ url: `/aimooc/${catalog.value}/add`, data: { aimooc_spjj: jjForm.value } })
          if (code === '1') {
            initDialog(false, '', 0)
            ElMessage.success('保存成功！')
            spjjListRef.value.initData()
             loading.value = false;
          }
        } else {
          const { code, data } = await request({ url: `/aimooc/${catalog.value}/edit`, data: { [fields.value.id]: currentId.value, aimooc_spjj: jjForm.value } })
          if (code === '1') {
            initDialog(false, '', 0)
            ElMessage.success('保存成功！')
            spjjListRef.value.initData()
             loading.value = false;
          }
        }
      }
      else {
        console.log('error submit!', fields1)
      }
    })
  }
  else if (dialogType.value === 2) {
    scFormRef.value?.validate(async (valid, fields1) => {
      if (valid) {
        const type = getFileType(scForm.value.az_file)
        if (type === 'video')
          scForm.value.az_type = '1'
        else if (type === 'audio')
          scForm.value.az_type = '2'
        else if (type === 'image')
          scForm.value.az_type = '3'

        let obj = {};
        for (let key in scForm.value) {
          obj[key] = scForm.value[key]
        }
        obj.az_img = scForm.value.az_img || scForm.value.az_file;

        if (currentId.value === '') {
          const { code, data } = await request({ url: `/aimooc/${catalog.value}/add`, data: { aimooc_zyk: obj } })
          if (code === '1') {
            initDialog(false, '', 0)
            ElMessage.success('保存成功！')
            spjjListRef.value.initData()
          }
        }
        else {
          const { code, data } = await request({ url: `/aimooc/${catalog.value}/edit`, data: { [fields.value.id]: currentId.value, aimooc_zyk: obj } })
          if (code === '1') {
            initDialog(false, '', 0)
            ElMessage.success('保存成功！')
            spjjListRef.value.initData()
          }
        }
      }
      else { console.log('error submit!', fields1) }
    })
  }
}

function handleMutiDelete() {
  const arr = checkedData.value.map((item) => {
    return item[fields.value.id]
  })
  ElMessageBox.confirm('确定要删除这些数据吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code } = await request({ url: `/aimooc/${catalog.value}/delete`, data: { [fields.value.id]: arr } })
      if (code === '1') {
        ElMessage.success('删除成功！')
        spjjListRef.value.initData()
      }
    })
    .catch(() => { })
}

function handleEdit(data) {
  if (status.value !== '3') {
  
   handleChangeGrade(data.azz_ssnj_v2)
    currentId.value = data[fields.value.id]
      if(currentId.value){
     request({
    baseURL: window.GLOBAL_CONFIG.uc,
    url: "/school/main/get_camp",
    data: {
      sm_id: data.as_zy_sm_id_v2,
    },
  }).then((res) => {
    if (res.code == "1") {
      campusData = res.data.camp;
    }
  });
  }
    for (const key in jjForm.value)
    jjForm.value[key] = data[key]
    initDialog(true, '编辑剪辑', 1)
    
  }
  else {
    currentId.value = data[fields.value.id]
    for (const key in scForm.value)
      scForm.value[key] = data[key]
    initDialog(true, '编辑素材', 2)
  }
}

async function handleDownload(item) {
  if (status.value !== '3') {
    const { code, data } = await request({ url: `/aimooc/${catalog.value}/detail`, data: { [fields.value.id]: item[fields.value.id] } })
    if (code === '1') {
      const file = data.one_info[fields.value.file]
      if (!file) {
        ElMessage.error('视频未生成，暂无视频下载！')
        return
      }
      const arr = file.split('.');
      const ext = arr[arr.length - 1].split("?")[0].toLowerCase();
      downLoadFile(file, `${data.one_info[fields.value.name]}.${ext}`)
    }
  } else {
    if (!item[fields.value.file]) {
      ElMessage.error('暂无资源！')
      return
    }
    const arr = item[fields.value.file].split('.');
    const ext = arr[arr.length - 1].split("?")[0].toLowerCase();
    downLoadFile(item[fields.value.file], `${item[fields.value.name]}.${ext}`)
  }
}

function handleEnter(data) {
  if (status.value !== '3') {
    const url = `${window.GLOBAL_CONFIG.spjj}/detail/${data.as_projectId}?originId=${data[fields.value.id]}&user_id=${user.value.user_id}&token=${user.value.token}&title=${data.as_title}`
    window.location.href = url
  } else {
    detailStore.setParams({
      catalog: catalog.value,
      idKey: fields.value.id,
      id: data[fields.value.id],
      cover: fields.value.img,
      name: fields.value.name,
      file: fields.value.file
    });
    router.push('/home/enter')
  }
}

if (sessionStorage.getItem('refresh') === '1') {
  sessionStorage.removeItem('refresh');
  location.reload();
}
</script>

<template>
  <div class="h-full flex flex-col">
    <div class="mb-15px flex items-center justify-between">
      <div class="flex space-x-6">
        <div v-for="(item, index) in statusData" :key="index" class="pageTitle" :class="status === item.status && 'active'" @click="changeStatus(item.status)">
          {{ item.name }}
        </div>
      </div>
      <div class="flex items-center">
        <template v-if="status==='1'" >
          <el-checkbox v-model="checkAll">全选</el-checkbox>
          <!-- <el-button type="primary" class="ml-20px h-42px w-130px" @click="handleCreate">创建审核</el-button> -->
        </template>
        <el-button v-if="status!=='3'" type="primary" class="ml-20px h-42px w-130px" @click="initDialog(true, '新增剪辑', 1)">新增剪辑</el-button>
        <div v-if="status==='3'" class="flex">
          <el-button type="primary" plain class="ml-20px h-42px w-130px bg-white" @click="handleMutiDelete">
            批量删除
          </el-button>
          <el-button type="primary" class="h-42px w-130px" @click="initDialog(true, '新增素材', 2)">
            上传素材
          </el-button>
        </div>
        <el-input v-model="params.keyword" class="ml-20px h-42px rounded-8px" placeholder="搜索" :prefix-icon="Search" />
      </div>
    </div>

    <CommonList ref="spjjListRef" class="flex-1" :to="catalog" :d="params" :fields="fields" :show-check="status==='2' ? false : true" :check-all="checkAll" @checkValue="initCheckData" @edit="handleEdit" @download="handleDownload" @enter="handleEnter">
      <template v-if="status === '3'" #search>
        <div class="flex items-center justify-end pr-80px pt-20px space-x-4">
          <div>筛选</div>
          <el-select v-model="params.az_type" class="select" size="large">
            <el-option label="全部" value="" />
            <el-option label="视频" value="1" />
            <el-option label="音频" value="2" />
            <el-option label="图片" value="3" />
          </el-select>
        </div>
      </template>
    </CommonList>

    <el-dialog v-model="dialogVisible" class="_" :title="dialogTitle" width="400px" destroy-on-close :close-on-click-modal="false" @close="initDialog(false, '', 0)">
      <el-form v-if="dialogType === 1" ref="jjFormRef" label-position="top" :model="jjForm" :rules="rules" class="demo-ruleForm">
        <el-form-item label="课程名称" prop="as_title">
          <el-input v-model="jjForm.as_title" />
        </el-form-item>
            <el-form-item label="年级" prop="azz_ssnj_v2" >
           <el-select 
          v-model="jjForm.azz_ssnj_v2"
          filterable
          clearable
          class="w-full"
          @change="handleChangeGrade"
        >
          <el-option
            v-for="item in grade_list"
            :key="item.grade_id"
            :label="item.grade_name"
            :value="item.grade_id"
          />
        </el-select>
         </el-form-item>
         <el-form-item label="学校" prop="as_zy_sm_id_v2" >
           <el-select 
          v-model="jjForm.as_zy_sm_id_v2"
          filterable
          clearable
          class="w-full"
          @change="handleSmChange"
        >
          <el-option
            v-for="item in school_list"
            :key="item.sm_id"
            :label="item.sm_name"
            :value="item.sm_id"
          />
        </el-select>
         </el-form-item>
         <el-form-item label="学院" prop="camp_id_v3" v-if="campusData.length>0" >
           <el-select 
          v-model="jjForm.camp_id_v3"
          filterable
          clearable
          class="w-full"
           @change="campChange"
        >
          <el-option
            v-for="item in campusData"
            :key="item.camp_id"
            :label="item.camp_name"
            :value="item.camp_id"
          />
        </el-select>
         </el-form-item>
         <el-form-item label="专业" prop="azz_id_v2" >
           <el-select 
          v-model="jjForm.azz_id_v2"
          filterable
          clearable
          class="w-full"
          @change="zyChange"
        >
          <el-option
            v-for="item in major_list"
            :key="item.azz_id_v2"
            :label="item.azz_name_v2"
            :value="item.azz_id_v2"
          />
        </el-select>
         </el-form-item>
         <el-form-item label="标签" prop="azb_id_v2" >
           <el-select 
          v-model="jjForm.azb_id_v2"
          filterable
          clearable
          class="w-full"
        >
          <el-option
            v-for="item in tag_list"
            :key="item.azb_id_v2"
            :label="item.azb_name_v2"
            :value="item.azb_id_v2"
          />
        </el-select>
         </el-form-item>
        <el-form-item label="封面上传">
          <common-upload v-model="jjForm.as_img" tip="上传比例限制308:200<br />建议上传小于500KB的jpg,jpeg,png格式图片" />
        </el-form-item>
      </el-form>
      <el-form v-if="dialogType === 2" ref="scFormRef" label-position="top" :model="scForm" :rules="rules" class="demo-ruleForm">
        <el-form-item label="名称">
          <el-input v-model="scForm.az_name" />
        </el-form-item>
        <template v-if="currentId === ''">
          <el-form-item label="封面上传">
            <common-upload v-model="scForm.az_img" tip="上传比例限制308:200<br />建议上传小于500KB的jpg,jpeg,png格式图片" />
          </el-form-item>
          <el-form-item label="素材上传" prop="az_file">
            <common-upload v-model="scForm.az_file" tip="建议上传mp4,mp3,jpg,png,jpeg格式的素材" type="video" aliyun="1" accept=".mp4,.mp3,.jpg,.jpeg,.webp,.png" />
            <!-- <common-upload v-model="scForm.az_file" tip=" " type="video" accept=".mp4,.mp3" /> -->
          </el-form-item>
        </template>
      </el-form>
      <el-button class="mt-30px h-48px w-full" type="primary"  :loading="loading"  @click="handleSubmit"  >
        确认
      </el-button>
    </el-dialog>
  </div>
</template>

<route lang="json">
  {
    "meta":{
      "title":"视频剪辑",
      "img":"/images/spjj.png",
      "sort": 3
    }
  }
</route>

<style lang="scss" scoped>
@use "~/styles/page.scss";
@use "~/styles/dialog.scss";
@use "~/styles/checkbox.scss";
:deep {
  .el-input__wrapper {
    // background: #f7f7f7;
    box-shadow: none;
  }
  .select {
    .el-input__wrapper {
      background: #f3f3f3;
    }
    &.el-select .el-input.is-focus .el-input__wrapper {
      box-shadow: none !important;
    }
  }
}
</style>