<script setup>
import { reactive, ref } from "vue";
import { ElMessage,ElMessageBox } from "element-plus";

import mPage from '@/components/mPage.vue';
import {pushSettingInterface} from '@/api/modules/pushSettingApi.js';
import {classifylist,interactiveInterface} from '@/api/api.js';

const tableColumns=[
  {label:'产品名称',key:'ClassifyName',minWidth:''},
  {label:'产品类型',key:'ConfigType',minWidth:''},
  {label:'优先类型',key:'Level',minWidth:''},
  {label:'更新时间',key:'ModifyTime',minWidth:''},
]
const tableData=ref([])
const total=ref(0)
const pageNo=ref(1)
const pageSize=ref(10)

const reactiveData=reactive({
  sortOption:{SortParam:'',SortType:''},
  settingItem:{
    ClassifyName:'',
    ConfigType:'',
    Level:'',
    ConfigId:0
  }
})

const isSettingDialogShow=ref(false) 
const productTypeOptions=[
  {id:1,label:'研报'},
  {id:2,label:'语音播报'},
  {id:3,label:'视频社区'},
  {id:4,label:'线上路演'},
]//现可推送的产品:研报、语音播报、视频社区、线上路演
const productNameOptions=ref([])//根据productType取相应值
const levelOptions=[
  {key:1,label:'紧急'},
  {key:2,label:'优先'},
  {key:3,label:'普通'}
]
const title=ref('添加产品')
const modifyType=ref('add')
const formRules={
  ClassifyName: [
      { required: true, message: '请选择产品', trigger: 'change' }
  ],
  ConfigType: [
      { required: true, message: '请选择产品类型', trigger: 'change' }
  ],
  Level: [
      { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

const priorityFormRef=ref(null)

const handleModifyPriority=(type,data)=>{
  modifyType.value = type
  productNameOptions.value=[]
  if(type==='add'){
    title.value = '添加产品'
    reactiveData.settingItem={ClassifyName:'',ConfigType:'',Level:'',ConfigId:0}
  }else{
    title.value='编辑优先类型'
    const {ClassifyName,ConfigType,Level,ConfigId} = data
    reactiveData.settingItem = {ClassifyName,ConfigType,Level,ConfigId}
  }
  isSettingDialogShow.value = true 
}
const deleteSetting=(data)=>{
  ElMessageBox.confirm('删除后不可恢复，确认删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const {ConfigId} = data
    pushSettingInterface.deletePriority({ConfigId}).then((res)=>{
      if(res.Ret!==200) return 
      ElMessage.success('删除成功')
      changePage(1)
    })
  }).catch(()=>{})
}
const getTableData=()=>{
  const {SortParam, SortType} = reactiveData.sortOption
  pushSettingInterface.getPriorityList({
    SortParam,SortType,
    CurrentIndex:pageNo.value,
    PageSize:pageSize.value
  }).then(res=>{
    if(res.Ret!==200) return 
    const {Paging,List} = res.Data
    tableData.value = List||[]
    total.value = Paging.Totals
  })
}
const changePage=(page)=>{
  pageNo.value=page
  getTableData()
}
const sortChangeHandle=({ prop,order })=>{
  let SortParam='',SortType=''
  SortType = order==='ascending'?'asc':order==='descending'?'desc':''
  SortParam = prop==='Level'&&SortType?'level':''
  reactiveData.sortOption = {SortParam,SortType}
  getTableData()
}
//产品类型变化时
const handleSelectChange=()=>{
  const {ConfigType} = reactiveData.settingItem
  //重置产品名称的值
  reactiveData.settingItem.ClassifyName=''

  productNameOptions.value = []
  //根据ConfigType决定productNameOptions的值
  const configTypeMap = {
    '研报':getReportClassify,
    '语音播报':getVoiceClassify
  }
  if(configTypeMap[ConfigType]){
    configTypeMap[ConfigType]()
  }else{
    productNameOptions.value = [{key:0,label:ConfigType}]
  }
}
//获取研报的分类列表,转换结构后赋值给productNameOptions
const getReportClassify=()=>{
  classifylist({
    CurrentIndex: 0, PageSize: 1000,
  }).then(res=>{
    if(res.Ret!==200||!Array.isArray(res.Data.List)) return
    let tempArr = []
    res.Data.List.forEach(item=>{
      let tempItem = {
        key:item.Id,
        label:item.ClassifyName,
      }
      if(item.Child&&item.Child.length>0){
        tempItem.children = []
        item.Child.forEach(i=>{
          let tempI = {
            key:i.Id,
            label:i.ClassifyName
          }
          tempItem.children.push(tempI)
        })
      }
      tempArr.push(tempItem)
    })
    productNameOptions.value = tempArr
  })
}
//获取语音播报板块列表,转换结构后赋值给productNameOptions
const getVoiceClassify=()=>{
  interactiveInterface.voiceList({
    CurrentIndex: pageNo.value,
    PageSize:1000
  }).then(res=>{
    if(res.Ret!==200||!Array.isArray(res.Data.List)) return
    let tempArr = []
    res.Data.List.forEach(item=>{
        let tempItem = {
        key:item.SectionId,
        label:item.SectionName,
      }
      tempArr.push(tempItem)
    })
    productNameOptions.value = tempArr
  })
}
const saveChange=async ()=>{
  let formValid = null
  await priorityFormRef.value.validate((valid)=>{formValid = valid})
  if(!formValid) return 
  const {ConfigType,Level,ClassifyName,ConfigId} = reactiveData.settingItem
  if(modifyType.value==='edit'){
    pushSettingInterface.editPriority({
      ConfigId,Level
    }).then(res=>{
      if(res.Ret!==200) return 
      ElMessage.success('编辑成功')
      closeDialog()
      changePage(1)
      return
    })
  }else{
    let ClassifyId = 0
    if(ConfigType==='研报'){
      ClassifyId =Number(ClassifyName[ClassifyName.length-1]) 
    }else if(ConfigType==='语音播报'){
      ClassifyId = ClassifyName
    }
    pushSettingInterface.addPriority({
      ConfigType,ClassifyId,Level
    }).then(res=>{
      if(res.Ret!==200) return
      ElMessage.success('添加成功')
      closeDialog()
      changePage(1)
      return
    })
  }
  
}
const closeDialog=()=>{
  reactiveData.settingItem={ClassifyName:'',ConfigType:'',Level:'',ConfigId:0}
  priorityFormRef.value.resetFields()
  isSettingDialogShow.value = false
}

getTableData()

</script>

<template>
  <div class="priority-setting-list">
    <div class="add-btn-wrap">
      <el-button type="primary" @click="handleModifyPriority('add',{})">添加产品</el-button>
    </div>
    <div class="setting-table">
      <el-table :data="tableData" border @sort-change="sortChangeHandle">
        <el-table-column v-for="item in tableColumns" 
          :label="item.label"
          :key="item.key"
          :prop="item.key"
          :sortable="item.key==='Level'?'custom':false"
          align="center">
          <template #default="{row}">
            <span v-if="item.key==='Level'">
              {{levelOptions[row['Level']-1].label}}
            </span>
            <span v-else>{{row[item.key]||'--'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <span
              style="cursor: pointer; font-size: 14px; color: #409eff;margin-right:15px;"
              @click="handleModifyPriority('edit',row)"
              >编辑</span>
            <span
              style="cursor: pointer; font-size: 14px; color: #D1433A"
              @click="deleteSetting(row)"
              >删除</span>
          </template>
        </el-table-column>
        <template #empty>
          <div class="table-noData">
            <img src="~@/assets/img/cus_m/nodata.png" />
            <span>暂无数据</span>
          </div>
        </template>
      </el-table>
    </div>
    <m-page
      :page_no="pageNo"
      :pageSize="pageSize"
      :total="total"
      style="position: absolute; right: 50px; bottom: 50px"
      @handleCurrentChange="changePage"
    />
    <!-- 添加/编辑产品弹窗 -->
    <el-dialog
      :title="title"
      v-model="isSettingDialogShow"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      width="592px"
      @closed="closeDialog"
    >
    <div class="dialog-container">
      <el-form :model="reactiveData.settingItem" :rules="formRules" ref="priorityFormRef" style="max-width: 300px;margin: 0 auto;">
        <el-form-item label="产品类型" prop="ConfigType">
          <el-select placeholder="请选择产品类型" :disabled="modifyType==='edit'"
            v-model="reactiveData.settingItem.ConfigType"  @change="handleSelectChange">
              <el-option v-for="productType in productTypeOptions" :key="productType.id"
                :label="productType.label" :value="productType.label"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="ClassifyName">
          <template v-if="reactiveData.settingItem.ConfigType==='研报'&&modifyType==='add'">
            <el-cascader 
            placeholder="请选择产品名称"
            v-model="reactiveData.settingItem.ClassifyName" 
            :options="productNameOptions"
            :props="{value:'key',label:'label'}"
            >
            </el-cascader>
          </template>
          <template v-else>
            <el-select placeholder="请选择产品类型" :disabled="modifyType==='edit'" v-model="reactiveData.settingItem.ClassifyName">
              <el-option v-for="productName in productNameOptions" :key="productName.key"
                :label="productName.label" :value="productName.key"
              />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="优先类型" prop="Level">
          <el-select placeholder="请选择优先类型" v-model="reactiveData.settingItem.Level">
              <el-option v-for="level in levelOptions" :key="level.key"
                :label="level.label" :value="level.key"
              />
            </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template  #footer>
      <div class="foot-container">
        <el-button type="primary" @click="saveChange">保 存</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>

    </el-dialog>
  </div>
</template>

<style lang="scss">
.priority-setting-list{
  .dialog-container{
    .el-form-item{
      .el-cascader{
        .el-input{
          width: 100%;
        }
      }
    }
  }
}
.el-dialog .el-input{
  width: 100%;
}
</style>
<style scoped lang="scss">
.priority-setting-list{
  .add-btn-wrap{
    text-align: right;
    position: relative;
    .el-button{
      position:absolute;
      right:0;
      top:-70px;
    }
  }
  .setting-table{
    .table-noData{
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin: 18vh 0;
      img{
        height: 110px;
        width: 136px;
      }
      span{
        font-weight: 400;
        font-size: 16px;
        color: #999999;
      }
    }
  }
  .dialog-container{
    .el-form{
      .el-form-item{
        display: flex;
        justify-content: center;
      }
    }
  }
  .foot-container{
    text-align: center;
  }
}
</style>
