<template>
  <div class="mould-fee table_form-container">
    <header>
      <div class="header-actions">
        <el-button type="primary" @click="addFee" v-auth="'feeHandl_createFeeSetting'">添加模板</el-button>
        <el-button type="primary" @click="editFee" v-auth="'feeHandl_editFeeSetting'">编辑模板</el-button>
        <el-button type="primary" @click="changeStatus(1)" v-auth="'feeHandl_editFeeSetting'">启用模板</el-button>
        <el-button type="danger" @click="changeStatus(2)" v-auth="'feeHandl_editFeeSetting'">禁用模板</el-button>
        <el-button type="primary" @click="editFeeDetail" v-auth="'feeHandl_setFeeSettingDetail'">编辑模板详情</el-button>
      </div>
    </header>
    <div class="table-container">
      <div class="table-container-left">
        <Table ref="singleTableRef" :show-column-setting="false" :table-data="tableData"  :columns="tableColumns" row-key="id" :loading="loading"
          :highlight-current-row="true" @current-change="handleCurrentChange" />
      </div>
      <div class="table-container-right">
        <Table :show-column-setting="false" row-key="id" :table-data="tableDataDetail" :columns="tableColumnsDetail" :loading="detailLoading" />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogTitleType === 1 ? '添加手续费模板' : '编辑手续费模板'" width="500">
      <Form :formItems="formItems" :formRules="formRules" :formData="formData" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submit">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="detaildialogVisible" title="编辑手续费模板详情" width="700">
      <el-table height="600px" :data="tableDataDetail">
        <template v-for="column in tableColumnsDetail" :key="column.prop">
          <el-table-column v-if="column.prop === 'fee'" :prop="column.prop" :label="column.label">
            <template #default="scope">
              <el-input-number :min="0" :max="999999999" :controls="false" v-model="scope.row.fee" />
            </template>
          </el-table-column>
          <el-table-column v-else :prop="column.prop" :label="column.label" />
        </template>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detaildialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitDetailLoading" @click="submitDetail">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">

defineOptions({
  name: 'HandleFee'
})

import { ref, onMounted } from 'vue'
import { usePageLoading, useButtonLoading } from '@/composables/useLoading'
import {
  getFeeSettingList,
  getFeeSettingDetail,
  createFeeSetting,
  editFeeSetting,
  setFeeSettingDetail,
} from '@/api/modules/mould/handleFee.ts'
import Form from '@/components/common/Form.vue'
import Table from '@/components/common/Table.vue'
import { formDataList, formRulesList } from './option.ts'

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitleType = ref(1)

// 表单相关
const formData = ref({
  name: '',
  status: 1,
  type: 2,
  description: '',
})
const formItems = formDataList
const formRules = formRulesList

// 详情弹窗相关
const detaildialogVisible = ref(false)

// 加载状态
const { loading, startLoading, stopLoading } = usePageLoading()
const { buttonLoading: detailLoading, startButtonLoading: startDetailLoading, stopButtonLoading: stopDetailLoading } = useButtonLoading()
const { buttonLoading: submitLoading, startButtonLoading: startSubmitLoading, stopButtonLoading: stopSubmitLoading } = useButtonLoading()
const { buttonLoading: submitDetailLoading, startButtonLoading: startSubmitDetailLoading, stopButtonLoading: stopSubmitDetailLoading } = useButtonLoading()

// 主表格相关
const tableData = ref<any[]>([])
const tableColumns = [
  { prop: 'name', label: '名称' },
  { prop: 'type', label: '状态' },
]
const currentRow = ref<Record<string, any>>({})
const singleTableRef = ref()

// 重置表单数据
const resetFormData = () => {
  formData.value = {
    name: '',
    status: 1,
    type: 2,
    description: '',
  }
}

// 设置当前选中行
const setCurrent = (row: any) => {
  singleTableRef.value?.setCurrentRow(row)
}

// 主表格行选中变化
const handleCurrentChange = (row: any) => {
  currentRow.value = row
  fetchItemDetail(row.id)
}

// 详情表格相关
const tableDataDetail = ref<any[]>([])
const tableColumnsDetail = [
  { prop: 'name', label: '品种' },
  { prop: 'code', label: '编号' },
  { prop: 'fee', label: '开仓手续费' },
]

// 获取主表格数据
const getTableData = async () => {
  startLoading()
  try {
    const res = await getFeeSettingList()
    tableData.value = Array.isArray(res) ? res : []
    handleTableDataAfterLoad()
  } finally {
    stopLoading()
  }
}

// 处理表格数据加载后的逻辑
const handleTableDataAfterLoad = () => {
  const savedId = currentRow.value?.id

  if (tableData.value.length === 0) {
    tableDataDetail.value = []
    return
  }

  const targetRow = savedId ? tableData.value.find((item) => item.id === savedId) : null
  const rowToSelect = targetRow || tableData.value[0]

  setCurrent(rowToSelect)
  handleCurrentChange(rowToSelect)
}

// 获取详情数据
const fetchItemDetail = async (id: number) => {
  startDetailLoading();
  try {
    const res = await getFeeSettingDetail({ id })
    tableDataDetail.value = res || []
  } finally {
    stopDetailLoading();
  }
}

// 打开添加弹窗
const addFee = () => {
  dialogVisible.value = true
  dialogTitleType.value = 1
  resetFormData()
}

// 打开编辑弹窗
const editFee = () => {
  dialogVisible.value = true
  dialogTitleType.value = 2
  formData.value = {
    id: currentRow.value.id,
    name: currentRow.value.name,
    type: currentRow.value.type,
    description: currentRow.value.description,
  }
}

// 切换模板状态
const changeStatus = (status: number) => {
  dialogTitleType.value = 2
  formData.value = {
    id: currentRow.value.id,
    name: currentRow.value.name,
    type: currentRow.value.type,
    description: currentRow.value.description,
    status,
  }
  submit()
}

// 提交主表单
const submit = async () => {
  startSubmitLoading();
  try {
    if (dialogTitleType.value === 1) {
      await createFeeSetting(formData.value)
    } else {
      await editFeeSetting(formData.value)
    }
    resetFormData()
    dialogVisible.value = false
    getTableData()
  } finally {
    stopSubmitLoading();
  }
}

// 打开编辑详情弹窗
const editFeeDetail = () => {
  detaildialogVisible.value = true
}

// 提交详情表单
const submitDetail = async () => {
  startSubmitDetailLoading();
  try {
    const contentsJson: Record<string, any> = {}

    tableDataDetail.value.forEach((item) => {
      contentsJson[item.variety_id] = item.fee
    })

    await setFeeSettingDetail({
      id: currentRow.value.id,
      contents_json: JSON.stringify(contentsJson),
    })

    detaildialogVisible.value = false
    getTableData()
  } finally {
    stopSubmitDetailLoading();
  }
}

onMounted(() => {
  getTableData()
})
</script>

<style scoped lang="scss">
.mould-fee {
  // height: 100%;
  // overflow: hidden;
}

header {
  margin-bottom: 8px;
}

.table-container {
  display: flex;
  column-gap: 20px;
  height: calc(100% - 40px);

  .table-container-left {
    width: 300px;
    height: 100%;
    flex: 0 0 auto;
    overflow: hidden;
  }

  .table-container-right {
    flex: 1;
    height: 100%;
    overflow: hidden;
  }
}
</style>

