<template>
  <div>
    <div class="screenBox_mini">
      <Input ref="InputRef_text" title="关键词" placeholderTxt="关键词" @changeEvent="()=>init()" @clearEvent="()=>init()"/>
      <Select ref="acRef"
              title="账号"
              selectWidth="160px"
              @changeEvent="()=>init()" @clearEvent="()=>init()"
              :isMultiple="true"
              :optObj="{k:'account_id',la:'account_id',val:'account_id'}"
              :options="pageInfo.acList"/>
      <Select ref="statusRef"
              title="状态"
              selectWidth="160px"
              @changeEvent="()=>init()" @clearEvent="()=>init()"
              :options="pageInfo.statusList"/>
      <TimeScreen title="时间" selectWidth="260px" :haveQuick="false" :clearFlag="true" :valueIsKong="true"
                  ref="timeRef"
                  @init="()=>init()"></TimeScreen>
      <span class="pointer c-theme lMar10" @click="clearEvent">清空</span>
      <el-button class="lMarauto" type="primary" @click="goNewPlanEvent">新建计划</el-button>
    </div>
    <div>
      <div class="bMar10 flex">
        <Dropdown title="批量操作" :list="tableInfo.moreList" @close="dropdownEvent" class="rMar10"
                  :disabledFlag="tableInfo.multipleSelection&&tableInfo.multipleSelection.length == 0"></Dropdown>
        <div>已选 : <span>{{tableInfo.multipleSelection&&tableInfo.multipleSelection.length}}</span></div>
<!--        <el-button class="lMarauto" type="primary" @click="customIndEvent">自定义指标</el-button>-->

        <div  class="lMarauto">
          <Indicators type="media_base" @refresh="IndicatorsRefreshList"></Indicators>
        </div>
      </div>
我是账户列表
      <el-table v-loading="loading" ref="tableRef" :data="tableInfo.tableList"
                :header-cell-style="tableHeaderStyle"
                :key="tableInfo.updateKey" style="width: 100%"
                border empty-text="暂无数据"
                row-key="campaign_id"
                max-height="calc(100vh - 294px)">
        <el-table-column fixed width="80" >
          <template #header>
            <div class="flex">
              <el-checkbox v-model="tableInfo.chooseAll" @change="allChooseCheckboxEvent"></el-checkbox>
              <el-dropdown class="lMar10" @command="handleCommandChoosePage">
                <el-icon color="#3173FF"><i-ep-ArrowDownBold /></el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="1">当前页</el-dropdown-item>
                    <el-dropdown-item command="2">全部</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          <template #default="scope">
            <div class="checkBoxSelf flex"
                 @click="singleChooseCheckboxEvent(tableInfo.multipleSelection.findIndex(n=>n.campaign_id == scope.row.campaign_id),scope.row)"
                 :class="tableInfo.multipleSelection.findIndex(n=>n.campaign_id == scope.row.campaign_id)>=0 ? 'active' : ''">
              <el-icon color="#fff" v-if="tableInfo.multipleSelection.findIndex(n=>n.campaign_id == scope.row.campaign_id)>=0"><i-ep-Check /></el-icon>
            </div>
          </template>
        </el-table-column>
        <template v-for="item in tableInfo.descol">
          <el-table-column :fixed="item.isfixed" :min-width="item.minWidth ? item.minWidth : '80px'">
            <template #header>
              <div class="flex"
                   :style="{ justifyContent: item.alignSelf ? item.alignSelf : 'center' }"
                   :class="[tableInfo.sortKey == item.column ? 'active_css' : '',item.isSort ? 'pointer' : '']"
                   @click="item.isSort&&sortEvent(item.column)">
                {{ item.name }}
                <el-tooltip v-if="item.notes" effect="dark" :content="item.notes"><i-ep-QuestionFilled class="lMar5 c-999 f14 pointer" /></el-tooltip>
                <div v-if="item.isSort">
                  <div class="sortItem"><el-icon :color="tableInfo.sortKey == item.column ? '#3173FF' : ''"><i-ep-CaretBottom /></el-icon></div>
                </div>
              </div>
            </template>
            <template #default="scope">
              <div class="flex" :style="{ justifyContent: item.alignSelf ? item.alignSelf : 'center' }">

              <div v-if="item.column == 'campaign_name'">
                <span class="c-theme flex campaignName">
                  <span class="pointer" @click="goAdvertEvent(scope.row.campaign_id)">{{scope.row[item.column]}}</span>
                  <el-icon color="#3173FF" class="pointer lMarauto f16 icon" @click="edit_campaign_name_event(scope.row)"><i-ep-Edit /></el-icon>
                </span>
              </div>
              <div v-else-if="item.column == 'configured_status'">
                <span class="c-green" v-if="scope.row[item.column] == 'AD_STATUS_NORMAL'">正常</span>
                <span class="c-red" v-else-if="scope.row[item.column] == 'AD_STATUS_SUSPEND'">暂停</span>
                <span v-else>-</span>
              </div>
              <div v-else-if="item.column == 'speed_mode'">
                <span v-if="scope.row[item.column] == 'SPEED_MODE_STANDARD'">标准投</span>
                <span v-else-if="scope.row[item.column] == 'SPEED_MODE_FAST'">加速投放</span>
                <span v-else>-</span>
              </div>
              <div v-else-if="item.column == 'operate'">
                <div class="flex">
                  <span class="c-theme pointer" @click="editPlanEvent(scope.row)">修改</span>
                  <span class="lMar10"
                        :class="scope.row.configured_status == 'AD_STATUS_NORMAL' ? 'pointer-drop c-green-opa' : 'pointer c-green'"
                        @click="scope.row.configured_status == 'AD_STATUS_SUSPEND'&&batchPlanEvent(scope.row,1)">启用</span>
                </div>
                <div>
                    <span :class="scope.row.configured_status == 'AD_STATUS_SUSPEND' ? 'pointer-drop c-red-opa' : 'pointer c-red'"
                          @click="scope.row.configured_status == 'AD_STATUS_NORMAL'&&batchPlanEvent(scope.row,2)">暂停</span>
                  <Popconfirm key="dele" @confirm="batchPlanEvent(scope.row,3)" :slotFlag="true">
                    <template #con>
                      <span class="pointer lMar10">删除</span>
                    </template>
                  </Popconfirm>

                </div>


              </div>
              <div class="flex c-theme pointer" v-else-if="item.column == 'daily_budget'" @click="editPlanEvent(scope.row)">
                {{scope.row[item.column] ? NumberHandle(scope.row[item.column]) : '不限'}}
              </div>


              <div class="cellDiv" :class="tableInfo.sortKey == item.column ? 'active_css' : ''" v-else>
                <el-tooltip :disabled="!(scope.row[item.column] && scope.row[item.column].length >30)" effect="dark" :content="scope.row[item.column]+''">
                  <div class="clampTwo line21" style="flex: 1">
                    {{ scope.row[item.column] || scope.row[item.column]==0 ?
                      (item.cancleForMat ? (scope.row[item.column] ? scope.row[item.column] : '-') : NumberHandle(scope.row[item.column])) : '-'}}
                    <span v-if="item.hasPercent&&(scope.row[item.column] || scope.row[item.column] ==0)">%</span>
                  </div>
                </el-tooltip>
              </div>
              </div>
            </template>
          </el-table-column>
        </template>
      </el-table>

      <div class="paginationBox flex" style="justify-content: center" v-if="Number(tableInfo.total) > 0">
        <el-pagination
            v-model:currentPage="tableInfo.currentPage"
            v-model:page-size="tableInfo.pageSize"
            background
            :total="tableInfo.total"
            @current-change="handleCurrentChange" />
      </div>
    </div>

    <EditIpt ref="planEditIptRef" title="推广计划" @confirm="planEditConfirm"></EditIpt>
    <TargetEdit ref="TargetEditRef" title="计划设置" @confirm="init"></TargetEdit>
  </div>
</template>
<script setup lang="ts">
import {getCurrentInstance, nextTick, onMounted, reactive, ref} from "vue";
import Select from '@/components/capsulationMoudle/_select.vue'
import TimeScreen from '@/components/capsulationMoudle/timeScreen.vue'
import Input from '@/components/capsulationMoudle/_input.vue'
import EditIpt from '@/components/businessMoudle/gdtList/dialog/editIpt.vue'
import TargetEdit from '@/components/businessMoudle/gdtList/dialog/target.vue'
import Dropdown from '@/components/capsulationMoudle/_dropdown.vue'
import Popconfirm from '@/components/capsulationMoudle/_popconfirm.vue'
import noData from '@/components/capsulationMoudle/noData.vue'
import {listTs} from "@/components/businessMoudle/gdtList/ts/list";
import {Api} from "@/api/api";
import {ElMessage} from "element-plus";
import {batchGdt_edit, batchGdt_list, reactiveTableAndAny} from "@/api/ApiModel";
import Indicators from './indicators/index.vue'

const { proxy } = getCurrentInstance() as any;
// 全局方法定义
const NumberHandle = proxy.$NumberHandle

const emit = defineEmits<{
  (event: "goNewPlan"): void;
  (event: "goAdvert",campaign_id:any): void;
}>();
const goNewPlanEvent = () => {
  emit('goNewPlan')
}
const goAdvertEvent = (campaign_id:any) => {
  emit('goAdvert',campaign_id)
}

const loading = ref<boolean>(false)
const tableInfo = reactive<reactiveTableAndAny>({
  tableList:[],
  tableList_all:[],
  descol:[
    { name:'计划名称',column:'campaign_name',slotFlag: true,isfixed:true,alignSelf:'left'},
    { name:'操作',column:'operate',slotFlag: true,isfixed:true},
    { name:'账号ID',column:'account_id',cancleForMat:true},
    { name:'计划ID',column:'campaign_id',cancleForMat:true},
    { name:'计划类型',column:'campaign_type'},
    { name:'推广目标类型',column:'promoted_object_type'},
    { name:'日预算(元)',column:'daily_budget',slotFlag: true},
    // { name:'总预算',column:'total_budget'},
    { name:'投放日期',column:'created_time'},
    { name:'客户状态',column:'configured_status',slotFlag: true},
    { name:'投放速度',column:'speed_mode',slotFlag: true},
  ],
  multipleSelection:[],
  updateKey:1,
  chooseAll:false,
  sortKey:'',
  moreList:[
    {value:'1',label:'启用'},
    {value:'2',label:'暂停'},
    {value:'3',label:'删除'},
  ],
  currentPage:1,
  pageSize:20,
  total:0,
  totalPages:0,//共多少页
})



//批量操作
const batchEvent = () => {

}

// 启用 暂停 删除
const batchPlanApi = async (arr?:any,val?:any) => {
  const paramsModel = reactive<batchGdt_edit>({
    campaign_infos:JSON.stringify(arr),
    flag:val?val:0
  })
  let res:any = await proxy.$http.post(Api.batchGdt_plan_batch_edit,paramsModel)
  ElMessage.info(res.errMsg)
  if(res&&res.errNo=='0'){
    init()
    tableInfo.multipleSelection = []
  }else{
    loading.value = false
  }
}
const batchPlanEvent = async (row?:any,val?:any) => {
  loading.value = true
  let arr:any = []
  arr.push({
    account_id:row.account_id,
    campaign_id:row.campaign_id
  })
  batchPlanApi(arr,val)

}
const dropdownEvent = (val: string | number | object) => {
  loading.value = true
  let arr:any = []
  tableInfo.multipleSelection.forEach(item=>{
    arr.push({
      account_id:item.account_id,
      campaign_id:item.campaign_id
    })
  })
  batchPlanApi(arr,val)
}

//修改计划
const editPlanEvent = (row:any) => {
  nextTick(()=>{
    TargetEditRef.value!.switchShow(true,row)
  })
}
//修改计划名称
const edit_campaign_name_event = (row:any) => {
  nextTick(()=>{
    planEditIptRef.value!.switchShow(true,row.campaign_name)
  })
}
//推广计划 - 确定
const planEditConfirm = () => {

}


//排序
const sortEvent = (row:any) => {

}

//列表
const init = async (page?:any,totalPages?:any) => {
  loading.value = true
  const paramsModel = reactive<batchGdt_list>({
    account_ids:acRef.value!.value,
    keyword:InputRef_text.value!.value,
    status:statusRef.value!.value,
    start:timeRef.value!.dateVal&&timeRef.value!.dateVal[0],
    end:timeRef.value!.dateVal&&timeRef.value!.dateVal[1],
    page:page?page:1,
    pageSize:totalPages ? totalPages : tableInfo.pageSize
  })
  let res:any = await proxy.$http.get(Api.batchGdt_plan_list,paramsModel)
  loading.value = false
  if(res&&res.errNo=='0'){
    if(totalPages){
      tableInfo.tableList_all = res.rst.data
    }else{
      tableInfo.tableList = res.rst.data
      tableInfo.total = res.rst.pageInfo.total
      tableInfo.totalPages = res.rst.pageInfo.total
    }
  }else{
    ElMessage.error(res.errMsg)
  }
}

//分页
const handleCurrentChange = (val) => {
  tableInfo.currentPage = val
  init(val)
}


//清空值
const clearChooseVal = ()=>{
  tableInfo.chooseAll = false
  tableInfo.multipleSelection = []
}
//添加值
const multipleSelection_add = (item?:any) => {
  let idx:number = tableInfo.multipleSelection.findIndex(n=>n.campaign_id == item.campaign_id)
  if(idx<0){
    tableInfo.multipleSelection.push(item)
  }
}
//删除值
const multipleSelection_splice = (item?:any) => {
  let idx:number = tableInfo.multipleSelection.findIndex(n=>n.campaign_id == item.campaign_id)
  if(idx>=0){
    tableInfo.multipleSelection.splice(idx,1)
  }
}
const handleCommandChoosePage = async (command: string | number | object)=>{
  let arr:any = tableInfo.tableList
  clearChooseVal()
  tableInfo.chooseAll = true
  if(command == 2){ // 全部
    await init(1,tableInfo.totalPages)
    arr = tableInfo.tableList_all
  }
  arr.forEach(item=>{
    multipleSelection_add(item)
  })
}
//全选
const allChooseCheckboxEvent = (val:string | number | boolean)=>{
  tableInfo.tableList.forEach(item=>{
    if(val){
      multipleSelection_add(item)
    }else{
      tableInfo.multipleSelection = []
    }
  })
}
//单选
const singleChooseCheckboxEvent = (idx:number,row:any)=>{
  if(idx==-1){
    tableInfo.multipleSelection.push(row)
  }else{
    tableInfo.multipleSelection.splice(idx,1)
    tableInfo.chooseAll = false
  }
}

const IndicatorsRefreshList = () => {
  //这里刷新列表
}

const {
  init_acList,
  pageInfo,
  timeRef,
  acRef,
  statusRef,
  InputRef_text,
  clearEvent,
  tableHeaderStyle,
  planEditIptRef,
  TargetEditRef,
  customIndEvent
} = listTs()

onMounted(()=>{
  nextTick(async ()=>{
    await init_acList()
    await init()
  })
})
</script>
<style lang="scss" scoped>
.campaignName{
  .icon{
    color: #3173FF;
    opacity: 0;
  }
  &:hover{
    .icon{
      opacity: 1;
    }
  }
}
.checkBoxSelf{
  width: 13px;
  height: 13px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  &:hover{
    cursor: pointer;
    border: 1px solid #3173FF;
  }
  &.active{
    border: 1px solid #3173FF;
    background-color: #3173FF;
  }
}
</style>
