<script setup lang="ts">
import { useRenderIcon } from '/@/components/ReIcon/src/hooks';
import ChooseOrderModal from "./../ChooseOrderModal/index.vue"
import { statusOptions, typeOptions } from '../../config/shared';
import { ElButton, ElForm, ElMessage, ElTooltip } from 'element-plus';
import { useTypeOptions } from '/@/utils/status';
import { reactive, ref } from 'vue';

import ChooseGoodModal from "./../ChooseGoodModal/index.vue"
import ChildGoodEditModal from "./../ChildGoodEditModal.vue";
import SealMonthPicker from "/@/components/SealMonthPicker/index.vue"
import { useTask } from '/@/hooks/core';

import { httpAdd } from "/@/api/invoiceInOut/clientC"
import { useRouter } from 'vue-router';

const state = reactive({ 
    orderVisible: false, 
    goodvisible: false, 
    editVisible: false, 
    data: {},
    index: -1
})

const router = useRouter()
const formData = ref({ orders: [], goods: [], month: '' })

const createTask = useTask({ success(){
    ElMessage.success('创建成功') 
    router.push('/invoiceInOut/clinetC') 
} })

const formRef = ref<InstanceType<typeof ElForm> | null>(null)

function getSpanNumber(data, prop) {
    let length = Array.isArray(data) ? data.length : 0;
    if (length > 0) {
        let position = 0;
        let temp = data[0][prop];
        let result = [1];
        for (let i = 1; i < length; i++) {
            if (data[i][prop] == temp) {
                result[position] += 1;
                result[i] = 0;
            } else {
                position = i;
                result[i] = 1;
                temp = data[i][prop];
            }
        }
        return result;
    } else {
        return [0];
    }
}


function spanMethod({ row: _1, column: _2, rowIndex, columnIndex }: any) {
    if ([0, 1, 2, 7].includes(Number(columnIndex))) {
        let nameSpan = getSpanNumber(formData.value.goods, "id");
        return { rowspan: nameSpan[rowIndex], colspan: 1 };
    }
}

function handleOrderSubmit(values: any[]){
    const ids = formData.value.orders.map(({ id }) => id)
    values.forEach(item => {
        if(!ids.includes(item.id)){
            formData.value.orders.push(item)
        }
    })
}
function handleChildGoodEdit(index: number) {
    state.index = index
    state.editVisible = true
    state.data = { ...formData.value.goods[index] }
}


function handleDelete(index) {
    const { id } = formData.value.goods[index]
    formData.value.goods = formData.value.goods.filter((item) => item.id !== id)
}

function handleGoodComfirm(values: any[]) {
    const ids = formData.value.goods.map(({ id }) => id)
    const list = []

    values.forEach(item => {
        if (!ids.includes(item.id)) { list.push(item) }
    })

    formData.value.goods = [...list, ...formData.value.goods]
}

function handleEditGood(index: number, data: any) {
    const { id } = formData.value.goods[index];
    formData.value.goods = formData.value.goods.map(item => {
        if (item.id === id) {
            const goodNum = data.goodNum;
            const childActionNum = item.childNum
                ? Number(item.childNum) * Number(goodNum)
                : undefined;

            return { ...item, goodNum, childActionNum };
        }
        return item;
    });
}

async function submitForm(){
    try{
        await formRef.value?.validate()
        const { orders, goods, month } = formData.value

        const parameter = {
            manager_id: orders.map(item => item.id),
            relaArr: goods.map(item => ({ id: item.id, num: item.goodNum })),
            fz_date: month
        }

        createTask.run(httpAdd(parameter))
    }catch(err){
        console.log(err)
    }
}


const rules = {
    orders: [{ required: true, message: '请选择toC订单信息', trigger: 'change' }],
    goods: [{ required: true, message: '请选择操作商品', trigger: 'change' }],
    month: [{ required: true, message: '请选择入账月份', trigger: 'change' }]
}
</script>

<template>
    <ElForm
        ref="formRef" 
        label-width="100px" 
        :model="formData"
        :rules="rules" 
    >
        <ElFormItem label="toC订单信息" prop="orders">
            <ElTable border size="small" :data="formData.orders">
                <ElTableColumn label="确认单编号" prop="orderCode" show-overflow-tooltip />
                <ElTableColumn label="销售主单号" prop="cxCode" show-overflow-tooltip />

                <ElTableColumn label="业务类型">
                    <template #="{ row }">
                        <ElTag size="small">
                            {{ typeOptions.find(item => item.value == row.type)?.label || '--' }}
                        </ElTag>
                    </template>
                </ElTableColumn>

                <ElTableColumn label="状态">
                    <template #="{ row }">
                        <ElTag size="small">
                            {{ statusOptions.find(item => item.value == row.status)?.label || '--' }}
                        </ElTag>
                    </template>
                </ElTableColumn>

                <ElTableColumn label="平台订单号" prop="poCode" show-overflow-tooltip />

                <ElTableColumn label="平台类型">
                    <template #="{ row }">
                        <ElTag size="small">
                            {{ useTypeOptions.find(item => item.value == row.status)?.label || '--' }}
                        </ElTag>
                    </template>
                </ElTableColumn>

                <ElTableColumn label="卖出方公司" prop="seller_name" show-overflow-tooltip />
                <ElTableColumn label="客户公司" prop="buyer_name" show-overflow-tooltip />
                <ElTableColumn label="商品名称" prop="goodName" show-overflow-tooltip />
                <ElTableColumn label="下单数量" prop="num" show-overflow-tooltip />
                <ElTableColumn label="销售单价" prop="goodPrice" show-overflow-tooltip />
                <ElTableColumn label="销售合计" prop="totalPrice" show-overflow-tooltip />
                <ElTableColumn label="出库时间" porp="fz_date" show-overflow-tooltip />
                <ElTableColumn label="操作" fixed="right" width="60px">
                    <template #header>
                        <div class="flex justify-between">
                            <span>操作</span>
                            <ElTooltip content="添加" placement="top">
                                <ElButton :icon="useRenderIcon('add')" link size="small" type="primary"
                                    @click="state.orderVisible = true" />
                            </ElTooltip>
                        </div>
                    </template>

                    <template #="{ $index }">
                        <ElTooltip content="删除" placement="top">
                            <ElButton @click="formData.orders.splice($index, 1)" :icon="useRenderIcon('delete')"
                                size="small" type="danger" link />
                        </ElTooltip>
                    </template>
                </ElTableColumn>
            </ElTable>
        </ElFormItem>

        <ElFormItem label="操作商品" prop="goods">
            <ElTable :span-method="spanMethod" border size="small" :data="formData.goods">
                <ElTableColumn label="商品编号" prop="skuCode" show-overflow-tooltip />
                <ElTableColumn label="商品名称" prop="goodName" show-overflow-tooltip />
                <ElTableColumn label="操作数量" prop="goodNum" show-overflow-tooltip />
                <ElTableColumn label="子商品编号" prop="childCode" show-overflow-tooltip />
                <ElTableColumn label="销售方公司纳税识别号" width="140px" prop="seller_code" show-overflow-tooltip />
                <ElTableColumn label="子商品比例" prop="childNum" show-overflow-tooltip />
                <ElTableColumn label="子商品操作数量" prop="childActionNum" show-overflow-tooltip />

                <ElTableColumn width="70px" label="操作">
                    <template #header>
                        <div class="w-full flex justify-between">
                            <span>操作</span>
                            <ElTooltip content="添加" placement="top">
                                <ElButton link size="small" type="primary" :icon="useRenderIcon('add')"
                                    @click="state.goodvisible = true" />
                            </ElTooltip>
                        </div>
                    </template>

                    <template #="{ $index }">
                        <ElTooltip content="编辑" placement="top">
                            <ElButton :icon="useRenderIcon('edits')" type="primary" size="small" link
                                @click="handleChildGoodEdit($index)" />
                        </ElTooltip>


                        <ElTooltip content="删除" placement="top">
                            <ElButton :icon="useRenderIcon('delete')" type="danger" size="small" link
                                @click="handleDelete($index)" />
                        </ElTooltip>
                    </template>
                </ElTableColumn>
            </ElTable>
        </ElFormItem>

        <ElFormItem label="入账月份" prop="month">
            <SealMonthPicker v-model="formData.month" placeholder="入账月份" />
        </ElFormItem>


        <div class="w-full flex justify-end">
            <ElButton 
                type="primary"
                @click="submitForm"
                >保存</ElButton>
        </div>

        <ChooseOrderModal 
            v-model:visible="state.orderVisible" 
            @submit="handleOrderSubmit" 
        />

        <ChooseGoodModal 
            v-model:visible="state.goodvisible" 
            @submit="handleGoodComfirm" 
        />

        <ChildGoodEditModal 
            :data="state.data" 
            :index="state.index" 
            v-model:visible="state.editVisible"
            @submit="handleEditGood" 
         />
    </ElForm>
</template>