<template>
    <div class="add-area">
        <div class="header flex-center">
            <p>{{ queryData.type == 'edit' ? '编辑' : '添加' }}订单</p>
            <p>*为必填项</p>
        </div>
        <div class="content">
            <el-form ref="orderFormRef" :model="form" :rules="rules" class="flex" label-width="120px">
                <div class="order-form-content">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="订单标题：" prop="title">
                                <el-input v-model="form.title" placeholder="请输入订单标题" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="关联客户：" prop="customerId">
                                <el-input v-if="queryData.type == 'edit'" v-model="form.customerName"
                                    disabled></el-input>
                                <paginationSelect v-model="form.customerId" @changeSelect="changeCustomer"
                                    :selectedName="form.customerName" source="orderForm" :listFn="listCustomer"
                                    :params="customerParams" v-else />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="关联商机：" prop="businessId">
                                <el-select-v2 v-model="form.businessId" :options="businessData" placeholder="请选择商机"
                                    filterable clearable @change="getProduct({ businessId: form.businessId })"
                                    v-loading="isLoading" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="订单金额：" prop="quotationAddDTO.totalMoney">
                                <div style="width: 100%" class="flex">
                                    <el-input disabled v-model="form.quotationAddDTO.totalMoney"
                                        placeholder="请先选择关联产品" />
                                    <div class="unit" style="margin-right: 12px">元</div>
                                    <el-button @click="addQuotation" type="primary">{{ form.quotationAddDTO?.id ? '编辑' :
                                        '添加' }}报价</el-button>
                                </div>
                            </el-form-item>
                        </el-col>

                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <!-- <el-form-item label="付款币种：" prop="currencyId" class="form-item">
                                <el-select-v2 v-model="form.currencyId" :options="currencyData" placeholder="选择付款币种"
                                              filterable clearable />
                            </el-form-item> -->
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="订单类型：" prop="orderTypeDictValue">
                                <SelectDict v-model="form.orderTypeDictValue" placeholder="选择订单类型"
                                    dictCode="order_type"></SelectDict>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="签单日期：" prop="signingDate">
                                <el-date-picker v-model="form.signingDate" type="date" placeholder="选择签单日期"
                                    value-format="YYYY-MM-DD" />
                            </el-form-item>
                        </el-col>

                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="预计生产日期：" prop="expectedProductionDate">
                                <el-date-picker v-model="form.expectedProductionDate" type="date" placeholder="选择预计生产日期"
                                    value-format="YYYY-MM-DD" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="预计发货日期：" prop="expectedDeliveryDate">
                                <el-date-picker v-model="form.expectedDeliveryDate" type="date" placeholder="选择预计发货日期"
                                    value-format="YYYY-MM-DD" />
                            </el-form-item>
                        </el-col>

                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="客户签约人：" prop="customerSignatory">
                                <el-input v-model="form.customerSignatory" placeholder="请输入客户签约人" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="我方签约人：" prop="ourSignatory">
                                <el-input v-model="form.ourSignatory" placeholder="请输入我方签约人" />
                            </el-form-item>
                        </el-col>

                    </el-row>
                    <el-row>

                        <el-col :span="24">
                            <el-form-item label="上传附件：" class="form-item">
                                <Upload v-model="form.resourceIdList" :resourceList="fileList" />
                            </el-form-item>
                        </el-col>
                    </el-row>


                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="备注信息：" prop="remark">
                                <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入备注信息"
                                    :maxlength="300" resize="none" show-word-limit />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="通知人员：" prop="remindUserIds" class="form-item">
                                <SelectUser multiple v-model="form.remindUserIds" :inputHeight="34"></SelectUser>
                                <p>注：处理完成后，将自动通知到所选人员。</p>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="归属人员：" prop="ownerBy">
                                <SelectUser v-model="form.ownerBy"></SelectUser>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <CreateQuickTask v-model="form.task" />
                </div>
            </el-form>
        </div>
        <div class="footer flex">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
            <el-button @click="reset">重置</el-button>
        </div>
    </div>
    <GetProductPrice ref="getProductPriceRef" @ok="getProductPrice"></GetProductPrice>
</template>

<script setup lang="ts" name="addOrderForm">
import { OrderFormQuery, OrderFormForm } from '@/api/orderForm/types';
import { addOrderForm, updateOrderForm, getOrderForm } from '@/api/orderForm';
import { listAllBusiness } from '@/api/business/allBusiness';
import GetProductPrice from '@/modules/sales/views/business/component/GetProductPrice.vue';
import { listCurrencySetting } from '@/api/system/currencySetting';
import Upload from '@/components/FileUpload/upload.vue';
import { useDictCache } from '@/hooks/web/useDict';
import { getDetail } from "@/api/product";
import CreateQuickTask from '@/components/common/createQuickTask.vue';
import useUserStore from '@/store/modules/user';
import useTagsViewStore from "@/store/modules/tagsView";
import paginationSelect from '@/components/common/paginationSelect.vue';
import { listCustomer } from '@/api/customer';
const tagsViewStore = useTagsViewStore()

const { queryDictDetailByCodes } = useDictCache(['order_type', 'task_remind_type', 'task_remind_mode', 'task_mark_tag', 'task_priority_grade']);
queryDictDetailByCodes();

const router = useRouter();
const route = useRoute();
let queryData: any = router.currentRoute.value.query;
const buttonLoading = ref(false);
const orderFormRef = ref<ElFormInstance>();
const getProductPriceRef = ref();
const addQuotation = () => {
    
    if (!form.value.quotationAddDTO.id) {
        getProductPriceRef.value.open(form.value.businessId);
    } else {
        getProductPriceRef.value.edite({ id: form.value.quotationAddDTO.id });
    }
};
const getProductPrice = async (data) => {
    if (data) {
        form.value.quotationAddDTO = data;
    } else {
        let params = form.value.quotationAddDTO?.id ? { id: form.value.quotationAddDTO.id } : { businessId: form.value.businessId };
        getProduct(params, true);
    }
};
const getProduct = async (params: any, isFlag?: boolean) => {
    if (!form.value.businessId && !isFlag) {
        form.value.quotationAddDTO = {
            totalMoney: undefined
        };
        form.value.quotationId = '';
    } else {
        const res = await getDetail(params);
        form.value.quotationAddDTO = res.result;
        form.value.quotationAddDTO.totalMoney = res.result.totalOrderAmt?.toFixed(2);
        form.value.quotationId = res.result.id;
    }
}

const customerParams = {
    commonScope: 1,
    commonScopeType: '10',
    customerForm: 10,
    hasPublicCustomer: 0,
    hasGarbageCustomer:0,
    customerName: '',
    id: queryData.customerId
}

const isLoading = ref(false);
const businessData = ref<{ label: string; value: string | number }[]>([]);
const getBusinessData = () => {
    let params = {
        pageIndex: 1,
        pageSize: 999999,
        customerId: form.value.customerId,
        hasOrderForm: 2,
        id: form.value.businessId,
        hasLoss: 0,
        commonScope: 1,
        commonScopeType: '10'
    };
    isLoading.value = true;
    listAllBusiness(params).then(res => {
        if (res.success) {
            businessData.value = res.result.records.map(item => {
                let obj = { label: item.title, value: item.id };
                return obj;
            });
        }
    }).finally(() => {
        isLoading.value = false;
    });
};

const currencyData = ref<{ label: string; value: string | number }[]>([]);
const getCurrencyData = () => {
    listCurrencySetting({ pageIndex: 1, pageSize: 999999 }).then(res => {
        if (res.success) {
            currencyData.value = res.result.records.map(item => {
                let obj = { label: item.chineseName, value: item.id };
                return obj;
            });
        }
    });
};

const changeCustomer = () => {
    form.value.businessId = '';
    getBusinessData();
    form.value.quotationAddDTO = {
        totalMoney: undefined
    };
    form.value.quotationId = '';
};

const { userInfo } = useUserStore();
const initFormData: OrderFormForm = {
    id: undefined,
    title: undefined,
    customerId: undefined,
    businessId: undefined,
    quotationId: undefined,
    orderAmount: undefined,
    currencyId: undefined,
    orderTypeDictValue: undefined,
    signingDate: undefined,
    expectedProductionDate: undefined,
    expectedDeliveryDate: undefined,
    customerSignatory: undefined,
    ourSignatory: undefined,
    remark: undefined,
    remindUserIds: undefined,
    isDelete: undefined,
    enabled: undefined,
    ownerBy: userInfo.id,
    sort: undefined,
    task: {
        isCreateTask: false
    },
    quotationAddDTO: {
        totalMoney: undefined
    }
};
const data = reactive<PageData<OrderFormForm, OrderFormQuery>>({
    form: { ...initFormData },
    rules: {
        title: [
            { required: true, message: "订单标题不能为空", trigger: "blur" }
        ],
        customerId: [
            { required: true, message: "关联客户不能为空", trigger: "change" }
        ],
        'quotationAddDTO.totalMoney': [
            { required: true, message: "订单金额不能为空", trigger: "change" }
        ],
        signingDate: [
            { required: true, message: "签单日期不能为空", trigger: "change" }
        ],
        'task.taskBeginTime': [
            { required: true, message: "下次跟进时间不能为空", trigger: "change" }
        ],
        'task.ownerBy': [
            { required: true, message: "跟进人员不能为空", trigger: "change" }
        ],
        'task.remindType': [
            { required: true, message: "任务提醒不能为空", trigger: "change" }
        ],
        'task.objectiveValue': [
            { required: true, message: "任务目的不能为空", trigger: "change" }
        ],
        'task.taskContent': [
            { required: true, message: "跟进内容不能为空", trigger: "blur" }
        ],
    }
});

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

// 编辑时查数据
const fileList = ref([]);
const catchId = ref()
const getDetailData = () => {
    let routerData: any = router.currentRoute.value.query
    if (routerData.type == 'edit') {
        if(catchId.value == routerData.id) {
            return
        }
        catchId.value = routerData.id
        tagsViewStore.editeTitle(route.path, '编辑订单')
        getOrderForm(routerData.id).then(res => {
            if (res.success) {
                if (res.result.remindUserIds) {
                    res.result.remindUserIds = typeof (res.result.remindUserIds) == 'string' ? res.result.remindUserIds.split(",") : '';
                }
                Object.assign(form.value, res.result);
                fileList.value = res.result.resourceList;
                getProduct({ orderFormId: routerData.id }, true);
                getBusinessData();
            }
        });
    }else {
        if(catchId.value) {
            reset()
        }
        catchId.value = undefined
        tagsViewStore.editeTitle(route.path, '添加订单')
    }
    if (routerData.businessId) {
        form.value.businessId = routerData.businessId;
        getProduct({ businessId: routerData.businessId });
    }
    if (routerData.customerId) {
        form.value.customerId = routerData.customerId;
        getBusinessData();
    }
}

/** 表单重置 */
const reset = () => {
    form.value = { ...initFormData };
    orderFormRef.value?.resetFields();
};

/** 提交按钮 */
const submitForm = () => {
    orderFormRef.value?.validate((valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            let params = JSON.parse(JSON.stringify(form.value));
            if (params.remindUserIds) {
                params.remindUserIds = params.remindUserIds?.join(",");
            }
            let request = queryData.type == 'add' ? addOrderForm : updateOrderForm;
            request(params).then(res => {
                if (res.success) {
                    ElMessage.success((queryData.type == 'add' ? '新增' : '编辑') + "成功");
                    router.push('../order/detail?id=' + res.result);
                }
            }).finally(() => buttonLoading.value = false);
        }
    });
};

onBeforeMount(() => {
    getCurrencyData();
});

onActivated(() => {
    getDetailData()
})

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

<style scoped lang="scss">
.add-area .content .el-form {

    .el-input,
    .el-textarea,
    .el-row,
    :deep(.el-date-editor),
    :deep(.el-select) {
        width: 100%;
    }
    .order-form-content{

        .el-row{
            width: 900px;

        }
    }
}
.form-item {
    :deep(.el-form-item__content) {
        flex-direction: column;
        align-items: flex-start;
    }
}

.unit {
    border: 1px solid #dcdfe6;
    width: 52px;
    text-align: center;
    border-radius: 2px;
    margin-left: -2px;
}
</style>
