<template>
    <div class="detail_area" v-loading="loadDetail">
        <div class="detail_header">
            <div class="detail_company flex">
                <div class="flex-center">
                    <div>
                        <div class="company_name">{{ detailData?.title}}</div>
                        <div class="company_user">
                            <span>关联客户：{{ detailData?.customerName }}</span>
                            <span>主要联系人：{{ detailData?.liaisonName }}</span>
                            <span>下次跟进：{{ detailData?.nextFollowUpTime }}</span>
                        </div>
                    </div>
                </div>
                <div class="header_right flex">
                    <div class="left" :class="detailData?.previousId ? '' : 'btn-grey'">
                        <el-icon @click="goPreNexDetail(detailData?.previousId)">
                            <ArrowLeft />
                        </el-icon>
                    </div>
                    <div class="right" :class="detailData?.nextId ? '' : 'btn-grey'">
                        <el-icon @click="goPreNexDetail(detailData?.nextId)">

                            <ArrowRight />
                        </el-icon>
                    </div>
                </div>
            </div>
            <div style="display: flex;justify-content: space-between">
                <div>
                    <el-dropdown @command="handleCommand"
                        :disabled="hasOrderForm || detailData?.quotationId || detailData?.hasLoss"
                        style="margin-right: 15px">
                        <el-button type="primary" :disabled="hasOrderForm">
                            {{ detailData?.stageName }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item v-for="item in business_stage" :key="item.value" :command="item.value"
                                    :disabled="item.label == '成交商机' || item.label == '产品报价'">
                                    <span> {{ item.label }}</span>
                                    <el-icon v-if="detailData?.stage == item.label" style='margin-left: 10px'><Select
                                            color="#1874ff" /></el-icon>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>

                    <el-dropdown style="margin-right: 12px;" @command="openDialog">
                        <el-button type="primary">
                            <el-icon>
                                <Plus />
                            </el-icon>添加<el-icon class="el-icon--right"><arrow-down /></el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item v-if="auth.hasPermi(`business:business:detail_add`)"
                                    command="productPrice">产品报价</el-dropdown-item>
                                <el-dropdown-item v-if="auth.hasPermi(`business:business:detail_lisaon`)"
                                    command="addConcat">联系人</el-dropdown-item>
                                <!--                                <el-dropdown-item v-if="auth.hasPermi(`business:business:detail_fee`)"-->
                                <!--                                    command="addFee">费用</el-dropdown-item>-->
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <template v-for="item in operateBtn">
                        <el-button :key="item.value" v-if="item.show" @click="openDialog(item.value)"
                            :disabled="item.disabled">{{ item.label }}</el-button>
                    </template>

                </div>
                <div>
                    <el-button :disabled="detailData?.stage == 4" v-hasPermi="[`business:detail:sjlshhx`]"
                        :type="detailData?.hasLoss ? 'success' : 'warning'" @click="updateLossStatus">{{
                        detailData?.hasLoss ? '唤醒商机' : '商机流失' }}</el-button>
                    <el-button v-hasPermi="[`business:detail:bjsj`]" @click="handleUpdate">编辑商机</el-button>
                    <el-button v-hasPermi="[`business:detail:scsj`]" @click="handleDelete">删除商机</el-button>
                </div>

            </div>
        </div>

        <div class="step" style="">
            <el-steps :active="detailData?.stage" finish-status="success" simple>
                <el-step v-for="(item, index) in business_stage" :key='index' :title="item.label" />
            </el-steps>
        </div>
        <div class="detail_main">
            <InfoMainNav :navList="navList" @change="changeTab" ref="informationRef"></InfoMainNav>
            <!-- <transition name="fade" mode="out-in">
                <section> -->
            <Information perPrefix="business" :detailData="detailData" v-if="navValue == 'infomation'">
            </Information>
            <Liaison perPrefix="business" v-if="navValue == 'liaison'" resourceType="30"
                :resourceTypeId="detailData?.id" :customerId="detailData?.customerId">
            </Liaison>
            <FollowUp perPrefix="business" v-if="navValue == 'follow'" resourceType="30"
                :resourceTypeId="detailData?.id"></FollowUp>
            <Task :isCorrelation="false" perPrefix="business" v-if="navValue == 'task'" resourceType="30"
                :resourceTypeId="detailData?.id"></Task>
            <sendRecord :customerId="detailData?.customerId" perPrefix="business" v-if="navValue == 'sendRecord'"
                resourceType="30" :resourceTypeId="detailData?.id" :customerName="detailData.customerName"
                :resourceName="detailData.title"></sendRecord>
            <resourceList perPrefix="business" v-if="navValue == 'resourceList'" resourceType="30"
                :resourceTypeId="detailData?.id" :customerId="detailData?.customerId"></resourceList>
            <operationLog perPrefix="business" v-if="navValue == 'operationLog'" resourceType="30"
                :resourceTypeId="detailData?.id"></operationLog>
            <orderForm perPrefix="business" v-if="navValue == 'order'" :businessId="detailData?.id"></orderForm>
            <QuotationList perPrefix="business" ref="quotationListRef" v-if="navValue == 'quotation'" resourceType="30"
                :resourceTypeId="detailData?.id"></QuotationList>
            <CostList perPrefix="business" v-if="navValue == 'cost'" resourceType="30"
                :customerId="detailData?.customerId" :resourceTypeId="detailData?.id"></CostList>
            <!-- </section>
            </transition> -->
        </div>

    </div>
    <el-dialog :title="detailData?.hasLoss ? '唤醒商机' : '流失商机'" v-model="lostVisible" width="600px">
        <el-form ref="lossFormRef" :model="lostForm" :rules="lossRules" label-width="120px">
            <el-form-item v-if="!detailData?.hasLoss" label="流失原因：" prop="lossReasonDictValue">
                <SelectDict v-model="lostForm.lossReasonDictValue" placeholder="请选择流失原因" dictCode="loss_reason">
                </SelectDict>
            </el-form-item>
            <el-form-item v-else label="唤醒原因：" prop="awakenReasonDictValue">
                <SelectDict v-model="lostForm.awakenReasonDictValue" placeholder="请选择唤醒原因" dictCode="awaken_reason">
                </SelectDict>
            </el-form-item>
            <el-form-item v-if="detailData?.hasLoss" label="备注：" prop="awakenRemark">
                <el-input v-model="lostForm.awakenRemark" type="textarea" :rows="4" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item v-else label="备注：" prop="lossRemark">
                <el-input v-model="lostForm.lossRemark" type="textarea" :rows="4" placeholder="请输入内容" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="lossCancel">取消</el-button>
                <el-button :loading="lossButtonLoading" type="primary" @click="submitFormLoss">提交</el-button>
            </div>
        </template>
    </el-dialog>
    <GetProductPrice ref="getProductPriceRef" @ok="refreshPriceData"></GetProductPrice>
    <!-- 按钮弹窗 -->
    <component v-bind="{ isCorrelation: false }" :is="dialogComponent" @onOk="onOk" @refresh="onOk"
        :ref="($event: any) => setItemRef($event)">
    </component>

</template>

<script setup lang="ts">

import Follow from '@/components/Follow/index.vue'
import CreateTask from '@/components/common/createTask.vue'
import AddFollow from '@/components/Follow/add.vue'
import InfoMainNav from '@/components/common/InfoMainNav.vue'
import transferClue from '@/components/common/transferClue.vue'
import ConvertCustomer from '@/components/common/convertCustomer.vue'
import Addcontact from './Addcontact.vue'
import addCollaborate from '@/components/common/addCollaborate.vue'
import turnBussnese from './TurnBus.vue'
import GetProductPrice from './GetProductPrice.vue'
import Information from './Information.vue'
import CostList from './CostList.vue'
import FollowUp from '@/components/detailCommon/followUp.vue'
import Liaison from '@/components/detailCommon/liaison.vue'
import sendRecord from '@/components/detailCommon/sendRecord.vue'
import resourceList from '@/components/detailCommon/resourceList.vue'
import operationLog from '@/components/detailCommon/operationLog.vue'
import QuotationList from './QuotationList.vue'
import orderForm from '@/components/detailCommon/orderForm.vue'
import {
    addAllBusiness,
    changeStage,
    delAllBusiness,
    getById,
    getPreNexById,
    lostBusiness
} from '@/api/business/allBusiness';
import {AllBusinessForm, AllBusinessVO, LostBusinessDTO} from '@/api/business/allBusiness/types';
import {useDictCache} from '@/hooks/web/useDict'
import {useDictStore} from "@/store/modules/dict";
import {storeToRefs} from "pinia";
import {getCustomer} from "@/api/customer";
import {onMounted} from "vue";
import {deleteComment} from "@/api/public";
import auth from '@/plugins/auth'
import {liaisonResourceAdd} from "@/api/customer/liaison";
import useAppStore from '@/store/modules/app';
import useSettingsStore from '@/store/modules/settings'
const useSetStore = useSettingsStore();
const appStore = useAppStore();
const toggleSideBar = () => {
    appStore.closeSideBar(false);
}

const router = useRouter();
let queryData: any = router.currentRoute.value.query

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {queryDictDetailByCodes} = useDictCache(['business_stage','sales_phase','loss_reason','awaken_reason', 'business_type', 'transaction_probability', 'sources_of_business', 'task_remind_type', 'task_remind_mode'])
queryDictDetailByCodes()
const useDict = useDictStore()

const stepIndex = computed(()=>{
    let data = useDict.getDict('business_stage')
    if(!data || data.length == 0)return
    return data.findIndex(i=>i.value == detailData?.value?.salesPhaseDictValue)

})

const salesPhase = computed(() => {
    return useDict.getDict('sales_phase')
})
const business_stage = computed(() => {
    return useDict.getDict('business_stage')
})

const getProductPriceRef = ref()
const perPrefix = ref(queryData.from)
const quotationListRef = ref()

const navList = [
    {label: '概况信息', value: 'infomation', show: auth.hasPermi('business:detail:tab_gkxx')},
    {label: '联系人', value: 'liaison' , show: auth.hasPermi('business:detail:tab_lxr')},
    {label: '跟进记录', value: 'follow' , show: auth.hasPermi('business:detail:tab_gjjl')},
    {label: '任务记录', value: 'task' , show: auth.hasPermi('business:detail:tab_rwjl')},
    {label: '关联订单', value: 'order' , show: auth.hasPermi('business:detail:tab_gldd')},
    {label: '产品报价', value: 'quotation', show: auth.hasPermi('business:detail:tab_cpbj') },
    {label: '寄样记录', value: 'sendRecord' , show: auth.hasPermi('business:detail:tab_jyjl')},
    // {label: '费用记录', value: 'cost' , show: auth.hasPermi('business:detail:tab_fyjl')},
    {label: '相关附件', value: 'resourceList' , show: auth.hasPermi('business:detail:tab_xgfj')},
    {label: '操作日志', value: 'operationLog' , show: auth.hasPermi('business:detail:tab_czrz')}
];

const navValue = ref<string>('infomation')
const changeTab = (value: string) => {
    navValue.value = value
}

const navIndex = ref<number>(0)
const onlyFollow = ref<Boolean>(false)
const loadDetail = ref<boolean>(false)


// 获取线索详情数据
const detailData = ref<AllBusinessVO| null>(null)


//更改销售阶段
const handleCommand = async (command: string) => {
    let param:AllBusinessForm = {
        id: detailData?.value?.id,
        stage: command
    }
    await changeStage(param).finally(() => {
        getDetailData()
    });

}
//流失商机
const lostVisible = ref(false)
const lossButtonLoading = ref(false)
const lossCancel = () => {
    lostVisible.value = false
    resetLoss()
}
const updateLossStatus = () => {
    lostVisible.value = true
}
const lostForm = reactive<LostBusinessDTO>({
    id:  queryData.id,
    lossReasonDictValue: '',
    awakenReasonDictValue: '',
    hasLoss: undefined
})
const lossRules = reactive({
    lossReasonDictValue:[{required: true, message: '请选择流失原因', trigger: 'change'}],
    awakenReasonDictValue:[{required: true, message: '请选择唤醒原因', trigger: 'change'}],
    awakenRemark:[{required: true, message: '请输入唤醒备注', trigger: 'blur'}],
    lossRemark:[{required: true, message: '请输入流失备注', trigger: 'blur'}],
})

/** 表单重置 */
const resetLoss = () => {
    lossButtonLoading.value = false
    Object.assign(lostForm, {
        id:  queryData.id,
        lossReasonDictValue: '',
        awakenReasonDictValue: '',
        hasLoss: ''
    })
    lossFormRef.value?.resetFields();
}
const lossFormRef = ref()
const submitFormLoss = async () => {
    lossButtonLoading.value = true

    lossFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            lostForm.hasLoss = detailData.value?.hasLoss == 1 ? 0 : 1
            let res = await lostBusiness(lostForm)
            resetLoss()
            getDetailData()
            lostVisible.value = false
        }

        lossButtonLoading.value = false
    })

}

const getDetailData = () => {
    loadDetail.value = true
    let param: any = {
        id: queryData.id,
        preNextScopeMenuId: queryData.scopMenuId
    }
    getById(param).then(res => {
        if (res.success) {
            detailData.value = res.result || {} as AllBusinessVO;
        }
        loadDetail.value = false

        useSetStore.setTitle(detailData.value.title)
    })
}
const init = async ()=>{
    getDetailData()
}

const route = useRoute();
watch(route, (newRoute, oldRoute) => {
    let queryDataNew: any = router.currentRoute.value.query
    if (queryDataNew.id) {
        queryData.id = queryDataNew.id
        init()
    }
});


const informationRef = ref()
const goPreNexDetail = (id:string)=>{
    if (!id) return
    navValue.value = 'infomation'
    informationRef.value.resetNavList()
    setTimeout(() => {
        router.push(`./detail?id=${id}&type=detail&scopMenuId=${queryData.scopMenuId}`)
    }, 100)

}
const hasOrderForm = computed(() => {
    return detailData.value?.hasOrderForm || detailData.value?.hasLoss == 1 || detailData.value?.stage == 4
})
const hasLossForm = computed(() => {
    return !detailData.value?.hasLoss
})


// 操作按钮弹窗
let operateBtn = ref([
    // { label: '初步洽谈', value: 'intention' },
    { label: '写新跟进', value: 'AddFollow', show: auth.hasPermi('business:detail:xxgj'), disabled: false},
    { label: '新建任务', value: 'task', show: auth.hasPermi('business:detail:xjrw'), disabled: false },
    { label: '转为订单', value: 'transforOrder', show: auth.hasPermi('business:detail:zwdd'), disabled: hasOrderForm  },
    { label: '转移商机', value: 'turnBussnese', show: auth.hasPermi('business:detail:zysj'), disabled: false },
    { label: '添加协作', value: 'addCollaborate', show: auth.hasPermi('business:detail:tjxz'), disabled: false },
])
const dialogComponent = shallowRef()
const dialogRef = ref()
const setItemRef = (el: any) => {
    if (el) {
        dialogRef.value = el
    }
}

/** 修改按钮操作 */
const handleUpdate = async () => {
    router.push('./addbus?id=' + detailData.value?.id)
}

/** 删除操作 */
const handleDelete = async () => {
    if(!!!detailData.value) return

    ElMessageBox.confirm(
        '是否确认删除当前商机吗？',
        '确认提示',
        { type: 'warning', confirmButtonText: '提交' }
    ).then(() => {
        delAllBusiness(detailData?.value?.id).then(res => {
            if(res.success) {
                ElMessage.success('删除成功')
                router.push('./allBusiness')
            }else{
                ElMessage.error('删除失败')
            }
        })
    }).catch(() => {})
}

const refreshPriceData = () => {
    quotationListRef.value.getQuotationList()
}

const onOk= (type: string) => {
    if( 'detailTurnBussnese' == type) {
        router.push(`/business_opportunity/${queryData.from}`)
        return
    }

   if(type == 'addConcat' || 'addCollaborate' == type  ) {
       getDetailData()
   }
}

const openDialog = (val: string) => {

    switch (val) {
        case 'addConcat': // 转为客户
            dialogComponent.value = Addcontact
            break;
        case 'AddFollow': // 写新跟进

            dialogComponent.value = AddFollow
            break;
        case 'task': // 新建任务
            dialogComponent.value = CreateTask
            break;
        case 'addFee': // 新建任务
            // dialogComponent.value = CreateTask
            break;
        case 'addCollaborate': // 添加协作
            dialogComponent.value = addCollaborate
            break;
        case 'turnBussnese': // 转移商机

            dialogComponent.value = transferClue
            break;
        case 'editClue': // 编辑商机
            router.push('./add?type=eite')
            break;
        case 'transforOrder': // 编辑线索
            router.push('/order/add?type=add&businessId=' + detailData.value?.id + '&customerId=' + detailData.value.customerId)
            break;
        case 'productPrice': // 编辑线索
            getProductPriceRef.value.open(detailData.value?.id, detailData.value.customerId)
            break;
        case 'delClue': // 删除线索
            ElMessageBox.confirm(
                '是否确认删除当前数据？',
                '确认提示',
                { type: 'warning', confirmButtonText: '提交' }
            ).then(() => {
                // delCustomer(id).then((res: AxiosResponse) => {
                //     if(res.success) {
                //         ElMessage.success('删除成功')
                //         getData()
                //     }else{
                //         ElMessage.error('删除失败')
                //     }
                // })
            }).catch(() => { })
            break;
    }
    if(val == 'addFee' || val == 'convert') {
        proxy?.$modal.msgWarning("功能暂未开放！敬请期待");
        return
    }
    if (['AddFollow', 'task', 'addConcat', 'addCollaborate', 'turnBussnese'].includes(val)) {
        nextTick(() => {
            if(val == 'addCollaborate'){
                dialogRef.value.open({
                    userIdList: detailData.value.collaborator ? detailData.value.collaborator.split(',') : [],
                    resourceType:30,
                    resourceIdList:[detailData?.value?.id]
                })
            }
            if(val=='turnBussnese') {
                dialogRef.value.open({
                    resourceType:30,
                    typeName: '商机',
                    idList:[detailData?.value?.id],
                    tag: 'detailTurnBussnese'
                })
                return
            }
            if(val == 'addConcat') {
                dialogRef.value.open(detailData?.value?.customerId, detailData?.value?.id, detailData?.value?.title)
                return
            }
            if(val == 'task') {

                dialogRef.value.open({
                    type: 'add',
                    obj: {
                        resourceType: '30',
                        resourceTypeId: detailData?.value?.id
                    }

                })
                return
            }
            if(val == 'AddFollow') {
                let param = {
                    type: 'add',
                    customerId: detailData?.value?.customerId,
                    customerName: detailData?.value?.customerName,
                    resourceType: 30,
                    resourceTypeId: detailData?.value?.id,
                    resourceName: detailData?.value?.title,
                    resourceStageName: detailData?.value?.stageName,
                    resourceStageDictValue: detailData?.value?.stage
                }
                dialogRef.value.open(param)
                return
            }
            // dialogRef.value.open()
        })
    }

}
onMounted(()=>{
    init()
    toggleSideBar()

})
</script>

<style lang="scss" scoped>
.btn-grey{
    cursor: no-drop;
    opacity: 0.5;
}
.step{
    width: 100%;
    padding:15px 20px;
    background: #fff;
    margin-top: 15px;
}
</style>
