<template>
    <!-- 添加或修改回款计划详情对话框 -->
    <el-dialog  :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
        <el-form ref="receivePlanDetailFormRef" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="客户名称" prop="customerId">
                <el-select
                    v-model="form.customerId"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入搜索选择客户"
                    remote-show-suffix
                    :remote-method="remoteMethod"
                    :loading="queryCutloading"
                    @change="getOrder"
                >
                    <el-option
                        v-for="item in custOptions"
                        :key="item.id"
                        :label="item.customerName"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="关联订单" prop="orderId">
                <el-select
                    v-model="form.orderId"
                    placeholder="请选择关联订单"
                    @change="getItem"
                >
                    <el-option
                        v-for="item in orderList"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="签单日期">
                <el-input v-model="orderItem.signingDate" readonly disabled/>
            </el-form-item>
            <el-form-item label="订单金额">
                <el-input v-model="orderItem.orderAmount" readonly disabled/>
            </el-form-item>
            <el-divider content-position="left">生成回款计划</el-divider>
            <template v-if="isParam">
                <el-form-item label="首次回款日期" prop="firstReceiveDate">
                    <el-date-picker clearable
                                    v-model="form.firstReceiveDate"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                    placeholder="请选择首次回款日期"
                    />
                </el-form-item>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="回款时间间隔" prop="receiveInterval">
                            <el-input style="width: 240px" v-model="form.receiveInterval"/>

                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="间隔类型" prop="receiveIntervalUnit">
                            <el-select v-model="form.receiveIntervalUnit" placeholder="请选择间隔类型">
                                <el-option value="1" label="日"></el-option>
                                <el-option value="2" label="月"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="回款期数" prop="receivePeriodTotal">
                    <el-input v-model="form.receivePeriodTotal"/>
                </el-form-item>
            </template>
            <el-table v-else :data="form.updateData">
                <el-table-column type="期次" width="55" prop="index" align="center">
                    <template #default="scope">
                        {{ scope.$index }}
                    </template>
                </el-table-column>
                <el-table-column label="计划回款日期" align="center" prop="materialNo" width="180">
                    <template #default="scope">
                        <el-form-item label-width="0px" :prop="'updateData['+scope.$index+'].planReceiveDate'" :rules="rules['updateData.planReceiveDate']">
                            <!--                                    <el-input v-model="scope.row.planReceiveDate" placeholder="计划回款日期"  size="small" ></el-input>-->
                            <el-date-picker clearable
                                            v-model="scope.row.planReceiveDate"
                                            type="date"
                                            value-format="YYYY-MM-DD"
                                            placeholder="计划回款日期"
                            />
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column label="回款占比" align="center" prop="quantity" width="160">
                    <template #default="scope">
                        <el-form-item label-width="0px" :prop="`updateData[${scope.$index}].receiveRatio`" :rules="rules['updateData.receiveRatio']">
                            <el-input type="number" v-model="scope.row.receiveRatio" placeholder="回款占比" :min="1" size="small"
                                             :max="100"></el-input>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column label="回款金额" align="center" width="180">
                    <template #default="scope">
                        <el-form-item label-width="0px" :prop="`updateData[${scope.$index}].planReceiveAmount`" :rules="rules['updateData.planReceiveAmount']">
                            <el-input type="number" v-model="scope.row.planReceiveAmount" placeholder="回款金额" size="small"></el-input>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column label="备注" align="center" width="160">
                    <template #default="scope">
                        <el-form-item label-width="0px">
                            <el-input v-model="scope.row.remark" placeholder="备注" size="small"></el-input>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-button link type="danger" icon="Delete" @click="deletePlan(scope.$index)"></el-button>
                        <el-button link type="primary" icon="plus" @click="addTime"></el-button>
                    </template>
                </el-table-column>
            </el-table>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button :loading="buttonLoading" type="primary" v-if="!isParam" @click="submitForm">提交</el-button>
                <el-button type="primary" @click="getDatePlan" v-else>下一步</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="ReceivePlanDetail" lang="ts">
import {

    addReceivePlanDetail,
    updateReceivePlanDetail,
    computedPlanDetail
} from '@/api/finance/receivePlanDetail';
import {listCustomer} from '@/api/customer';
import {listOrderForm} from '@/api/orderForm';
import {
    ReceivePlanDetailVO,
    ReceivePlanDetailQuery,
    ReceivePlanDetailForm,
    ComputedPlan
} from '@/api/finance/receivePlanDetail/types';
import auth from '@/plugins/auth'
import {tableTypes} from '@/components/Table/types'
import {DeptVO} from "@/api/system/dept/types";
import {listDept} from "@/api/system/dept";
import {MiniOrderFormVo, OrderFormQuery, OrderFormVO} from "@/api/orderForm/types";
import {CustomerQuery} from "@/api/customer/types";

const receivePlanDetailFormRef = ref<ElFormInstance>();
const tableFormRef = ref<ElFormInstance>();
const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const orgOptions = ref<Array<DeptVO>>([]);

const isParam = ref(true)

const receivePlanFormRef = ref(true)

const next = () => {
    isParam.value = false
}

const receivePlanDetailList = ref<ReceivePlanDetailVO[]>([]);
const buttonLoading = ref(false);
const queryCutloading = ref(true);
const showSearch = ref(true);

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const initFormData: ReceivePlanDetailForm = {
    id: undefined,
    receivePlanCode: undefined,
    planRecelveDate: undefined,
    actualRecelveDate: undefined,
    planRecelveAmount: undefined,
    customerId: undefined,
    actualRecelveAmount: undefined,
    recelveRatio: undefined,
    orderId: undefined,
    approveStatus: undefined,
    periodNum: undefined,
    periodTotal: undefined,
    receiveStatus: undefined,
    overdueDay: undefined,
    remark: undefined,
    isDelete: undefined,
    enabled: undefined,
    receivePeriodTotal: undefined,
    receiveIntervalUnit: undefined,
    firstReceiveDate: undefined,
    updateData: [{
        firstReceiveDate: undefined,
        receiveIntervalUnit: undefined,
        receiveInterval: undefined,
        receivePeriodTotal: undefined,
        planReceiveAmount: undefined,
        isCreate: 1,

    }]
}
const addTime = () => {

    form.value.updateData.push({
        firstReceiveDate: '',
        receiveIntervalUnit: '',
        receiveInterval: '',
        receivePeriodTotal: '',
        planReceiveAmount: '',
        isCreate: 1,
    })
}
const deletePlan = (index) => {

    form.value.updateData.splice(index, 1)
}

const data = reactive<PageData<ReceivePlanDetailForm, ReceivePlanDetailQuery>>({
    form: {...initFormData},
    rules: {

        'updateData.planReceiveDate': [
            {required: true, message: "请选择回款日期1", trigger: "change"}
        ],
        'updateData.receiveRatio': [
            {required: true,  message: "请输入回款占比2", trigger: "blur"}
        ],
        'updateData.planReceiveAmount': [
            {required: true, message: "请输入回款金额3", trigger: "blur"}
        ],
        customerId: [
            {required: true, message: "请选择客户", trigger: "change"}
        ],
        orderId: [
            {required: true, message: "请选择订单", trigger: "change"}
        ],
        firstReceiveDate: [
            {required: true, message: "首次回款金额不能为空", trigger: "change"}
        ],
        receiveInterval: [
            {required: true, message: "回款间隔不能为空", trigger: "change"}
        ],
        receiveIntervalUnit: [
            {required: true, message: "回款间隔类型", trigger: "blur"}
        ],
        receivePeriodTotal: [
            {required: true, message: "回款期数不能为空", trigger: "blur"}
        ],

        planReceiveDate: [
            {required: true, message: "请选择日期", trigger: "change"}
        ],
        receiveRatio: [
            {required: true, message: "回款占比", trigger: "change"}
        ],
        planReceiveAmount: [
            {required: true, message: "计划回款金额", trigger: "change"}
        ]
    }
});
const plansData = ref<ComputedPlan[]>([])

const getDatePlan = async () => {
    receivePlanDetailFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            let param: ComputedPlan = {
                firstReceiveDate: form.value.firstReceiveDate,
                receiveIntervalUnit: form.value.receiveIntervalUnit,
                receiveInterval: form.value.receiveInterval,
                receivePeriodTotal: form.value.receivePeriodTotal,
                planReceiveAmount: orderItem.orderAmount,
                isCreate: 1,

            }
            let data = await computedPlanDetail(param)
            form.value.updateData = data.result
            next()
        }
    });

}

const {form, rules} = toRefs(data);

const closeDilog = () => {
    isParam.value = true
    reset()
    dialog.visible = false
}

const reset = () => {
    isParam.value = true
}

/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}


const receivePlanDetailTable = ref()
/** 搜索按钮操作 */
const handleQuery = () => {
    receivePlanDetailTable.value.getData()
}


/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加回款计划详情";
}

const getList = () => {
    receivePlanDetailTable.value.getData()
}
/** 提交按钮 */
const submitForm = async () => {
    console.log(form.value, ">>>>>>>>>>>>>>>>>>..........")
    receivePlanDetailFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.id) {
                await updateReceivePlanDetail(form.value).finally(() => buttonLoading.value = false);
            } else {
                await addReceivePlanDetail(form.value).finally(() => buttonLoading.value = false);
            }
            proxy?.$modal.msgSuccess("操作成功");
            dialog.visible = false;
            // await getList();
        }
    });
}

const getDept = async () => {
    let typs: number[] = [10, 20, 30]
    const res = await listDept(typs, undefined);
    orgOptions.value = res.result;

}

interface ListItem {
    id: string
    customerName: string
}

const custOptions = ref<ListItem[]>([])
const orderList = ref<OrderFormVO[]>([])
const orderItem = reactive<MiniOrderFormVo>({
    id: 0,
    orderAmount: 0,
    signingDate: null
})

const getItem = (item) => {
    console.log(item, ">>>>>>>>>>>>>..........")
    let dataItem = orderList.value.find(i => i.id = item)
    if (dataItem) {
        orderItem.id = dataItem.id;
        orderItem.orderAmount = dataItem.orderAmount;
        orderItem.signingDate = dataItem.signingDate;
    }

}

const getOrder = async () => {
    orderList.value = []
    form.value.orderId = undefined
    let query: OrderFormQuery & PageQuery = {
        customerId: form.value.customerId,
        pageIndex: 1,
        pageSize: 100
    }
    let data = await listOrderForm(query)
    console.log(data, ">.................")
    orderList.value = data.result.records
}
const getCust = async (query) => {
    queryCutloading.value = true
    let param: CustomerQuery & PageQuery = {
        blurry: query,
        pageSize: 1000,
        pageIndex: 1
    }
    let data = await listCustomer(param)
    console.log(data, ">.................")
    custOptions.value = data.result.records
    queryCutloading.value = false
}

const remoteMethod = async (query: string) => {
    if (query) {
        getCust(query)
    }
}
const open = () => {
    handleAdd()
}

defineExpose({
    open

})
onMounted(() => {
    getDept()
    getCust(undefined)
});
</script>
