<!--
 * @Author: fxs bjnsfxs@163.com
 * @Date: 2024-09-18
 * @LastEditors: fxs bjnsfxs@163.com
 * @LastEditTime: 2024-12-07
 * @Description: 
 * 
-->
<script setup lang="ts">
import type { ReqConfig } from '@/types/dataAnalysis'
import type { FormConfig, FormField } from '@/types/form'
import { FormFieldType } from '@/types/form'
import type { FormRules } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import type { DialogConfig } from '@/types/dialog'
import type { TableFieldInfo, TablePaginationSetting, TableToolsConfig } from '@/types/table'
import { FieldSpecialEffectType, TextType } from '@/types/tableText'
import { onUnmounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useRequest } from '@/hooks/useRequest'
import { useCommonStore } from '@/stores/useCommon'

import Form from '@/components/form/CustomForm.vue'
import Table from '@/components/table/CustomTable.vue'
import Dialog from '@/components/common/CustomDialog.vue'
import FileUpload from '@/components/form/FileUpload.vue'

import axiosInstance from '@/utils/axios/axiosInstance'
import router from '@/router'

const { selectInfo } = useCommonStore()
const { AllApi, analysisResCode } = useRequest()

defineEmits(['tableDataLoaded', 'upload'])

// 事件表单对象
const eventFormRef = ref()

// 参数表格ref对象
const optionTableRef = ref()

// 是否是新增触发
const isAdd = ref(true)

// 事件ID,这里的actionID，在获取事件详情的时候传入的字段是id字段，但是在获取
// 参数列表的时候，传入的是actionId字段
const actionId = ref()

// 编辑状态
const eventEditState = ref(false)

// 属性对话框
const attrDialog = ref()

// 上传ref
const uploadRef = ref<InstanceType<typeof FileUpload> | null>(null)

// 上传的信息
const uploadInfo = reactive({
  dialogTitle: '上传事件信息'
})

// 表单规则字段
const ruleForm = reactive({
  // actionId:"",
  actionName: '',
  status: 1,
  remark: ''
})

// 表单规则
const rules = reactive<FormRules<typeof ruleForm>>({
  actionName: [
    { required: true, message: '事件名称是必填项', trigger: 'blur' },
    { min: 5, max: 20, message: '事件名称长度必须在5到20之间', trigger: 'blur' }
  ],
  remark: [
    { required: false, message: '备注是可选项', trigger: 'blur' },
    { max: 100, message: '备注长度不能超过100个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '是否启用是必选项', trigger: 'change' },
    { type: 'number', message: '启用状态必须是数字', trigger: 'change' }
  ]
})

// 表单字段信息
const FormFields: Array<FormField> = [
  {
    name: 'actionName',
    cnName: '事件名',
    type: FormFieldType.INPUT
  },
  {
    name: 'status',
    cnName: '使用状态',
    type: FormFieldType.SELECT,
    otherOptions: {
      placeholder: '请选择状态',
      options: [
        {
          name: 'disabled',
          label: '禁用',
          value: 0
        },
        {
          name: 'able',
          label: '启用',
          value: 1
        }
      ]
    }
  },
  {
    name: 'remark',
    cnName: '备注',
    type: FormFieldType.RICHTEXT,
    otherOptions: {
      placeholder: '请输入备注'
    }
  }
]

// 表单请求参数
const formReq = reactive<ReqConfig>({
  url: AllApi.updateGameAction,
  otherOptions: {}
})

// 表单设置
const formConfig = reactive<FormConfig>({
  reqConfig: formReq,
  fieldsInfo: FormFields,
  rules
})

// 表格分页设置
const pageConfig = reactive<TablePaginationSetting>({
  limit: 20,
  currentPage: 1,
  total: 0,
  pageSizeList: [20, 30]
})

// 表格字段信息
const tableFieldConfig = reactive<Array<TableFieldInfo>>([
  {
    name: 'id',
    cnName: 'ID',
    isShow: true,
    needSort: true
  },
  {
    name: 'actionId',
    cnName: '事件ID',
    isShow: false,
    needSort: false
  },

  {
    name: 'optionId',
    cnName: '选项ID',
    isShow: true,
    needSort: false
  },
  {
    name: 'optionName',
    cnName: '选项名称',
    isShow: true,
    needSort: false
  },
  {
    name: 'optionType',
    cnName: '选项类型',
    isShow: true,
    needSort: false,
    specialEffect: {
      type: FieldSpecialEffectType.TEXT,
      otherInfo: {
        textType: TextType.TEXT,
        translateMap: {
          string: '字符串',
          int: '数字',
          array: '数组'
        }
      }
    }
  },
  {
    name: 'status',
    cnName: '使用状态状态',
    isShow: true,
    needSort: false,
    specialEffect: {
      type: FieldSpecialEffectType.TEXT,
      otherInfo: {
        textType: TextType.TEXT,
        translateMap: ['启用', '禁用']
      }
    }
  },
  {
    name: 'createdAt',
    cnName: '创建时间',
    isShow: true,
    needSort: false
  },
  {
    name: 'updatedAt',
    cnName: '更新时间',
    isShow: true,
    needSort: false
  }
])

// 表格请求配置
const tableReqConfig = reactive<ReqConfig>({
  url: AllApi.gameActionOptionList,
  otherOptions: {}
})

// 工具栏配置
const tableToolsConfig: TableToolsConfig = {
  add: true,
  filterFields: true,
  refresh: true,
  download: false
}

// 对话框请求参数
const dialogReqConfig = reactive<ReqConfig>({
  url: AllApi.addGameActionOption,
  otherOptions: {
    formData: {}
  }
})

// 对话框表单规则字段
const dialogRuleForm = reactive({
  optionName: '',
  optionId: '',
  status: 1,
  optionType: ''
})

// 表单规则
const dialogRules = reactive<FormRules<typeof dialogRuleForm>>({
  optionName: [{ required: true, message: '选项名称是必填项', trigger: 'change', type: 'string' }],
  optionId: [{ required: true, message: '选项ID是必填项', trigger: 'change', type: 'string' }],
  status: [{ required: true, message: '选项状态是必填项', trigger: 'change', type: 'number' }],
  optionType: [
    {
      required: true,
      message: '选项类型是必填项',
      trigger: 'change'
    }
  ]
})

// 表单字段信息
const dialogFormFields: Array<FormField> = [
  {
    name: 'optionId',
    cnName: '选项ID',
    type: FormFieldType.INPUT
  },
  {
    name: 'optionName',
    cnName: '选项名称',
    type: FormFieldType.INPUT
  },

  {
    name: 'status',
    cnName: '选项状态',
    type: FormFieldType.SELECT,
    defaultValue: 1,
    otherOptions: {
      placeholder: '请选择状态',
      options: [
        {
          name: 'disabled',
          label: '禁用',
          value: 0 // 对应int型状态
        },
        {
          name: 'able',
          label: '启用',
          value: 1 // 对应int型状态
        }
      ]
    }
  },
  {
    name: 'optionType',
    cnName: '选项类型',
    type: FormFieldType.SELECT,
    defaultValue: 'string',
    otherOptions: {
      placeholder: '请选择类型',
      options: [
        {
          name: 'string',
          label: '字符串',
          value: 'string'
        },
        {
          name: 'int',
          label: '整数',
          value: 'int'
        },
        {
          name: 'array',
          label: '数组',
          value: 'array'
        }
      ]
    }
  }
]

// 对话框设置
const dialogConfig = reactive<DialogConfig>({
  title: '自定义属性',
  reqConfig: dialogReqConfig,
  rules: dialogRules,
  fieldsInfo: dialogFormFields
})

/**
 *  获取事件详情
 * @param {*} id 这个id还是路由参数中query传过来的id
 */
const getEventInfo = (id: number) => {
  axiosInstance
    .post(AllApi.gameActionDetail, { id })
    .then((data: any) => {
      analysisResCode(data, '请求', true).then((info) => {
        let result = info.data
        let updateEventField = {
          gid: '',
          actionId: '',
          actionName: '',
          remark: '',
          status: 1
        }
        eventFormRef.value.fillForm(Object.assign(updateEventField, { ...result }))
      })
    })
    .catch((err) => {
      console.log(err)
    })
}

// 新增属性
const addNewAttr = () => {
  attrDialog.value.addForm()
}

// 改变编辑状态
const changeEditState = (state: boolean) => {
  eventEditState.value = state
}

/**
 * 取消编辑,同时把数据恢复
 */
const cancelEdit = () => {
  changeEditState(false)

  eventFormRef.value.clearValid()
  eventFormRef.value.resumeFormData()
}

/**
 * 保存编辑，提交表单,只有表单验证通过了才能更改编辑状态
 */
const saveEdit = () => {
  eventFormRef.value
    .submitFormData()
    .then(() => {
      changeEditState(false)
    })
    .catch((err: any) => {
      console.log(err)
    })
}

/**
 * 开始编辑，备份一份现有的表单数据
 */
const startEdit = () => {
  changeEditState(true)
  eventFormRef.value.backupFormData()
}

/**
 * 接受到表单提交事件后，需要去重新请求一下表格的数据
 */
const formSub = () => {
  optionTableRef.value.getData()
}

/**
 * 修改选项
 */
const editOption = (row: any) => {
  attrDialog.value.editForm(row, AllApi.updateGameActionOption)
}

/**
 * 删除选项
 */
const delOption = (row: any) => {
  ElMessageBox.confirm('确认删除该配置吗', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      optionTableRef.value.deleteRow(AllApi.deleteGameActionOption, { id: row.id })
    })
    .catch(() => {})
}

/**
 *  初始化参数
 *  加载时如果有actionId，则代表是修改页面，需要去请求数据，没有则是新增页面
 * 这里的actionId，是返回参数中id、actionID中的前者，在这个页面会被用于请求事件详情和相关的参数列表
 * 在请求的时候，他们的名字不同，但传入的都是这个id
 */
const initParams = () => {
  const routes = useRoute()
  let query_actionId = routes.query.id as string
  console.log(query_actionId)
  if (query_actionId) {
    isAdd.value = false
    actionId.value = parseInt(query_actionId)
    getEventInfo(parseInt(actionId.value))
    tableReqConfig.otherOptions.actionId = actionId.value
    dialogReqConfig.otherOptions.formData.actionId = actionId.value
  }
}

// 初始化参数
initParams()

const watchGid = watch(
  () => selectInfo.gid,
  () => {
    router.replace({ name: 'EventManage' })
  }
)

onUnmounted(() => {
  watchGid()
})
</script>

<template>
  <div class="eventDetail">
    <div class="header">
      <span>基本信息</span>
      <div class="headerBtn">
        <span v-if="eventEditState">
          <el-button class="handleBtn" @click="cancelEdit" color="#626aef" plain>取消</el-button>
          <el-button class="handleBtn" @click="saveEdit" color="#626aef">保存</el-button>
        </span>
        <span v-else>
          <el-button class="handleBtn" @click="startEdit" color="#626aef">编辑</el-button>
        </span>
      </div>
    </div>
  </div>
  <div class="eventForm">
    <div class="formBody">
      <Form
        :disabled="eventEditState"
        ref="eventFormRef"
        :inline="true"
        :config="formConfig"
      ></Form>
    </div>
  </div>
  <div class="attrList">
    <div class="header">
      <span>属性列表</span>
    </div>
    <div class="list">
      <Table
        :tools="tableToolsConfig"
        :open-page-query="true"
        :open-filter-query="false"
        :pagination-config="pageConfig"
        :table-fields-info="tableFieldConfig"
        :request-config="tableReqConfig"
        @add-new-item="addNewAttr"
        ref="optionTableRef"
      >
        <template #tableOperation>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button
                size="small"
                color="#626aef"
                @click="editOption(scope.row)"
                class="operationBtn"
              >
                修改
              </el-button>

              <el-button
                size="small"
                color="#EF5A6F"
                @click="delOption(scope.row)"
                class="operationBtn"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </Table>
    </div>
  </div>
  <div class="addAttrDialog">
    <Dialog ref="attrDialog" :config="dialogConfig" @form-submit="formSub"></Dialog>
  </div>
  <div class="uploadFileBox">
    <FileUpload ref="uploadRef" :title="uploadInfo.dialogTitle"></FileUpload>
  </div>
</template>

<style scoped>
.eventDetail,
.eventForm,
.attrList {
  width: 98%;
  margin: 0 auto;
  background-color: white;
  box-sizing: border-box;
}

.header {
  width: 100%;
  box-sizing: border-box;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
  box-shadow: inset 0 -1px 0 0 rgba(23, 35, 61, 0.1);
  font-weight: 600;
  font-size: 14px;
  color: #17233d;
  padding: 12px 24px;
}

.headerBtn {
  box-sizing: border-box;
}

.handleBtn {
  margin-right: 15px;
}

.eventForm {
  padding: 24px;
}

.formBody {
  width: 45%;
}

.operationBtn {
  cursor: pointer;
  margin-right: 5px;
  color: white;
}
</style>
