<template>
  <div class="app-container" ref="appContainer">
    <ServerPropTable :loading="loading" @selection-change="selectionChange" :columns="column" :data="list" @reset="reset"
      @onSubmit="onSubmit" @onUpdate="onUpdate">
      <template v-slot:btn>
        <div style="display: flex; justify-content: flex-end">
          <el-button type="danger" @click="batchDelete"><el-icon>
              <delete />
            </el-icon>删除</el-button>
        </div>
      </template>
      <template v-slot:state="scope">{{getStateLabel(scope.row.state)}}</template>
      <template v-slot:openTime="scope">{{getDate(scope.row.openTime)}}</template>
      <template v-slot:operation="scope">
        <el-button type="primary" size="small" icon="Edit" @click="edit(scope.row)">
          编辑
        </el-button>
        <el-button @click="del(scope.row)" type="danger" size="small" icon="Delete">
          删除
        </el-button>
      </template>
    </ServerPropTable>

    <el-dialog v-model="dialogVisible" :title='title' width="50%">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
        :size="formSize">
        <el-form-item label="ID" prop="_id">
          <el-input readonly :value="ruleForm._id" />
        </el-form-item>
        <el-form-item label="推荐权重" prop="weight">
          <el-input v-model="ruleForm.weight" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="ruleForm.state">
            <el-radio :label="0">关闭</el-radio>
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="2">开放</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开服时间" prop="openTime">
          <el-date-picker
                    v-model="ruleForm.openTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    clearable
                />

          <!-- <el-input v-model="ruleForm.openTime" /> -->
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleClose(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup name="comprehensive">
import { ref, reactive, onMounted, nextTick, onBeforeMount } from 'vue'
import * as dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import serverApi from '@/api/server'

const loading = ref(true)
const appContainer = ref(null)
import ServerPropTable from '@/components/Table/ServerPropTable/index.vue'
// const data = []
// for (let i = 0; i < 100; i++) {
//   data.push({
//     _id: i + 1,
//     name: 'S' + i,
//     gmAddr: '127.0.0.1:2002',
//     weight: 100 + i,
//     gatewayId: 1,
//     state: i % 3,
//     openTime: '2023-08-17 10:00:00'
//   })
// }

const data = ref([])
const serverName = "game"

// 时间戳转日期
const getDate = (val) => {
  if (!val) {
    return ""
  }
  let now = new Date(val),
    y = now.getFullYear(),
    m = now.getMonth() + 1,
    d = now.getDate()
  return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
}

onBeforeMount(() => {
  loadServerInfo()
})

const loadServerInfo = () => {
  serverApi.getAll(serverName).then(res => {
    data.value = res.data.result;
    console.log(data)
  })
}

const column = [
  { type: 'selection', width: 60, fixed: 'left' },
  { name: '_id', label: 'ID', inSearch: true, valueType: 'inputNumber', width: 80 },
  { name: 'name', label: '名称'},
  { name: 'gmAddr', label: 'GM地址'},
  { name: 'weight', label: '推荐权重', inSearch: true, valueType: 'inputNumber'},
  { name: 'gatewayId', label: '连接网关服'},
  {
    name: 'state',
    label: '状态',
    slot: true,
    inSearch: true,
    options: [
      {
        value: 0,
        label: '关闭',
      },
      {
        value: 1,
        label: '开启',
      },
      {
        value: 2,
        label: '开放',
      }
    ],
    valueType: 'select',
  },
  { name: 'openTime', label: '开服时间', inSearch: true, valueType: 'datetime'},
  { name: 'operation', slot: true, fixed: 'right', width: 200, label: '操作' },
]

const getStateLabel = (val) => {
  if (val == 0) {
    return '关闭'
  } else if (val == 1) {
    return '开启'
  } else if (val == 2) {
    return '开放'
  }
}

const list = ref(data)

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  _id:null,
  weight: 0,
  state: null,
  openTime: null
})

const rules = reactive({
  state: [
    {
      required: true,
      message: '请选择状态',
      trigger: 'change',
    },
  ],
})

const dialogVisible = ref(false)
const rowObj = ref({})
const selectObj = ref([])
const title = ref('编辑')

const handleClose = async (done: () => void) => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      list.value.forEach((item) => {
          let updateParams = reactive({
            serverName: serverName,
            _id: ruleForm._id,
            updateValue: ruleForm
          })
          serverApi.update(updateParams).then(res=>{
            if (res.data.code = 200) {
                loadServerInfo()
                return ElMessage.success('修改成功')
              } else {
                return ElMessage.error('修改失败')
              }
          })
      })
      dialogVisible.value = false
      console.log('submit!', ruleForm.weight, ruleForm.state)
    } else {
      console.log('error submit!', fields)
    }
  })
}

const batchDelete = () => {
  if (!selectObj.value.length) {
    return ElMessage.error('未选中任何行')
  }
  ElMessageBox.confirm('你确定要删除选中项吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  })
    .then(() => {
      let selectServerIds = reactive([])
      for (let value of selectObj.value) {
        selectServerIds.push(value._id)
      }
      let deleteParams = reactive({
        serverName: serverName,
        serverIds: selectServerIds
      })
      serverApi.deleteBatch(deleteParams).then(res => {
        loadServerInfo()
        ElMessage.success('批量删除成功')
      })
      list.value = list.value.concat([])
    })
    .catch(() => { })
}
const selectionChange = (val) => {
  selectObj.value = val
}

const edit = (row) => {
  rowObj.value = row
  dialogVisible.value = true
  ruleForm._id = row._id
  ruleForm.weight = row.weight
  ruleForm.state = row.state
  ruleForm.openTime = getDate(row.openTime)
}

const del = (row) => {
  console.log('row==', row)
  ElMessageBox.confirm('你确定要删除当前项吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  })
    .then(() => {
      // list.value = list.value.filter((item) => item._id !== row._id)
      let deleteParams = reactive({
        serverName: serverName,
        serverId: row._id
      })
      serverApi.delete(deleteParams).then(res => {
        loadServerInfo()
        ElMessage.success('删除成功')
      })
      loading.value = true
      setTimeout(() => {
        loading.value = false
      }, 500)
    })
    .catch(() => { })
}

const reset = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
  ElMessage.success('重置成功')
}

const onSubmit = (val) => {
  if (!val._id && val.state == null && !val.weight) {
    ElMessage.warning('请输入查询条件')
    return
  }
  let queryParams = reactive({
    serverName: serverName
  })
  if (val._id) {
    queryParams._id = parseInt(val._id)
  }
  if (val.state != null) {
    queryParams.state = val.state
  }
  if (!val.weight) {
    queryParams.weight = val.weight
  }
  serverApi.query(queryParams).then(res => {
    data.value = res.data.result;
    console.log(data.value)
  })
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const onUpdate = (val) => {
  if (val.state == null && !val.weight && !val.openTime) {
    ElMessage.warning('请输入编辑内容')
    return
  }
  let updateParams = reactive({
    serverName: serverName,
    updateValue: reactive({})
  })
  if (val._id) {
    updateParams._id = parseInt(val._id)
  }
  if (val.state != null) {
    updateParams.updateValue.state = val.stage
  }
  if (!val.weight) {
    updateParams.updateValue.weight = val.weight
  }
  if (!val.openTime) {
    updateParams.updateValue.openTime = val.openTime.getTime()
  }
  serverApi.updateBatch(updateParams).then(res => {
    if (res.data.code = 200) {
      loadServerInfo()
      return ElMessage.success('修改成功')
    } else {
      return ElMessage.error('修改失败')
    }
  })
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const getHeight = () => {

}

onMounted(() => {
  nextTick(() => {
    // let data = appContainer.value.
  })
  setTimeout(() => {
    loading.value = false
  }, 500)
})
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}

.app-container {
  flex: 1;
  display: flex;
  width: 100%;
  padding: 16px;
  box-sizing: border-box;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
