<template>
    <div>
      <div class="gva-search-box">
        <el-form ref="searchForm" :inline="true" :model="searchInfo">
          <el-form-item label="任务Id">
            <el-input v-model="searchInfo.task_id" placeholder="任务Id" />
          </el-form-item>
          <el-form-item label="负责人">
            <el-select v-model="searchInfo.user" placeholder="负责人" >
            <el-option
                v-for="item in ResponsiblePerson"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
          <el-select v-model="searchInfo.status" placeholder="是否完成" >
              <el-option
                v-for="item in searchStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
        </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
            <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="gva-table-box">
        <div class="gva-btn-list">
          <el-button size="small" type="primary" icon="plus" @click="openDialog('addCard')">新增</el-button>
        </div>
        <el-table :data="tableData" border @sort-change="sortChange" @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column align="left" label="任务ID" min-width="60" prop="task_id" sortable="custom" />
          <el-table-column align="left" label="任务名称" min-width="60" prop="task_name" sortable="custom" />
          <el-table-column align="left" label="负责人" min-width="60" prop="user" sortable="custom" />
          <el-table-column align="left" label="游戏名称" min-width="80" prop="game_name" sortable="custom" />
          <el-table-column align="left" label="游戏端口" min-width="60" prop="game_port" />
          <el-table-column align="left" label="登录方式" min-width="60" prop="login_method" />
          <el-table-column align="left" label="开始时间" min-width="80" prop="date" />
          <el-table-column align="left" label="停止时间" min-width="110" prop="stop_time" />
          <el-table-column align="left" label="新增目标" min-width="80" prop="new_target">
            <template #default="scope">
              {{ scope.row.new_target_h === 0 ? 0 : scope.row.new_target+"~"+scope.row.new_target_h}}
            </template>
          </el-table-column>
          <el-table-column align="left" label="留存目标" min-width="80" prop="retained_target">
            <template #default="scope">
              {{ scope.row.retained_target_h === scope.row.retained_target ? scope.row.retained_target_h : scope.row.retained_target+"~"+scope.row.retained_target_h}}
            </template>
          </el-table-column>
          <el-table-column align="left" label="付费目标" min-width="45" prop="pay_target" />
          <el-table-column align="left" label="付费单价" min-width="45" prop="pay_price"  />
          <!-- <el-table-column align="left" label="状态" min-width="60" prop="status" >
            <template #default="scope">
              <div>
                <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">{{ statusFiletr(scope.row.status) }}</el-tag>
              </div>
            </template>
          </el-table-column> -->
          <el-table-column align="left" label="状态" min-width="60">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              inline-prompt
              :active-value="1"
              :inactive-value="-1"
              @change="()=>{switchEnable(scope.row)}"
            />
          </template>
        </el-table-column>
          <el-table-column align="left" label="创建时间" min-width="120" prop="create_time" sortable="custom" />
          <el-table-column align="left" label="更新时间" min-width="120" prop="update_time" sortable="custom" />
          <el-table-column align="left" fixed="right" label="操作" width="140">
            <template #default="scope">
              <el-button
                icon="edit"
                size="small"
                type="primary"
                link
                @click="editCardFunc(scope.row)"
              >编辑</el-button>
              <el-button
              icon="delete"
              size="small"
              type="primary"
              link
              @click="deleteApiFunc(scope.row)"
            >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="gva-pagination">
          <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
  
      </div>
  
      <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="dialogTitle">
        <el-form ref="apiForm" :model="form" :rules="rules" label-width="80px" :inline="true">
          <el-form-item label="任务ID" prop="task_id">
            <el-input v-model="form.task_id" autocomplete="off" :disabled="(form.is_add == 0)" />
          </el-form-item>
          <el-form-item label="任务名称" prop="task_name">
            <el-input v-model="form.task_name" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="负责人" prop="user" >
            <el-select v-model="form.user" placeholder="请选择" style="width:100%">
                  <el-option
                    v-for="item in ResponsiblePerson"
                    :key="item.id"
                    :label="`${item.name}`"
                    :value="item.name"
                  />
                </el-select>
          </el-form-item>
          <el-form-item label="重要参数">
            <el-radio-group v-model="form.new_retained">
              <el-radio border label="1">用新增做付费,会同步至机房</el-radio>
              <el-radio border label="2">用留存做付费,会同步至机房</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        
        <el-tabs type="border-card">
          <el-tab-pane label="基本信息">
            <el-form ref="apiForm" :model="form" :rules="rules" label-width="80px">
              <!-- <el-form-item  label="游戏名称" prop="game_name">
                <el-col :span="12">
                <el-autocomplete
                    v-model="form.game_name"
                    :fetch-suggestions="querySearch"
                    @select="handleSelect"
                    value-key="game_name"
                  >
                    <template #default="{ item }">
              
                      <div class="name">{{ item.value=item.game_name }}</div>
                    </template>
                  </el-autocomplete>
                </el-col>
              </el-form-item> -->
              <el-form-item label="游戏名称" prop="game_name">
              <el-select
                v-model="form.game_name"
                size="small"
                @change="changeTask"
                filterable
              >
                <el-option
                  v-for="item in links"
                  :key="item.game_id"
                  :label="item.game_name"
                  :value="item.game_name"
                />
              </el-select>
            </el-form-item>
            </el-form>
            <el-form ref="apiForm" :model="form" :rules="rules" :inline="true">
              <!-- <el-form-item label="开始日期" prop="date">
                <el-date-picker
                  v-model="form.date"
                  popper-class="picker-popovers"
                  :shortcuts="rangeShortcuts"
                  class="timefilter"
                  @visible-change="handleVisibleChange"
                  type="datetime"
                  placeholder="选择日期时间"
                  :prefix-icon="customPrefix"
                  value-format="YYYY-MM-DD HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item> -->
              <el-form-item label="游戏端口" prop="game_port_id">
                <el-select v-model="form.game_port_id" placeholder="请选择" style="width:100%">
                  <el-option
                    v-for="item in GamePortOptions"
                    :key="item.Id"
                    :label="`${item.ChannelName}`"
                    :value="item.Id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="账号类型" prop="account_type" >
                <el-select v-model="form.account_type" placeholder="请选择" style="width:100%">
                  <el-option
                    v-for="item in accountTypeOptions"
                    :key="item.Id"
                    :label="`${item.TypeName}`"
                    :value="item.Id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="登录方式" prop="login_method">
                <el-select v-model="form.login_method" placeholder="请选择" style="width:100%">
                  <el-option
                    v-for="item in loginMethodOptions"
                    :key="item.Id"
                    :label="`${item.LoginName}`"
                    :value="item.Id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="腾讯渠道" prop="tx_channel" v-if="(form.login_method == 6 || form.login_method == 3 || form.login_method == 5 )">
                <el-input v-model="form.tx_channel" autocomplete="off" />
              </el-form-item>
              <el-form-item label="腾讯游戏Id" prop="tx_game_id" v-if="(form.login_method == 6 || form.login_method == 3 || form.login_method == 5 )">
                <el-input v-model="form.tx_game_id" autocomplete="off" />
              </el-form-item>
              <el-form-item label="魅族渠道" prop="mz_channel" v-if="(form.login_method == 2 || form.game_port_id == 5)">
                <el-input v-model="form.mz_channel" autocomplete="off" />
              </el-form-item>
              <el-form-item label="魅族游戏Id" prop="mz_game_id" v-if="(form.login_method == 2 || form.game_port_id == 5)">
                <el-input v-model="form.mz_game_id" autocomplete="off" />
              </el-form-item>
              <el-form-item label="小绵羊Id" prop="game_id_xmy" v-if="(form.login_method == 1)">
                <el-input v-model="form.game_id_xmy" autocomplete="off" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="数优目标">
              <el-form ref="apiForm" :model="form" :rules="rules" label-width="120px" :inline="true">
                <el-form-item  label="新增目标下限" prop="new_target">
                  <el-input v-model="form.new_target" autocomplete="off" />
                </el-form-item>
                <el-form-item  label="新增目标上限" prop="new_target_h">
                  <el-input v-model="form.new_target_h" autocomplete="off" />
                </el-form-item>
                <el-form-item label="付费目标" prop="pay_target">
                  <el-input v-model="form.pay_target" autocomplete="off"/>
                </el-form-item>
            </el-form>
            <el-form ref="apiForm" :model="form" :rules="rules" label-width="120px" :inline="true">
                <el-form-item label="留存目标下限" prop="retained_target" >
                  <el-input v-model="form.retained_target" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="留存目标上限" prop="retained_target_h" >
                  <el-input v-model="form.retained_target_h" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="付费单价" prop="pay_price" >
                  <el-input v-model="form.pay_price" autocomplete="off"/>
                </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <template #footer>
          <div class="dialog-footer">
            <el-button size="small" @click="closeDialog">取 消</el-button>
            <el-button size="small" type="primary" @click="enterDialog">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  export default {
    name: 'GameTask',
  }
  </script>
  
  <script setup>
  import {
    getPcList,
    getPcById,
    createPc,
    updatePc,
    colsePc,
  } from '@/api/computer'
  import {
    createGameTask,
    getGameTaskList,
    getGameTaskById,
    statusOperation,
    updateGameTask,
    deleteGameTask,
  } from '@/api/task'
  import {
    selectResponsiblePerson,
} from '@/api/responsiblePerson'
  import { useUserStore } from '@/pinia/modules/user'
  import { toSQLLine } from '@/utils/stringFun'
  import warningBar from '@/components/warningBar/warningBar.vue'
  import { ref } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {downloadTemplate } from '@/api/excel'
  
  const downloadExcelTemplate = () => {
    downloadTemplate('PcCodeExcelTemplate.xlsx')
  }
  
  const loadExcel = (res) => {
    if(res.code === 0){
      ElMessage({
        type: 'success',
        message: res.msg
      })
    }else{
      ElMessage({
        type: 'error',
        message: res.msg,
        showClose: true
      })
    }
  }
  
  const path = ref(import.meta.env.VITE_BASE_API)
  const userStore = useUserStore()
  const typeFiletr = (value) => {
    const target = typeOptions.value.filter(item => item.value === value)[0]
    return target && `${target.label}`
  }
  
  const statusFiletr = (value) => {
    const target = statusOptions.value.filter(item => item.value === value)[0]
    return target && `${target.label}`
  }
  const ResponsiblePerson = ref([])
  const getResponsiblePerson = async() => {
    const table = await selectResponsiblePerson()
    if (table.code === 0) {
      ResponsiblePerson.value = table.data
    }
  }
  getResponsiblePerson()
  const searchStatusOptions = ref([
    {
      value: -1,
      label: '关闭',
      type: 'success'
    },
    {
      value: 1,
      label: '运行中',
      type: ''
    }
  ])
  
  const apis = ref([])
  const rules = ref({
    task_id: [{ required: true, message: '输入任务ID', trigger: 'blur' }],
    task_name: [
      { required: true, message: '请输入任务名称', trigger: 'blur' }
    ],
    user: [
      { required: true, message: '请输入使用者', trigger: 'blur' }
    ],
    new_retained: [
      { required: true, message: '请选择重要参数', trigger: 'blur' }
    ],
    game_name: [
      { required: true, message: '请选择游戏', trigger: 'blur' }
    ],
    date: [
      { required: true, message: '请选择开始时间', trigger: 'blur' }
    ],
    game_port_id: [
      { required: true, message: '请选择游戏端口', trigger: 'blur' }
    ],
    account_type: [
      { required: true, message: '请选择账号类型', trigger: 'blur' }
    ],
    login_method: [
      { required: true, message: '请选择登录方式', trigger: 'blur' }
    ],
    tx_channel: [
      { required: true, message: '请输入腾讯渠道号', trigger: 'blur' }
    ],
    mz_channel: [
      { required: true, message: '请输入魅族渠道号', trigger: 'blur' }
    ],
    new_target: [
      { required: true, message: '请输入新增目标', trigger: 'blur' }
    ],
    new_target_h: [
      { required: true, message: '请输入新增上限', trigger: 'blur' }
    ],
    pay_target: [
      { required: true, message: '请输入付费目标', trigger: 'blur' }
    ],
    retained_target: [
      { required: true, message: '请输入留存目标', trigger: 'blur' }
    ],
    retained_target_h: [
      { required: true, message: '请输入留存上限', trigger: 'blur' }
    ]
  })
  const form = ref({
    task_id: '',
    task_name: '',
    user: '',
    new_retained: '1',
    game_name:'',
    date:'',
    game_port_id:'',
    account_type:'',
    login_method:'',
    tx_channel:'',
    tx_game_id:'',
    mz_channel:'',
    mz_game_id:'',
    game_id_xmy:'',
    new_target:'',
    pay_target:'',
    retained_target:'',
    pay_price:'',
  })
  const statusOptions = ref([
    {
      value: -1,
      label: '关闭',
      type: 'wain'
    },
    {
      value: 1,
      label: '使用',
      type: 'success'
    }
  ])

  const GamePortOptions = ref([
    // {
    //   id: 1,
    //   name: '腾讯游戏',
    // },
    // {
    //   id: 2,
    //   name: '360游戏',
    // },
    // {
    //   id: 3,
    //   name: '网易游戏',
    // },
    // {
    //   id: 4,
    //   name: '酷派游戏',
    // },
    // {
    //   id: 5,
    //   name: '魅族游戏',
    // },
  ])

  const accountTypeOptions = ref([
    // {
    //   id: 1,
    //   name: '小绵羊账号',
    // },
    // {
    //   id: 2,
    //   name: 'QQ账号',
    // },
    // {
    //   id: 3,
    //   name: '魅族账号',
    // },
    // {
    //   id: 4,
    //   name: '华为账号',
    // },
    // {
    //   id: 5,
    //   name: '测试类型',
    // },
    // {
    //   id: 6,
    //   name: '微信',
    // },
    // {
    //   id: 7,
    //   name: '微信+QQ',
    // },
  ])

  const loginMethodOptions = ref([
    // {
    //   id: 1,
    //   name: '小绵羊登录',
    // },
    // {
    //   id: 2,
    //   name: '魅族账号登录',
    // },
    // {
    //   id: 3,
    //   name: 'QQ账号登录',
    // },
    // {
    //   id: 4,
    //   name: '网易账号登录',
    // },
    // {
    //   id: 5,
    //   name: '微信授权登录',
    // },
    // {
    //   id: 6,
    //   name: '微信+QQ授权登录',
    // },
  ])
  
  
  const type = ref('')
  
  
  const page = ref(1)
  const total = ref(0)
  const pageSize = ref(10)
  const tableData = ref([])
  const searchInfo = ref({})
  
  const onReset = () => {
    searchInfo.value = {}
  }
  // 搜索
  
  const onSubmit = () => {
    page.value = 1
    pageSize.value = 10
    searchInfo.value.task_id = Number(searchInfo.value.task_id)
    getTableData()
  }
  
  // 分页
  const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
  }
  
  const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
  }
  
  // 排序
  const sortChange = ({ prop, order }) => {
    if (prop) {
      if (prop === 'id') {
        prop = 'id'
      }
      searchInfo.value.orderKey = toSQLLine(prop)
      searchInfo.value.desc = order === 'descending'
    }
    getTableData()
  }
  
  // 查询
  const getTableData = async() => {
    const table = await getGameTaskList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
    if (table.code === 0) {
      tableData.value = table.data.list
      total.value = table.data.total
      GamePortOptions.value = table.data.option.game_port
      loginMethodOptions.value = table.data.option.login_type
      accountTypeOptions.value = table.data.option.account_type
      links.value = table.data.option.game_list
      page.value = table.data.page
      pageSize.value = table.data.pageSize
    }
  }
  
  getTableData()
  
  // 批量操作
  const handleSelectionChange = (val) => {
    apis.value = val
  }
  
  const deleteVisible = ref(false)
  const onDelete = async() => {
    const ids = apis.value.map(item => item.id)
    console.log(ids)
    // const res = await deleteApisByIds({ ids })
    // if (res.code === 0) {
    //   ElMessage({
    //     type: 'success',
    //     message: res.msg
    //   })
    //   if (tableData.value.length === ids.length && page.value > 1) {
    //     page.value--
    //   }
    //   deleteVisible.value = false
    //   getTableData()
    // }
  }
  
  const onClose = async() => {
    const ids = apis.value.map(item => item.id)
    console.log(ids)
    const status = -1
    const res = await colsePc({ ids,status })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: res.msg
      })
      if (tableData.value.length === ids.length && page.value > 1) {
        page.value--
      }
      deleteVisible.value = false
      getTableData()
    }
  }
  
  const onOpen = async() => {
    const ids = apis.value.map(item => item.id)
    console.log(ids)
    const status = 1
    const res = await colsePc({ ids,status })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: res.msg
      })
      if (tableData.value.length === ids.length && page.value > 1) {
        page.value--
      }
      deleteVisible.value = false
      getTableData()
    }
  }
  
  // 弹窗相关
  const apiForm = ref(null)
  const initForm = () => {
    apiForm.value.resetFields()
    form.value = {
      task_id: '',
      task_name: '',
      user: '',
      new_retained: '1',
      game_name:'',
      date:'',
      game_port_id:'',
      account_type:'',
      login_method:'',
      tx_channel:'',
      tx_game_id:'',
      mz_channel:'',
      mz_game_id:'',
      game_id_xmy:'',
      new_target:'',
      pay_target:'',
      retained_target:'',
      pay_price:'',
    }
  }
  
  const dialogTitle = ref('新增')
  const dialogFormVisible = ref(false)
  const openDialog = (key) => {
    switch (key) {
      case 'addCard':
        dialogTitle.value = '新增'
        form.value.is_add = 1
        break
      case 'edit':
        dialogTitle.value = '编辑'
        form.value.is_add = 0
        break
      default:
        break
    }
    type.value = key
    dialogFormVisible.value = true
  }
  const closeDialog = () => {
    initForm()
    dialogFormVisible.value = false
  }
  
  const editCardFunc = async(row) => {
    const res = await getGameTaskById({ id: row.task_id })
    form.value = res.data
    openDialog('edit')
  }
  
  const enterDialog = async() => {
    apiForm.value.validate(async valid => {
      form.value.task_id = Number(form.value.task_id)
      form.value.new_target = Number(form.value.new_target)
      form.value.pay_price = Number(form.value.pay_price)
      form.value.pay_target = Number(form.value.pay_target)
      form.value.retained_target = Number(form.value.retained_target)
      form.value.new_target_h = Number(form.value.new_target_h)
      form.value.retained_target_h = Number(form.value.retained_target_h)
      if(form.value.new_target > form.value.new_target_h){
        ElMessage({
                  type: 'warning',
                  message: '新增目标下限不能大于上限',
                  showClose: false
                })
                return
      }
      if(form.value.retained_target > form.value.retained_target_h){
        ElMessage({
                  type: 'warning',
                  message: '活跃目标下限不能大于上限',
                  showClose: false
                })
                return
      }
      if (valid) {
        switch (type.value) {
          case 'addCard':
            {
              const res = await createGameTask(form.value)
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '添加成功',
                  showClose: true
                })
                getTableData()
                closeDialog()
              }
              
            }
  
            break
          case 'edit':
            {
              const res = await updateGameTask(form.value)
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '编辑成功',
                  showClose: true
                })
                getTableData()
                closeDialog()
              }
              
            }
            break
          default:
            // eslint-disable-next-line no-lone-blocks
            {
              ElMessage({
                type: 'error',
                message: '未知操作',
                showClose: true
              })
            }
            break
        }
      }
    })
  }
  
  const deleteApiFunc = async(row) => {
    ElMessageBox.confirm('此操作将永久删除所有角色下该api, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async() => {
        const res = await deleteGameTask(row)
        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功!'
          })
          if (tableData.value.length === 1 && page.value > 1) {
            page.value--
          }
          getTableData()
        }
      })
  }

  const switchEnable = async(row) => {
    const res = await statusOperation({task_id:row.task_id, status:row.status})
    if (res.code === 0) {
      ElMessage({ type: 'success', message: `${row.status === -1 ? '停止' : '开启'}成功` })
    }
}

const links = ref([])

const querySearch = (queryString, cb) => {
  const results = queryString
    ? links.value.filter(createFilter(queryString))
    : links.value
  // call callback function to return suggestion objects
  cb(results)
}
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}
// const loadAll = () => {
//   return [
//     { game_id: 1, game_name: '龙腾传世' },
//     { game_id: 2, game_name: '龙皇传说' },
//     { game_id: 3, game_name: '龙之国物语' },
//     { game_id: 4, game_name: '黑月' },
//     { game_id: 5, game_name: '麻将来了' },
//     { game_id: 6, game_name: '鸿途归来' },
//     { game_id: 7, game_name: '魔力宝贝归来' },
//   ]
// }
const handleSelect = (item) => {
  form.value.game_id = item.game_id
  console.log(item)
}

function changeTask(e) {
  form.value.game_name = e;
  form.value.game_id = item.game_id
}

const handleIconClick = (ev) => {
  console.log(ev)
}

// links.value = loadAll()
  
  </script>
  
  <style scoped lang="scss">
  .button-box {
    padding: 10px 20px;
    .el-button {
      float: right;
    }
  }
  :deep(.el-tabs__nav-scroll){
	width:35%;
	margin:0 auto
}
:deep(.el-tabs__nav-scroll)
  .warning {
    color: #dc143c;
  }
  </style>
  