<template>
    <div class="information pl-4 pr-4 pt-3 pb-3">
        <div class="flex justify-between">
            <div class="title">基本信息</div>
            <div>
                <el-button type="primary" @click="associateContact()" v-if="!information.contactsId">关联联系人</el-button>
                <el-button type="primary" @click="claimBusiness()" v-if="!information.inchargerId">认领</el-button>
                <el-button type="primary" @click="showVisible('transferBusinessVisible')"
                    v-if="information.inchargerId">转移</el-button>
                <el-button type="primary" v-permission="['businessAddAnEdit']" @click="showVisible('editBusinessVisible')">编辑</el-button>
            </div>
        </div>
        <div class="form flex flex-wrap justify-between">
            <div class="formItem flex pt-3 pb-1">
                <div class="w-20 text-right text-gray-500">商机名称：</div>
                <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1" v-ellipsis-tooltip>{{ information.name }}</div>
            </div>
            <div class="formItem flex pt-3 pb-1">
                <div class="w-22 text-right text-gray-500">客户名称：</div>
                <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1" v-ellipsis-tooltip>{{ information.customerName }}
                </div>
            </div>
            <div class="formItem flex pt-3 pb-1">
                <div class="w-22 text-right text-gray-500">联系人：</div>
                <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1">
                    {{ information.contactsName }}
                </div>
            </div>
            <div class="formItem flex pt-3 pb-1">
                <div class="w-22 text-right text-gray-500">商机金额：</div>
                <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1" v-ellipsis-tooltip>{{ information.amountOfMoney || 0
                }} 元</div>
            </div>
            <div class="formItem flex pt-3 pb-1">
                <div class="w-22 text-right text-gray-500">负责人：</div>
                <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1">
                    <TextTranslation translationTypes="userName" :translationValue="information.inchargerName"></TextTranslation>
                </div>
            </div>
            <div class="formItem flex pt-3 pb-1">
                <div class="w-22 text-right text-gray-500">预计成交日期：</div>
                <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1">{{
                    information.expectedTransactionDate }}</div>
            </div>
            <div class="formItem flex pt-3 pb-1">
                <div class="w-22 text-right text-gray-500">创建人：</div>
                <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1">
                    <TextTranslation translationTypes="userName" :translationValue="information.creatorName"></TextTranslation>
                </div>
            </div>
            <div class="formItem flex pt-3 pb-1">
                <div class="w-22 text-right text-gray-500">创建时间：</div>
                <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1">{{
                    information.createTime }}</div>
            </div>
            <div class="formItem flex pt-3 pb-1" style="width: 100%;">
                <div class="w-22 text-right text-gray-500">备注：</div>
                <div class="flex-1 ml-1 text " v-ellipsis-tooltip>
                    {{ information.remark }}
                </div>
            </div>
        </div>

        <!-- 编辑弹窗 -->
        <el-dialog v-model="allVisible.editBusinessVisible" width="1000" :show-close="false" top="10vh">
            <template #header="{ close, titleId, titleClass }">
                <div class="flex justify-between items-center border-b pb-3 dialog-header">
                    <h4 :id="titleId">{{ '编辑产品' }}</h4>
                    <div>
                        <el-button type="primary" @click="editBusiness()"
                            :loading="allLoading.businessSaveLading">保存</el-button>
                        <el-button @click="closeVisible('editBusinessVisible')">取消</el-button>
                    </div>
                </div>
            </template>
            <div class="h-[60vh] overflow-y-auto scroll-bar pt-3">
                <GenerateForm ref="generateForm" :data="generateFormData" :value="generateFormValue" />
            </div>
        </el-dialog>

        <!-- 转移 -->
        <el-dialog v-model="allVisible.transferBusinessVisible" width="600" :show-close="false" top="10vh">
            <template #header="{ close, titleId, titleClass }">
                <div class="flex justify-between items-center border-b pb-3 dialog-header">
                    <h4 :id="titleId">{{ '转移商机' }}</h4>
                    <div>
                        <el-button type="primary" :loading="allLoading.transferBusinessLoading"
                            @click="transferBusiness()">转移</el-button>
                        <el-button @click="allVisible.transferBusinessVisible = false">取消</el-button>
                    </div>
                </div>
            </template>
            <div class="scroll-bar m-6">
                <div class="flex mb-4">
                    <div class="w-20 flex items-center justify-end pr-4">转移至:</div>
                    <!-- <el-select v-model="transferValue" placeholder="请选择" class="flex1">
                        <el-option v-for="item in transferOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select> -->
                    <personnel-search v-model="transferValue" :size="''" placeholder="请选择"></personnel-search>
                </div>
                <div class="pl-3 text-[#e94a4a]">转移后，将看不到此商机</div>
            </div>
        </el-dialog>

        <!-- 关联 -->
        <el-dialog v-model="allVisible.saveContactVisible" width="600" :show-close="false" top="10vh">
            <template #header="{ close, titleId, titleClass }">
                <div class="flex justify-between items-center border-b pb-3 dialog-header">
                    <h4 :id="titleId">{{ '关联联系人' }}</h4>
                    <div>
                        <el-button type="primary" :loading="allLoading.saveContactLoading"
                            @click="saveAssociateContact()">关联</el-button>
                        <el-button @click="allVisible.saveContactVisible = false">取消</el-button>
                    </div>
                </div>
            </template>
            <div class="scroll-bar m-6">
                <div class="flex mb-4">
                    <div class="w-20 flex items-center justify-end pr-4">联系人:</div>
                    <el-select v-model="contactsId" placeholder="请选择" class="flex1">
                        <el-option v-for="item in contactsList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, defineExpose, inject, watchEffect } from 'vue'
import { GenerateForm } from '@zmjs/form-design';
import { get, post } from '@/utils/request';
import { BATCHTRANSFER, GETGENERATEFOEM, GETPERSONNEL, UPDATEINSET, URL_SAVECONTACT } from '../api';
import { formatDate, formatDateTime } from '@/utils/times';
import { confirmAction } from '@/utils/tools';
import { useStore } from '@/store/index'
import { URL_GETALL } from '@/pages/contacts/api';
import personnelSearch from '@/components/translationComponent/personnelSearch/personnelSearch.vue';

const { userInfo } = useStore()
const globalPopup = inject<GlobalPopup>('globalPopup')
const emits = defineEmits(['refreshData']);
const props = defineProps<{
    information: any
}>()

const information = ref<any>({})
const transferValue = ref('')
const transferOptions = ref<personnelInterface[]>([])
const generateFormValue = ref({})
const generateForm = ref<typeof GenerateForm>() // 自定义表单dom
const productTableListValue = ref<any[]>([])
const contactsId = ref('')
const contactsList = ref<optionType[]>([])
const allVisible = reactive({
    editBusinessVisible: false,
    transferBusinessVisible: false,
    saveContactVisible: false
})
const allLoading = reactive({
    editBusinessLoading: false,
    businessSaveLading: false,
    transferBusinessLoading: false,
    saveContactLoading: false
})
const generateFormData = ref({
    config: {},
    list: []
}) // 自定义表单数据

function associateContact() {
    contactsId.value = ''
    getContactList()
    showVisible('saveContactVisible')
}

function getContactList() {
    post(URL_GETALL, { customerId: information.value.customerId }).then(({ data }) => {
        contactsList.value = data.map((item: any) => {
            return { value: item.id, label: item.name }
        })
    })
}

function saveAssociateContact() {
    allLoading.saveContactLoading = false
    post(URL_SAVECONTACT, { id: information.value.id, contactsId: contactsId.value }).then(() => {
        globalPopup?.showSuccess('关联成功')
        closeVisible('saveContactVisible')
        emits('refreshData')
    }).finally(() => {
        allLoading.saveContactLoading = false
    })
}

function transferBusiness() {
    const ids = information.value?.id
    const inchargerId = information.value?.inchargerName ? transferValue.value : userInfo.id
    if (!inchargerId) {
        globalPopup?.showWarning('请选择转移的人员')
        return
    }
    allLoading.transferBusinessLoading = true
    post(BATCHTRANSFER, { ids, inchargerId }).then((res) => {
        if (res.code == 'ok') {
            globalPopup?.showSuccess('操作成功')
            allVisible.transferBusinessVisible = false
            emits('refreshData')
        }
    }).finally(() => {
        allLoading.transferBusinessLoading = false
    })
}

function claimBusiness() {
    confirmAction(`确定认领【${information.value.name}】商机吗？`).then(() => {
        transferBusiness()
    })
}

function editBusiness() {
    generateForm.value?.getData().then((res: any) => {
        let formVal = {
            id: information.value.id,
            ...res,
            expectedTransactionDate: res.expectedTransactionDate ? formatDate(new Date(res.expectedTransactionDate)) : '',
            businessItemProductList: JSON.stringify(productTableListValue.value)
        }
        allLoading.businessSaveLading = true
        post(UPDATEINSET, { ...formVal }).then((_res) => {
            allVisible.editBusinessVisible = false
            globalPopup?.showSuccess('保存成功')
            emits('refreshData')
        }).finally(() => {
            allLoading.businessSaveLading = false
        })
    }).catch((_err: any) => {
        console.log(_err)
        globalPopup?.showError('请填写完整')
    })
}

function editProductShow() {
    const productList = information.value.businessItemProducts || []
    const list = productList.map((item: any) => {
        const { id, productName, productId, productCode, unit, unitName, typeName, type, price, inventory, orderProductDetail, num, discount, sealPrice, totalPrice, quantity } = item
        return {
            id, productId: productId, productName, productCode, unit, unitName, typeName, type, price, inventory,
            num, discount, sealPrice, totalPrice, quantity
        }
    })
    productTableListValue.value = list
}

function showVisible(type: keyof typeof allVisible) {
    if (type == 'editBusinessVisible') {
        const { name, customerId, contactsId, amountOfMoney, expectedTransactionDate, stageId, inchargerId, remark } = information.value
        generateFormValue.value = { name, customerId, contactsId, amountOfMoney, expectedTransactionDate, stageId, inchargerId, remark }
        editProductShow()
    }
    allVisible[type] = true
}
function closeVisible(type: keyof typeof allVisible) {
    allVisible[type] = false
}

async function getSystemField() {
    const { data } = await post(GETPERSONNEL, {})
    transferOptions.value = data.map((item: any) => {
        const { id, name, phone, jobNumber } = item
        return {
            id, name, phone, jobNumber
        }
    })
    const res = await get(GETGENERATEFOEM)
    generateFormData.value = JSON.parse(res.data[0].config)
}

watchEffect(() => {
    information.value = props.information
});

// 生命周期钩子
onMounted(() => {
    getSystemField()
});
</script>
<style scoped lang="scss">
.information {
    .title {
        font-size: 18px;
        color: #606266
    }

    .form {
        .formItem {
            width: 48%;
        }

        .text {
            display: -webkit-box;
            /* Safari */
            -webkit-line-clamp: 2;
            /* number of lines to show */
            -webkit-box-orient: vertical;
            overflow: hidden;
            line-height: 1.5;
        }
    }
}</style>