<template>

    <!-- 添加或修改费用对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
        <el-form ref="costRecordFormRef" :model="form" :rules="rules" label-width="120px">

            <el-form-item label="费用名称" prop="costName">
                <el-input v-model="form.costName" placeholder="请输入费用名称"/>
            </el-form-item>
            <el-form-item label="费用类型" prop="costType">
<!--                <el-input v-model="form.costType" placeholder="请输入费用类型"/>-->
                <SelectDict v-model="form.costType" placeholder="请选择费用类型"
                            dictCode="cost_type"></SelectDict>
            </el-form-item>
            <el-form-item label="金额" prop="costAmount">
                <el-input v-model="form.costAmount" placeholder="请输入金额">
                    <template #append>
                        <span>元</span>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="费用描述" prop="costAmount">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入费用描述"> </el-input>
            </el-form-item>

            <el-form-item label="发生时间" prop="costTakeDate">
                <el-date-picker clearable
                                v-model="form.costTakeDate"
                                type="date"
                                style="width: 250px"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择发生时间">
                </el-date-picker>
            </el-form-item>

            <CorrelationSelect :disabled="isDisabled" v-model="form.cusstomerId" v-model:liaisonId="form.liaisonId" labelLiaison="联系人" />
            <el-form-item label="关联订单/商机" >
                <el-row style="width: 100%" :gutter="15">
                    <el-col :span="12">
                        <el-select v-model="form.resourceType" @change="getOrderOrBusiness">
                            <el-option :value="30" label="商机"></el-option>
                            <el-option :value="40" label="订单" ></el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="12">
                        <el-select-v2
                            v-model="form.resourceTypeId"
                            :options="groupData"
                            placeholder="请选择关联订单/商机"
                            filterable
                            @change="getlistFollow"
                        />
                    </el-col>
                </el-row>


            </el-form-item>
            <el-form-item label="上传附件">
                <Upload v-model="form.resourceIdList" />
            </el-form-item>
            <el-form-item label="跟进记录">
                <el-select-v2
                    v-model="form.followId"
                    :options="flowList"
                    placeholder="请选择跟进记录"
                    filterable

                />
            </el-form-item>

            <el-form-item label="负责人员" prop="ownerBy">
                <SelectUser placeholder="请选择负责人" v-model="form.ownerBy"></SelectUser>
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script setup name="addCostRecord" lang="ts">
import {
    getCostRecord,
    addCostRecord,
    updateCostRecord
} from '@/api/finance/costRecord/index';
import {CostRecordVO, CostRecordQuery, CostRecordForm} from '@/api/finance/costRecord/types';
import {listFollow} from "@/api/customer/follow";
import {listAllBusiness} from "@/api/business/allBusiness";
import {listOrderForm} from "@/api/orderForm";
import {useDictCache} from "@/hooks/web/useDict";
const emits = defineEmits(['ok'])
const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const {queryDictDetailByCodes} = useDictCache(['cost_type'])
queryDictDetailByCodes()
const costRecordList = ref<CostRecordVO[]>([]);

const isDisabled = ref(false)
const buttonLoading = ref(false)
const costRecordFormRef = ref<ElFormInstance>();
const groupData = ref<{ label: string; value: string | number }[]>([])
const flowList = ref<{ label: string; value: string | number }[]>([])
const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const initFormData: CostRecordForm = {
    id: undefined,
    costCode: undefined,
    costName: undefined,
    costAmount: undefined,
    costTakeDate: undefined,
    reimburseStatus: undefined,
    cusstomerId: undefined,
    resourceType: undefined,
    resourceTypeId: undefined,
    currencyUnitId: undefined,
    remark: undefined,
    isDelete: undefined,
    enabled: undefined,
    ownerBy: undefined,
    sort: undefined
}
const businessList = ref<{ label: string; value: string | number }[]>([])
const orderFormList = ref<{ label: string; value: string | number }[]>([])
const getOrderOrBusiness  = async (value: number)=>{
    if(!form.value.cusstomerId) return
    if(value == 30) {
        const res = await listAllBusiness({
            pageIndex: 1,
            pageSize: 1000,
            customerId: form.value.cusstomerId
        })
        groupData.value = res.result.records.map(item=>{
            return {
                label: item.title,
                value: item.id
            }
        })

    } else if(value == 40){
        const res = await listOrderForm({
            pageIndex: 1,
            pageSize: 1000,
            customerId: form.value.cusstomerId
        })
        groupData.value = res.result.records.map(item=>{
            return {
                label: item.title,
                value: item.id
            }
        })

    } else {
        groupData.value=[]
    }
}
const data = reactive<PageData<CostRecordForm, CostRecordQuery>>({
    form: {...initFormData},
    rules: {
        id: [
            {required: true, message: "主键不能为空", trigger: "blur"}
        ],
        costCode: [
            {required: true, message: "费用编号不能为空", trigger: "blur"}
        ],
        costType: [
            {required: true, message: "费用类型不能为空", trigger: "blur"}
        ],
        costName: [
            {required: true, message: "费用名称不能为空", trigger: "blur"}
        ],
        costAmount: [
            {required: true, message: "金额不能为空", trigger: "blur"}
        ],
        costTakeDate: [
            {required: true, message: "付费日期不能为空", trigger: "blur"}
        ],
        reimburseStatus: [
            {required: true, message: "报销状态不能为空", trigger: "change"}
        ],
        cusstomerId: [
            {required: true, message: "客户id不能为空", trigger: "blur"}
        ],
        resourceType: [
            {
                required: true,
                message: "10:客户、11线索、20:联系人、30:商机、40:订单、50:回款、60:退款、70:费用、80:任务、90:跟进、100:工单不能为空",
                trigger: "blur"
            }
        ],
        resourceTypeId: [
            {required: true, message: "关联订单or商机id不能为空", trigger: "blur"}
        ],
        currencyUnitId: [
            {required: true, message: "关联币种单位id不能为空", trigger: "blur"}
        ],

        ownerBy: [
            {required: true, message: "拥有者不能为空", trigger: "blur"}
        ],

    }
});

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

const cancel = () => {
    dialog.visible = false;
    reset();
}
/** 表单重置 */
const reset = () => {
    form.value = {...initFormData};
    costRecordFormRef.value?.resetFields();
}

const costRecordTable = ref()
/** 搜索按钮操作 */
const handleQuery = () => {
    costRecordTable.value.getData()
}
const isDefault = ref(false)
/** 新增按钮操作 */
const handleAdd = (item?: any) => {
    isDefault.value = false
    if(item) {
        isDefault.value = true
        Object.assign(form.value, item)
    }
    reset();
    dialog.visible = true;
    dialog.title = "添加费用";
}
//
/** 修改按钮操作 */
const handleUpdate = async (row?: CostRecordVO) => {
    reset();
    const _id = row?.id
    const res = await getCostRecord(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改费用";
}
const getList = () => {
    costRecordTable.value.getData()
}
/** 提交按钮 */
const submitForm = () => {
    costRecordFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.id) {
                await updateCostRecord(form.value).finally(() => buttonLoading.value = false);
            } else {
                await addCostRecord(form.value).finally(() => buttonLoading.value = false);
            }
            proxy?.$modal.msgSuccess("操作成功");
            dialog.visible = false;
        }
    });
}

const getlistFollow=async () => {
    const res = await listFollow({
        pageIndex: 1,
        pageSize: 1000,
        customerId: form.value.cusstomerId,
        resourceTypeId: form.value.resourceTypeId,
        resourceType: form.value.resourceType
    });
    flowList.value = res.result.records.map(item => {
        return {
            label: item.content,
            value: item.id
        }
    })
}

defineExpose({
    handleAdd,
    handleUpdate
})

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