<template>
    <div class="detail_area">
        <div class="detail_header">
            <div class="detail_company flex">
                <div class="flex-center">
                    <div>
                        <div class="company_name">{{ showDetailData?.title }}</div>
                        <div class="company_user">
                            <span>关联客户：{{ showDetailData?.customerName }}</span>
                            <span>关联商机：{{ showDetailData?.businessName }}</span>
                            <span>下次跟进：{{ showDetailData?.nextFollowUpTime }}</span>
                        </div>
                    </div>
                </div>
                <div class="header_right flex" v-if="queryData.scopeMenuId">
                    <div class="left" :class="orderDetail?.previousId?'':'btn-grey'" @click="changePage(orderDetail?.previousId)">
                        <el-icon><ArrowLeft /></el-icon>
                    </div>
                    <div class="right" :class="orderDetail?.nextId?'':'btn-grey'" @click="changePage(orderDetail?.nextId)">
                        <el-icon><ArrowRight /></el-icon>
                    </div>
                </div>
            </div>
            <div>
                <!-- <el-dropdown style="margin-right: 12px;">
                    <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>
                            <template v-for="item in dropdownItem">
                                <el-dropdown-item @click="openDialog(item.value)" v-if="item.show">
                                    {{ item.label }}
                                </el-dropdown-item>
                            </template>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown> -->
                <template v-for="item in operateBtn" :key="item.value">
                    <el-button v-if="item.show" @click="openDialog(item.value)">{{ item.label }}</el-button>
                </template>
            </div>
        </div>
        <div class="detail_main">
            <InfoMainNav :navList="navList" @change="changeTab" ref="informationRef"></InfoMainNav>
            <div class="nav_detail" v-if="navValue == 'infomation'">
                <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">基本信息</span>
                    </div>
                    <div class="form_area flex">
                        <div class="form_item">
                            <div class="flex">
                                <div class="label">订单标题：</div>
                                <div class="value">{{ showDetailData?.title }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">关联商机：</div>
                                <div class="value">
                                    <a style="color: #1874FF" v-if="orderDetail?.businessId"  target="_blank"
                                       :href="`/business_opportunity/detail?id=${orderDetail?.businessId}`">
                                        {{ orderDetail?.businessName }}</a>
                                    <span v-else> --</span>
<!--                                    {{ showDetailData?.businessName }}-->
                                </div>
                            </div>
                            <div class="flex">
                                <div class="label">订单总金额：</div>
                                <div class="value">{{ quotationData?.totalOrderAmt?.toFixed(2) }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">订单类型：</div>
                                <div class="value">{{ showDetailData?.orderTypeName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">预计发货日期：</div>
                                <div class="value">{{ showDetailData?.expectedDeliveryDate }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">我方签约人：</div>
                                <div class="value">{{ showDetailData?.ourSignatory }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">归属人员：</div>
                                <div class="value">{{ showDetailData?.ownerByName }}</div>
                            </div>
                        </div>
                        <div class="form_item">
                            <div class="flex">
                                <div class="label">关联客户：</div>
                                <div class="value">
                                    <a style="color: #1874FF" v-if="orderDetail?.customerId" type="primary" target="_blank"
                                                       :href="`/customer/customerDetail?id=${orderDetail?.customerId}`">
                                        {{  orderDetail?.customerName }}</a>
                                    <span v-else>--</span>
                                </div>
                            </div>
                            <div class="flex">
                                <div class="label">签单日期：</div>
                                <div class="value">{{ showDetailData?.signingDate }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">预计生产日期：</div>
                                <div class="value">{{ showDetailData?.expectedProductionDate }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">客户签约人：</div>
                                <div class="value">{{ showDetailData?.customerSignatory }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">付款币种：</div>
                                <div class="value">{{ showDetailData?.currencyName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">备注信息：</div>
                                <div class="value">{{ showDetailData?.remark }}</div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">回款信息</span>
                    </div>
                    <div class="form_area flex">
                        <div class="form_item">
                            <div class="flex">
                                <div class="label">回款计划：</div>
                                <div class="value"></div>
                            </div>
                            <div class="flex">
                                <div class="label">已完成计划：</div>
                                <div class="value"></div>
                            </div>
                            <div class="flex">
                                <div class="label">已回款金额：</div>
                                <div class="value"></div>
                            </div>
                            <div class="flex">
                                <div class="label">已开票金额</div>
                                <div class="value"></div>
                            </div>
                        </div>
                        <div class="form_item">
                            <div class="flex">
                                <div class="label">回款截止日期：</div>
                                <div class="value"></div>
                            </div>
                            <div class="flex">
                                <div class="label">已逾期计划：</div>
                                <div class="value"></div>
                            </div>
                            <div class="flex">
                                <div class="label">未回款金额：</div>
                                <div class="value"></div>
                            </div>
                            <div class="flex">
                                <div class="label">未开票金额：</div>
                                <div class="value"></div>
                            </div>
                        </div>
                    </div>
                </div> -->
                <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">系统信息</span>
                    </div>
                    <div class="form_area flex">
                        <div class="form_item">
                            <div class="flex">
                                <div class="label">系统编号：</div>
                                <div class="value">{{ showDetailData?.id }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">所属部门：</div>
                                <div class="value">{{ showDetailData?.deptName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">前归属人：</div>
                                <div class="value">{{ showDetailData?.formerOwnerByName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">创建时间：</div>
                                <div class="value">{{ showDetailData?.createTime }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">最后跟进：</div>
                                <div class="value">{{ showDetailData?.lastFollowUpTime }}</div>
                            </div>
                        </div>
                        <div class="form_item">
                            <div class="flex">
                                <div class="label">协作人员：</div>
                                <div class="value">{{ showDetailData?.collaboratorName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">创建人员：</div>
                                <div class="value">{{ showDetailData?.createByName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">前所属部门：</div>
                                <div class="value">{{ showDetailData?.formerDeptName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">更新时间：</div>
                                <div class="value">{{ showDetailData?.updateTime }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">下次跟进：</div>
                                <div class="value">{{ showDetailData?.nextFollowUpTime }}</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">订单动态</span>
                        <span class="flex-center">
                            <el-checkbox v-model="onlyFollow" size="large" />
                            <span style="margin: 0 16px 0 4px;">只看跟进</span>
                            <el-button type="primary" v-if="auth.hasPermi('orderForm:detail:xxgj')" @click="openDialog('AddFollow')">写跟进</el-button>
                        </span>
                    </div>
                    <div>
                        <Follow :onlyShowFollow="onlyFollow" :btnRole='roleBtn' :followParams="{ resourceType: '40', resourceTypeId: queryData.id }" :showAll="false"></Follow>
                    </div>
                </div>
            </div>
            <component :is="navComponent" v-bind="navProps"></component>
        </div>
    </div>
    <!-- 按钮弹窗 -->
    <component :is="dialogComponent" :ref="($event: any) => setItemRef($event)" v-bind="componentProps"></component>
</template>

<script setup lang="ts">
import { getOrderFormPreNext, delOrderForm } from '@/api/orderForm';
import { OrderFormVO } from '@/api/orderForm/types';
import InfoMainNav from '@/components/common/InfoMainNav.vue'
import Task from '@/components/detailCommon/task.vue'
import FollowUp from '@/components/detailCommon/followUp.vue'
import WorkOrder from '@/components/detailCommon/workOrder.vue'
import OperationLog from '@/components/detailCommon/operationLog.vue'
import SendRecord from '@/components/detailCommon/sendRecord.vue'
import ResourceList from '@/components/detailCommon/resourceList.vue'
import Follow from '@/components/Follow/index.vue'
import CreateTask from '@/components/common/createTask.vue'
import AddFollow from '@/components/Follow/add.vue'
import TransferClue from '@/components/common/transferClue.vue'
import AddCollaborate from '@/components/common/addCollaborate.vue'
import AddOrder from '@/components/common/addOrder.vue';
import QuotationList from '@/modules/sales/views/business/component/QuotationList.vue'
import { useTagsViewStore } from '@/store/modules/tagsView';
import { getDetail } from "@/api/product";
import { formateNullFieldData } from '@/api/customer';
import auth from '@/plugins/auth'
import useSettingsStore from '@/store/modules/settings'

const onlyFollow = ref<boolean>(false)
const navList = [
    { label: '概况信息', value: 'infomation', show: auth.hasPermi('orderForm:detail:tab_gkxx') },
    { label: '跟进记录', value: 'follow', show: auth.hasPermi('orderForm:detail:tab_gjjl'), components: FollowUp },
    { label: '任务记录', value: 'task', show: auth.hasPermi('orderForm:detail:tab_rwjl'), components: Task },
    // { label: '工单记录', value: 'order', show: auth.hasPermi('orderForm:detail:tab_gdjl'), components: WorkOrder },
    { label: '产品报价', value: 'quotation', show: auth.hasPermi('orderForm:detail:tab_cpbj'), components: QuotationList },
    { label: '寄样记录', value: 'sendRecord', show: auth.hasPermi('orderForm:detail:tab_jyjl'), components: SendRecord },
    // { label: '回款记录', value: '' },
    // { label: '发票记录', value: '' },
    // { label: '退款记录', value: '' },
    // { label: '费用记录', value: '' },
    { label: '相关附件', value: 'resource', show: auth.hasPermi('orderForm:detail:tab_xgfj'), components: ResourceList },
    { label: '操作日志', value: 'operationLog', show: auth.hasPermi('orderForm:detail:tab_czrz'), components: OperationLog }
];

const roleBtn = ref([
    { type: 'commit', hasPermi: `orderForm:detail:tab_gjjl_tj` },
    { type: 'detail', hasPermi: `orderForm:detail:tab_gjjl_xq` },
    { type: 'remove', hasPermi: `orderForm:detail:tab_gjjl_sc` },
    {type: 'edit', hasPermi: `orderForm:detail:tab_gjjl_bj`},
])

const router = useRouter();
let queryData: { id?: number, scopeMenuId?: string | number } = router.currentRoute.value.query
// 获取订单详情
const orderDetail = ref<OrderFormVO>()
const showDetailData = ref<OrderFormVO>()
const quotationData = ref()
const useSetStore = useSettingsStore()
const getDetailData = () => {
    getOrderFormPreNext(queryData.id, queryData.scopeMenuId).then(res => {
        if (res.success) {
            showDetailData.value = formateNullFieldData(JSON.parse(JSON.stringify(res.result)))
            orderDetail.value = res.result;
            getDetail({ orderFormId: queryData.id }).then(res => {
                quotationData.value = res.result
            })
            useSetStore.setTitle(orderDetail.value.title)
        }

    })
}
if (queryData.id) {
    getDetailData()
}

interface navPropsType {
    resourceType: string,
    resourceTypeId: string | number,
    customerId?: string | number,
    perPrefix: string,
    customerName?: string,
    resourceName?: string
}
const navValue = ref<string>('infomation')
const navComponent = shallowRef()
const navProps = ref<navPropsType>({ resourceType: '40', resourceTypeId: queryData.id, perPrefix: 'orderForm' })
const changeTab = (value: string) => {
    navValue.value = value
    navComponent.value = navList.find(a => a.value == value)?.components
    navProps.value = { resourceType: '40', resourceTypeId: queryData.id, perPrefix: 'orderForm' }
    if(value == 'sendRecord' || value == 'resource') {
        navProps.value.customerId = orderDetail.value.customerId
    }
    if(value == 'sendRecord') {
        navProps.value.customerName = orderDetail.value.customerName
        navProps.value.resourceName = orderDetail.value.title
    }
}

// 操作按钮弹窗
let dropdownItem = [
    { label: '工单', value: 'workOrder', show: auth.hasPermi('orderForm:detail:tjgd') },
    // { label: '回款', value: '' },
    // { label: '发票', value: '' },
    // { label: '费用', value: '' },
    // { label: '退款', value: '' },
]
let operateBtn = [
    { label: '写新跟进', value: 'AddFollow', show: auth.hasPermi('orderForm:detail:xxgj') },
    { label: '新建任务', value: 'task', show: auth.hasPermi('orderForm:detail:xjrw') },
    { label: '转移订单', value: 'transfer', show: auth.hasPermi('orderForm:detail:zydd') },
    { label: '添加协作', value: 'collaborate', show: auth.hasPermi('orderForm:detail:tjxz') },
    { label: '编辑订单', value: 'edit', show: auth.hasPermi('orderForm:detail:bjdd') },
    { label: '删除订单', value: 'delete', show: auth.hasPermi('orderForm:detail:scdd') },
]
const dialogComponent = shallowRef()
const componentProps = shallowRef()
const dialogRef = ref()
const setItemRef = (el: any) => {
    if (el) {
        dialogRef.value = el
    }
}
const openDialog = (val: string) => {
    if (!val || val == 'email') {
        return false
    }
    let query = {}
    switch (val) {
        case 'AddFollow': // 写新更进
            dialogComponent.value = AddFollow
            query = {
                type: 'add',
                resourceType: '40',
                resourceTypeId: queryData.id,
                resourceName: orderDetail.value?.title,
                customerId: orderDetail.value?.customerId,
                customerName: orderDetail.value?.customerName
            }
            break;
        case 'task': // 新建任务
            dialogComponent.value = CreateTask
            componentProps.value = { isCorrelation: false }
            query = { type: 'add', obj: { resourceType: '40', resourceTypeId: queryData.id } }
            break;
        case 'transfer': // 转移订单
            dialogComponent.value = TransferClue
            query = {
                resourceType: '40',
                typeName: '订单',
                idList: [queryData.id]
            }
            break;
        case 'collaborate': // 添加协作
            dialogComponent.value = AddCollaborate
            query = {
				resourceType: 40,
				resourceIdList: [queryData.id]
			}
            break;
        case 'workOrder': // 添加工单
            dialogComponent.value = AddOrder
            query = {
                type: 'add',
                orderFormId: queryData.id
            }
            break;
        case 'edit': // 编辑订单
            router.push('../order/add?type=edit&id=' + queryData.id)
            break;
        case 'delete': // 删除订单
            ElMessageBox.confirm(
                '是否确认删除当前数据？',
                '确认提示',
                { type: 'warning' }
            ).then(() => {
                delOrderForm(queryData.id).then(res => {
                    if(res.success) {
                        ElMessage.success('删除成功')
                        router.go(-1)
                        useTagsViewStore().delView(router.currentRoute.value)
                    }else{
                        ElMessage.error('删除失败')
                    }
                })
            }).catch(() => { })
            break;
    }
    if(!['edit', 'delete'].includes(val)) {
        nextTick(() => {
            dialogRef.value.open(query)
        })
    }
}

// 详情切换
const informationRef = ref()
const changePage = (id?: string | number) => {
    if(id){
        router.replace('./detail?id=' + id + '&scopeMenuId=' + queryData.scopeMenuId)
    }
    changeTab('infomation')
    informationRef.value.resetNavList()
}
const route = useRoute();
watch(route, (newRoute, oldRoute) => {
    let queryDataNew: any = router.currentRoute.value.query
    if (queryDataNew.id) {
        queryData.id = queryDataNew.id
        getDetailData()
    }
});
</script>
