<template>
    <div class="variety">
        <!-- 搜索 -->
        <VarietySearch :search-form="searchForm" :search-options="searchOptions" @search="handleSearch"
            @reset="handleReset">
            <template #button="{ form }">
                <el-button type="primary" :disabled="!selectedRow" @click="handleEdit()">
                    编辑
                </el-button>
                <el-button type="primary" @click="handleAdd()">
                    添加
                </el-button>
            </template>
        </VarietySearch>

        <!-- 表格 -->
        <VarietyTable :table-data="varietyTree" :columns="varietyTableColumnsOptions" row-key="id"
            @row-click="handleRowClick">
            <template #onlineStatus="{ row }">
                <el-switch :model-value="row.onlineStatus === 1" :active-value="true" :inactive-value="false" />
            </template>
            <template #tradeStatus="{ row }">
                <el-switch :model-value="row.status === 1" :active-value="true" :inactive-value="false" />
            </template>
        </VarietyTable>
    </div>
    <!-- dialog -->
    <VarietyDialog :visible="dialogVisible" :title="dialogTitle" :type="dialogType" @confirm="handleSubmit"
        @cancel="handleCancel" @close="handleClose">
        <VarietyForm :form-data="varietyForm" :form-rules="varietyFormRules" :form-items="dialogFormItemOptions"
            :options-map="varietyFormOptionsMap" :row-gutter="rowGutter" :col-span="colSpan" ref="varietyFormRef">
        </VarietyForm>
    </VarietyDialog>
    <!-- dialog表格 -->

</template>

<script setup lang="ts">
// 组件
import VarietySearch from '@/components/common/Search.vue'
import VarietyTable from '@/components/common/Table.vue'
import VarietyDialog from '@/components/common/Dialog.vue'
import VarietyForm from '@/components/common/Form.vue'

// 配置以及表单验证
import { search, tableColumns, editDialogFormItem } from './options'
import { rules } from './rules'

// 接口
import { getVarietyListApi, getTradeGroupListApi, editVarietyApi, createVarietyApi } from '@/api/modules/trade/variety'

/**
 * @description: 定义搜索数据
 */
const searchForm = ref({
    varietyName: '',
})
const searchOptions = ref(search)

/**
 * @description: 定义表格数据
 */
const varietyTree = ref([])
const varietyTableColumnsOptions = ref(tableColumns)

/**
 * @description: 定义弹窗数据
 */
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref('')

/**
 * @description: 定义弹窗表单数据
 */
const varietyForm = ref({
    // 品种名称
    varietyName: '',
    // 品种代码
    varietyCode: '',
    // 线上状态
    onlineStatus: 1,
    // 交易状态
    tradeStatus: 1,
    // 最小点差
    minPoint: '',
    // 最大点差
    maxPoint: '',
    // 合约大小(乘数)
    contractSize: '',
    // 最小波动
    minFlux: '',
    // 单位
    unit: '',
    // 交易组
    tradeGroup: '',
    // 多头库存费
    longStockFee: '',
    // 空头库存费
    shortStockFee: '',
    // 止盈水平
    profitLevel: '',

    id: '',
    groupId: '',
    // 预付款对冲
    prepaymentHedge: '',
    // 预付款对冲比例
    prepaymentPercent: '',
    // 小数位
    decimalPlaces: '',
    // 点差小数位   
    pointDecimalPlaces: '',
})
const varietyFormRef = ref<any>()
const varietyFormRules = ref(rules())
const dialogFormItemOptions = ref(editDialogFormItem)
const varietyFormOptionsMap = ref({
    tradeGroup: [],
})
// 选中行
const selectedRow = ref<any>(null)
const rowGutter = ref(20)
const colSpan = ref(12)

/**
 * @description: 定义公共请求数据方法
 */

//获取品种列表
const getVarietyList = async () => {
    const params = {
        name: searchForm.value.varietyName,
    }
    const data = await getVarietyListApi(params)
    console.log('data', data)
    //格式化表格数据
    varietyTree.value = data.map((item: any) => ({
        ...item,
        id: item.id,
        varietyName: item.name,
        varietyCode: item.code,
        onlineStatus: item.online_status,
        tradeStatus: item.status,
        minPoint: item.point_diff,
        maxPoint: item.point_diff_max,
        contractSize: item.multiplier,
        minFlux: item.undulate_min,
        unit: item.unit,
        tradeGroup: item.group.name,
        longStockFee: item.fee_inventory_long,
        shortStockFee: item.fee_inventory_short,
        profitLevel: item.stop_loss_level,
    }))
}

//获取交易组列表
const getTradeGroupList = async () => {
    const data = await getTradeGroupListApi()
    varietyFormOptionsMap.value.tradeGroup = data.map((item: any) => ({
        label: item.name,
        value: item.id,
    }))
}

/**
 * @description: 页面加载完成需要请求的数据
 */
onMounted(() => {
    getVarietyList()
    getTradeGroupList()
})

/**
 * @description: 定义搜索方法
 */
const handleSearch = async () => {
    getVarietyList()
}
const handleReset = () => {
    searchForm.value = {
        varietyName: '',
    }
    handleSearch()
}

console.log('varietyForm.value)', varietyForm.value)
const handleEdit = () => {
    getTradeGroupList()
    const row = selectedRow.value;
    varietyForm.value = {
        ...row,
        id: row.id,
        groupId: row.group.id,
        // 预付款对冲
        prepaymentHedge: row.bail_hedge,
        // 预付款对冲比例
        prepaymentPercent: row.bail_percent,
        // 小数位
        decimalPlaces: row.decimal_place,
        // 点差小数位   
        pointDecimalPlaces: row.point_diff_decimal_place,
    } as any
    //数据赋值完成后执行弹窗操作
    dialogVisible.value = true
    dialogTitle.value = '编辑合约品种'
    dialogType.value = 'edit'

}

const handleAdd = () => {
    dialogVisible.value = true
    dialogTitle.value = '添加合约品种'
    dialogType.value = 'add'
    varietyForm.value = {
    varietyName: '',
    varietyCode: '',
    onlineStatus: 1,
    tradeStatus: 1,
    minPoint: '',
    maxPoint: '',
    contractSize: '',
    minFlux: '',
    unit: '',
    tradeGroup: '',
    longStockFee: '',
    shortStockFee: '',
    profitLevel: '',

    id: '',
    groupId: '',
    prepaymentHedge: '',
    prepaymentPercent: '',
    decimalPlaces: '',
    pointDecimalPlaces: '',
    }
}
/**
 * @description: 定义表格方法
 */

/**
 * @description: 定义弹窗方法
 */
const handleSubmit = async () => {
    await varietyFormRef.value?.validate()
    const params = {
        id: varietyForm.value.id,
        code: varietyForm.value.varietyCode,
        name: varietyForm.value.varietyName,
        group_id: varietyForm.value.groupId,
        point_diff: varietyForm.value.minPoint,
        fee_inventory_short: varietyForm.value.shortStockFee,
        status: varietyForm.value.tradeStatus,
        bail_hedge: varietyForm.value.prepaymentHedge,
        bail_percent: varietyForm.value.prepaymentPercent,
        decimal_place: varietyForm.value.decimalPlaces,
        stop_loss_level: varietyForm.value.profitLevel,
        point_diff_max: varietyForm.value.maxPoint,
        fee_inventory_long: varietyForm.value.longStockFee,
        point_diff_decimal_place: varietyForm.value.pointDecimalPlaces,
        unit: varietyForm.value.unit,
        multiplier: varietyForm.value.contractSize,
        undulate_min: varietyForm.value.minFlux,
        online_status: varietyForm.value.onlineStatus,
    }
    if (dialogType.value === 'edit') {
        console.log(params)
        await editVarietyApi(params)
        getVarietyList()
    } else {
        await createVarietyApi({...params, group_id: varietyForm.value.tradeGroup})
        getVarietyList()
    }
    dialogVisible.value = false
}
const handleCancel = () => {
    dialogVisible.value = false
}
const handleClose = () => {
    dialogVisible.value = false
}

/**
 * @description: 定义弹窗表格方法
 */
// 点击行事件
const handleRowClick = (row: any) => {
    if (!row) {
        selectedRow.value = null
        return
    }
    selectedRow.value = row
}
</script>

<style scoped lang="scss">
.search-container {
    :deep(.el-form) {
        .el-form-item {
            flex: none;
        }
    }
}
</style>
