<template>
    <div class="add-area add-area-bus">
        <div class="header flex-center">
            <p>{{catchId ? '编辑商机' : '添加商机'}}</p>
            <p>*为必填项</p>
        </div>
        <div class="content">
            <el-form ref="allBusinessFormRef" :model="form" :rules="rules" class="flex" label-width="140px">
                <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="24">
                            <correlationSelect labelLiaison="联系人：" v-model="form.customerId"
                                v-model:liaisonId="form.liaisonId" :selectedName="form.customerName"
                                :selectedId="$route.query.customerId as string">
                            </correlationSelect>
                        </el-col>

                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="销售阶段：" prop="stage">
                                <SelectDict v-model="form.stage" placeholder="请选择销售阶段" dictCode="business_stage">
                                </SelectDict>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">

                            <el-form-item label="商机类型：" prop="businessTypeDictValue">
                                <SelectDict v-model="form.businessTypeDictValue" placeholder="请选择商机类型"
                                    dictCode="business_type"></SelectDict>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="商机来源：" prop="sourcesOfBusinessDictValue">
                                <SelectDict v-model="form.sourcesOfBusinessDictValue" placeholder="请选择商机来源"
                                    dictCode="sources_of_business"></SelectDict>
                            </el-form-item>

                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="成交机率：">
                                <SelectDict :clearable='false' v-model="form.transactionProbabilityDictValue"
                                    placeholder="请选择成交机率" dictCode="transaction_probability"></SelectDict>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">

                            <el-form-item label="预计金额：">

                                <div class="flex flex-column" style="width: 100%">
                                    <div class="flex" style="width: 100%">

                                        <div style="width: 70%">
                                            <el-input type="number" style="width: 100%"
                                                v-model="form.initialSalesAmount" placeholder="请输入预计销售金额"> </el-input>
                                        </div>
                                        <div style="width: 30%">
                                            <el-select style="width: 100%" v-model="form.currency" placeholder="请选择币种">
                                                <el-option :value="1" label="CNY"></el-option>
                                                <el-option :value="2" label="USD"></el-option>
                                            </el-select>
                                        </div>
                                    </div>
                                    <p style="width: 100%; " v-if="form.currency == 2">
                                        当前汇率：{{ rate }}，结算人民币：{{ $formatNumber(form.initialSalesAmount * rate) }}</p>
                                    <!-- <p style="width: 100%; " v-if="form.currency == 1">当前汇率：{{rate}}，折算美元：{{$formatNumber(form.initialSalesAmount / rate)}}</p> -->
                                </div>

                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="获取日期：" prop="getedDate">
                                <el-date-picker clearable v-model="form.getedDate" type="date" value-format="YYYY-MM-DD"
                                    :disabled-date="disabledFutureDates" placeholder="请选择获取日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="归属人员：" prop="ownerBy">
                                <SelectUser v-model.lazy="form.ownerBy"></SelectUser>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="预计签单：">
                                <el-date-picker :disabled-date="disabledPastDates" clearable
                                    v-model="form.expectedSigningDate" type="date" value-format="YYYY-MM-DD"
                                    placeholder="请选择预计签单日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <CreateQuickTask v-model="form.task"></CreateQuickTask>

                </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>

</template>

<script setup name="businessAdd" lang="ts">
import {
    listAllBusiness,
    delAllBusiness,
    addAllBusiness,
    updateAllBusiness, getById
} from '@/api/business/allBusiness';
import {getUSDtoCnyRate} from '@/api/product/index'
import correlationSelect from '@/components/common/correlationSelect.vue'
import addCollaborate from '@/components/common/addCollaborate.vue'
import createTask from '@/components/common/createTask.vue'
import { AllBusinessVO, AllBusinessQuery, AllBusinessForm } from '@/api/business/allBusiness/types';
import auth from '@/plugins/auth'
import Table from '@/components/Table/index.vue'
import { tableTypes } from '@/components/Table/types'
import { useDictCache } from '@/hooks/web/useDict'
import CreateQuickTask from '@/components/common/createQuickTask.vue';
import { listCustomer } from "@/api/customer";
import { useUserStore } from "@/store/modules/user";
import { listDetialByCodes } from "@/api/system/dict";
import useSettingsStore from "../../../store/modules/settings";
import useTagsViewStore from "@/store/modules/tagsView";
const tagsViewStore = useTagsViewStore()
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const { queryDictDetailByCodes } = useDictCache(['sales_phase',
    'business_type', 'transaction_probability',
    'sources_of_business',
    'task_remind_type',
    'task_remind_mode',
    'task_mark_tag',
    'task_priority_grade',
    'business_stage'
])
queryDictDetailByCodes()
const dictData: any = reactive({
    remindModeData: [],
})
// listDetialByCodes(['task_remind_mode']).then((res => {
//     if(res.success) {
//         dictData.remindModeData = res.result['task_remind_mode']
//     }
// }))
// const customerOption = ref([])



const disabledFutureDates = (time) => {
    return time.getTime() > Date.now();
};
const disabledPastDates = (time) => {
    return time.getTime() < Date.now() - 86400000; // 86400000 毫秒 = 1 天
};

const allBusinessList = ref<AllBusinessVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const rate = ref(0);
const showSearch = ref(true);


const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const allBusinessFormRef = ref<ElFormInstance>();
const catchId = ref()

const initFormData: AllBusinessForm = {
    id: undefined,
    title: undefined,
    customerId: proxy?.$route.query.customerId as string,
    liaisonId: proxy?.$route.query.liaisonId as string,
    estimatedSalesAmount: undefined,
    expectedSigningDate: undefined,
    salesPhaseDictValue: undefined,
    businessTypeDictValue: undefined,
    stage: undefined,
    transactionProbabilityDictValue: '10',
    sourcesOfBusinessDictValue: undefined,
    getedDate: undefined,
    remark: undefined,
    isDelete: undefined,
    enabled: undefined,
    ownerBy: userStore.userId as number,
    hasLoss: 0,
    sort: undefined,
    initialSalesAmount: 0,
    currency: 2,
    task: {
        taskBeginTime: '',
        taskContent: '',
        isCreateTask: false,
        remindModels: ['site'],
        remindType: undefined,
        ownerBy: userStore.userId
    }
}
const validateOwnerBy = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error("拥有者不能为空"));
    } else if (typeof value !== 'string') {
        callback(new Error("拥有者必须是字符串"));
    } else {
        callback(); // 验证通过
    }
};
const data = reactive<PageData<AllBusinessForm, AllBusinessQuery>>({
    form: { ...initFormData },
    rules: {
        id: [
            { required: true, message: "商机主键不能为空", trigger: "blur" }
        ],
        title: [
            { required: true, message: "商机标题不能为空", trigger: "blur" }
        ],
        customerId: [
            { required: true, message: "关联客户不能为空", trigger: "change" }
        ],
        liaisonId: [
            { required: true, message: "主要联系人不能为空", trigger: "change" }
        ],
        estimatedSalesAmount: [
            { required: true, message: "预计销售金额不能为空", trigger: "blur" }
        ],
        expectedSigningDate: [
            { required: true, message: "预计签单日期不能为空", trigger: "change" }
        ],
        salesPhaseDictValue: [
            { required: true, message: "销售阶段不能为空", trigger: "change" }
        ],
        currency: [
            { required: true, message: "币种不能为空", trigger: "change" }
        ],
        stage: [
            { required: true, message: "销售阶段不能为空", trigger: "change" }
        ],
        businessTypeDictValue: [
            { required: true, message: "商机类型不能为空", trigger: "change" }
        ],
        transactionProbabilityDictValue: [
            { required: true, message: "成交机率不能为空", trigger: "change" }
        ],
        sourcesOfBusinessDictValue: [
            { required: true, message: "商机来源不能为空", trigger: "change" }
        ],
        getedDate: [
            { required: true, message: "获取日期不能为空", trigger: "blur" }
        ],
        remark: [
            { required: true, message: "备注信息不能为空", trigger: "blur" }
        ],

        ownerBy: [
            { required: true, message: "拥有者不能为空", trigger: ["change", "blur"] }
        ],
        'task.taskBeginTime': [
            { required: true, message: "下次跟进时间不能为空", type: 'date', trigger: "change" }
        ],
        'task.ownerBy': [
            { required: true, message: "任务跟进人不能为空", trigger: "change" }
        ],
        'task.remindType': [
            { required: true, message: "任务提醒不能为空", trigger: "change" }
        ],
        'task.taskContent': [
            { required: true, message: "任务跟进主题不能为空", trigger: "blur" }
        ],
        'task.objectiveValue': [
            { required: true, message: "任务跟进目的不能为空", trigger: "change" }
        ],

    }
});

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

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


/** 提交按钮 */
const submitForm = () => {
    allBusinessFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            let res = await addAllBusiness(form.value).finally(() => buttonLoading.value = false);
            proxy?.$modal.msgSuccess("操作成功");
            router.push(`/business_opportunity/detail?id=${res.result}&type=detail&from=allBusiness`)
        }
    });
}
// const getCustomerData = () => {
//     listCustomer({pageIndex: 1, pageSize: 999999}).then(res => {
//         if (res.success) {
//             customerOption.value = res.result.records.map((item: { customerName: string, id: number }) => {
//                 let obj = {label: item.customerName, value: item.id}
//                 return obj
//             })
//         }
//     })
// }


const getDetail = async ()=>{
    let id: string = proxy?.$route?.query?.id as string

    if(proxy?.$route.query.id ){
        if(catchId.value == id) {
            return
        }
        catchId.value = id
        loading.value = true
        tagsViewStore.editeTitle(route.path, '编辑商机')

        await getById({id}).then(res => {
            if (res.success) {
                form.value = res.result
                form.value.task= {
                    taskBeginTime: '',
                        taskContent: '',
                        remindModels: [],
                        remindType: undefined,
                        ownerBy: undefined
                }
            }
        }).finally(() => loading.value = false)
    } else {
        if(catchId.value) {
            reset()
        }
        catchId.value = undefined
        tagsViewStore.editeTitle(route.path, '添加商机')
    }

}
const getRate =  ()=>{
    getUSDtoCnyRate().then(res=>{
        rate.value = res.result
    })

}
onActivated(()=>{
    getDetail()
    // getCustomerData()
})

onMounted(() => {
    getDetail()
    getRate()
    // getCustomerData()
});
</script>

<style scoped lang="scss">
.add-area-bus .content .el-form{
    .el-row{
        width: 900px;
    }
    .el-input, :deep(.el-select){
        flex: 1;
    }
}
.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>
