<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.game_port_id" placeholder="请选择" style="width:100%">
                  <el-option
                    v-for="item in GamePortOptions"
                    :key="item.id"
                    :label="`${item.name}`"
                    :value="item.id"
                  />
                </el-select>
          </el-form-item>
          
          <el-form-item label="状态">
          <el-select v-model="searchInfo.is_complete" 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 label="日期" prop="date">
            <el-date-picker
              v-model="searchInfo.date"
              size="default"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :disabled-date="disabledDate"
              :shortcuts="shortcuts"
            />
          </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-button class="excel-btn" size="small" type="primary" icon="download" @click="handleExcelExport">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="gva-table-box">
        
        <el-table :data="tableData" border @sort-change="sortChange" @selection-change="handleSelectionChange" style="width: 100%">
          <el-table-column label="任务ID" width="70" prop="task_id" sortable="custom" />
          <el-table-column label="任务日期" min-width="100" prop="create_date" />
          <el-table-column label="任务名称" width="130" prop="task_name" sortable="custom" />
          <el-table-column label="负责人" width="75" prop="user" sortable="custom" />
          <el-table-column label="登录方式" width="75" prop="login_method" />
          <el-table-column label="新增目标" width="75" prop="new_target" />
          <el-table-column  label="新增完成" width="75" prop="new_complete" />
          <el-table-column  label="剩余新增" width="75" prop="new_target1">
            <template #default="scope">
              {{ scope.row.new_target <= scope.row.new_complete  ? 0 : scope.row.new_complete-scope.row.new_target}}
            </template>
          </el-table-column>
          <el-table-column  label="留存目标" width="75" prop="retained_target" />
          <el-table-column label="留存完成" width="75" prop="retained_complete" />
          <el-table-column label="剩余留存" width="75" prop="retained_target1">
            <template #default="scope">
              {{ scope.row.retained_target <= scope.row.retained_complete  ? 0 : scope.row.retained_complete-scope.row.retained_target}}
            </template>
          </el-table-column>
          <el-table-column  label="付费目标" width="75" prop="pay_target" />
          <el-table-column label="付费完成" width="75" prop="pay_complete" />
          <el-table-column label="剩余付费" width="75" prop="pay_target1">
            <template #default="scope">
              {{ scope.row.pay_target <= scope.row.pay_complete  ? 0 : scope.row.pay_complete-scope.row.pay_target}}
            </template>
          </el-table-column>
          <el-table-column label="付费流水" width="75" prop="amount"/>
          <el-table-column label="群控效率" width="75" prop="game_rate"/>
          <el-table-column label="手动新增" width="75" prop="hand_new_complete"/>
          <el-table-column label="手动留存" width="75" prop="hand_retained_complete"/>
          <el-table-column label="手动付费" width="75" prop="hand_pay_complete"/>
          <el-table-column label="手动付费金额" width="75" prop="hand_amount_total"/>
          <el-table-column fixed="right" align="right" label="是否完成" width="75" prop="is_complete" >
          <template #default="scope">
            <div>
              <el-tag :type="scope.row.is_complete === -1 ? 'warning' : 'success'">{{ statusFiletr(scope.row.is_complete) }}</el-tag>
            </div>
          </template>
        </el-table-column>
          <el-table-column fixed="right" label="操作" width="160">
            <template #default="scope">
              <el-button
                icon="edit"
                size="small"
                type="primary"
                link
                @click="editCardFunc(scope.row)"
              >编辑</el-button>
              <el-button
                icon="edit"
                size="small"
                type="primary"
                link
                @click="resetFeeFunc(scope.row)"
              >重置付费</el-button>
              <el-button
                icon="edit"
                size="small"
                type="primary"
                link
                @click="accountListFunc(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" :disabled="true"/>
          </el-form-item>
          <el-form-item label="负责人" prop="user" >
            <el-input v-model="form.user" autocomplete="off" :disabled="true"/>
          </el-form-item>
          <el-form-item label="任务日期" prop="create_date" >
            <el-input v-model="form.create_date" autocomplete="off" :disabled="true"/>
          </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" :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="pay_target">
                <el-input v-model="form.pay_target" autocomplete="off"/>
              </el-form-item>
              <el-form-item label="留存目标" prop="retained_target" >
                <el-input v-model="form.retained_target" autocomplete="off"/>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="手动完成数据">
              <el-form ref="apiForm" :model="form" :rules="rules" label-width="80px" :inline="true">
                <el-form-item  label="新增个数" prop="hand_new_complete">
                <el-input v-model="form.hand_new_complete" autocomplete="off" />
              </el-form-item>
              <el-form-item label="留存个数" prop="hand_retained_complete" >
                <el-input v-model="form.hand_retained_complete" autocomplete="off"/>
              </el-form-item>
              <el-form-item label="是否付费">
                <el-radio-group v-model="form.is_free">
                  <el-radio border label="1">有付费</el-radio>
                  <el-radio border label="-1">没有付费</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="支付方式" prop="free_method" v-if="(form.is_free == 1)">
                <el-select v-model="form.free_method" placeholder="请选择" style="width:100%">
                  <el-option
                    v-for="item in FreeMethodOptions"
                    :key="item.id"
                    :label="`${item.name}`"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <el-form ref="apiForm" :model="form" :rules="rules" label-width="100px" :inline="true">
              <el-form-item label="手动付费个数" prop="hand_pay_complete" v-if="(form.is_free == 1)">
                <el-input v-model="form.hand_pay_complete" autocomplete="off"/>
              </el-form-item>
              <el-form-item label="付费总金额" prop="hand_amount_total" v-if="(form.is_free == 1)">
                <el-input v-model="form.hand_amount_total" autocomplete="off"/>
              </el-form-item>
            </el-form>
            <div v-if="(form.is_free == 1 && form.free_method == 1)" style="margin-bottom: 10px;">
              <el-button
                style="margin-top:12px"
                size="small"
                type="primary"
                icon="edit"
                @click="addBtn(form)"
              >添加卡号</el-button>
              <el-table :data="form.card_list" style="width: 100%">
                <el-table-column align="left" prop="card" label="卡号" width="180">
                  <template #default="scope">
                    <div>
                      <el-input v-model="scope.row.card" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column align="left" prop="amount" label="消费金额" width="180">
                  <template #default="scope">
                    <div>
                      <el-input-number v-model="scope.row.amount" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column align="left">
                  <template #default="scope">
                    <div>
                      <el-button
                        type="danger"
                        size="small"
                        icon="delete"
                        @click="deleteBtn(form.card_list,scope.$index)"
                      >删除</el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-form ref="apiForm" :model="form" :rules="rules" label-width="100px" :inline="true">
              <el-form-item label="上传机房" prop="is_upload_xjf">
                <el-radio-group v-model="form.is_upload_xjf">
                  <el-radio border label="1">是</el-radio>
                  <el-radio border label="-1">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="上传WT" prop="is_upload_wt" >
                <el-radio-group v-model="form.is_upload_wt">
                  <el-radio border label="1">是</el-radio>
                  <el-radio border label="-1">否</el-radio>
                </el-radio-group>
              </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>
      <el-dialog v-model="accountFormVisible" :before-close="closeAccount" :title="accountTitle">
        <el-table :data="tableData1">
          <el-table-column align="left" label="账号" show-overflow-tooltip min-width="160" prop="account" />
          <el-table-column align="left" label="密码" show-overflow-tooltip min-width="160" prop="password" />
        </el-table>
        <template #footer>
          <div class="dialog-footer">
            <el-button size="small" @click="closeAccount">取 消</el-button>
          </div>
        </template>
    </el-dialog>
    </div>
  </template>
  
  <script>
  export default {
    name: 'TargetTask',
  }
  </script>
  
  <script setup>
  import {
    getGameTaskTargetById,
    updateGameTaskTarget,
    getGameTaskTargetList,
    taskResetFee,
    getFeeAccountList,
    taskTargetExport
  } from '@/api/task'
  import {
    selectResponsiblePerson,
} from '@/api/responsiblePerson'
  import { toSQLLine } from '@/utils/stringFun'
  import warningBar from '@/components/warningBar/warningBar.vue'
  import { ref } from 'vue'
  import dayjs from "dayjs";
  import { ElMessage, ElMessageBox } from 'element-plus'

  const statusFiletr = (value) => {
  const target = statusOptions.value.filter(item => item.value === value)[0]
  return target && `${target.label}`
}

  const statusOptions = ref([
  {
    value: -1,
    label: '否',
    type: 'wain'
  },
  {
    value: 1,
    label: '是',
    type: 'success'
  },
])

const ResponsiblePerson = ref([])
  
  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' }
    ],
    pay_target: [
      { required: true, message: '请输入付费目标', trigger: 'blur' }
    ],
    retained_target: [
      { required: true, message: '请输入留存目标', trigger: 'blur' }
    ],
    retained_target: [
      { 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:'',
    free:-1
  })
  const GamePortOptions = ref([
    {
      id: 1,
      name: '腾讯游戏',
    },
    {
      id: 2,
      name: '360游戏',
    },
    {
      id: 3,
      name: '网易游戏',
    },
    {
      id: 4,
      name: '酷派游戏',
    },
    {
      id: 5,
      name: '魅族游戏',
    },
  ])

  const searchStatusOptions = ref([
 {
    value: -1,
    label: '未完成',
    type: 'wain'
  },
  {
    value: 1,
    label: '已完成',
    type: 'success'
  },
])

  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 FreeMethodOptions = ref([
    {
      id: 1,
      name: 'QQ卡',
    },
    {
      id: 2,
      name: '微信',
    },
    {
      id: 3,
      name: '支付宝',
    },
    {
      id: 4,
      name: '银行卡',
    },
  ])
  // 新增可控按钮
const addBtn = (form) => {
  if (!form.card_list) {
    form.card_list = []
  }
  form.card_list.push({
    card: '',
    amount: 0
  })
}
// 删除可控按钮
const deleteBtn = async(btns, index) => {
  const btn = btns[index]
  if (btn.ID === 0) {
    btns.splice(index, 1)
    return
  }
  btns.splice(index, 1)

}
  
  const type = ref('')
  
  
  const page = ref(1)
  const total = ref(0)
  const pageSize = ref(10)
  const tableData = ref([])
  const tableData1 = 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)
    if (typeof searchInfo.value.date != "undefined") {
      searchInfo.value.date[0] = dayjs(searchInfo.value.date[0]).format(
        "YYYY-MM-DD"
      );
      searchInfo.value.date[1] = dayjs(searchInfo.value.date[1]).format(
        "YYYY-MM-DD"
      );
  }
    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 getGameTaskTargetList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
    if (table.code === 0) {
      tableData.value = table.data.list
      total.value = table.data.total
      page.value = table.data.page
      pageSize.value = table.data.pageSize
    }
  }
  
  getTableData()

  
  const getResponsiblePerson = async() => {
    const table = await selectResponsiblePerson()
    if (table.code === 0) {
      ResponsiblePerson.value = table.data
    }
  }
  getResponsiblePerson()
  // 批量操作
  const handleSelectionChange = (val) => {
    apis.value = val
  }

  const handleExcelExport = async() => {
    var fileName = Date.parse(new Date()) + "-task.xlsx"
    if(searchInfo.value.create_date == null){
      let dt = new Date()
            var y = dt.getFullYear()
            var mt = (dt.getMonth() + 1).toString().padStart(2,'0')
            var day = dt.getDate().toString().padStart(2,'0')
            var timeStr = y + "-" + mt + "-" + day
      fileName = timeStr + "-task.xlsx"
    }else{
      fileName = searchInfo.value.create_date + "-task.xlsx"
    }
    taskTargetExport({ page: page.value, pageSize: pageSize.value, ...searchInfo.value },fileName)
}

  const shortcuts = [
  {
    text: "今日",
    value: () => {
      const end = new Date();
      const start = new Date();
      return [start, end];
    },
  },
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
];
  
  const deleteVisible = ref(false)
  
  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 accountFormVisible = 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 closeAccount = () => {
    accountFormVisible.value = false
  }
  
  const editCardFunc = async(row) => {
    const res = await getGameTaskTargetById({ id: row.task_id, create_date:row.create_date })
    if (res.code === 0) {
      form.value = res.data
      openDialog('edit')
    }
  }

  const accountListFunc = async(row) => {
    const res = await getFeeAccountList({ id: row.task_id, create_date:row.create_date })
    if (res.code === 0) {
      tableData1.value = res.data
      dialogTitle.value = '可付费账号'
      accountFormVisible.value = true
    }
  }
  
  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.hand_new_complete = Number(form.value.hand_new_complete)
      form.value.hand_retained_complete = Number(form.value.hand_retained_complete)
      form.value.hand_pay_complete = Number(form.value.hand_pay_complete)
      form.value.hand_amount_total = Number(form.value.hand_amount_total)
      form.value.is_free = Number(form.value.is_free)
      form.value.free_method = Number(form.value.free_method)
      form.value.is_upload_xjf = Number(form.value.is_upload_xjf)
      form.value.is_upload_wt = Number(form.value.is_upload_wt)
      if (valid) {
        switch (type.value) {
          case 'edit':
            {
              const res = await updateGameTaskTarget(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 resetFeeFunc = async(row) => {
    ElMessageBox.confirm('此操作将重置付费, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async() => {
        const res = await taskResetFee(row)
        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '重置成功!'
          })
          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)
}

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>
  