<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" v-if="!info.ownerId">认领</el-button>
                <el-button type="primary" v-else @click="operationCli(false)">转移</el-button>
                <el-button type="primary" v-permission="['contactsEdit']" @click="editInfo(info)">编辑</el-button>
            </div>
        </div>
        <div class="form flex flex-wrap justify-between">
            <div v-for="item in formItems" :key="item.label" class="formItem flex pt-2 pb-1" :style="{ width: item.width }">
                <div :class="item.labelClass">{{ item.label }}：</div>
                <div class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap ml-1" v-ellipsis-tooltip>{{ item.value }}</div>
            </div>
        </div>

        <el-dialog v-model="allVisible.editContactsVisible" 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="editContactsSave()"
                            :loading="allLoading.editContactsSaveLoading">保存</el-button>
                        <el-button @click="closeVisible('editContactsVisible')">取消</el-button>
                    </div>
                </div>
            </template>
            <div class="h-[60vh] overflow-y-auto scroll-bar pt-3">
                <div class="ml-4 mr-4">
                    <GenerateForm ref="contactsTemplateRef" :data="contactsTemplate" :value="contactsTemplateValue"
                        :key="contactsTemplateRefKey" v-loading="allLoading.contactsTemplateRefLoading" />
                </div>
            </div>
        </el-dialog>

        <el-dialog v-model="allVisible.transferVisible" 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">{{ allText.operationText }}</h4>
                    <div>
                        <el-button type="primary" :loading="allLoading.transferLoading"
                            @click="transferBusiness(true)">转移</el-button>
                        <el-button @click="allVisible.transferVisible = 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.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </div>
                <div class="pl-3 text-[#e94a4a]">转移后，将看不到此联系人</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 { getFromValue, getTemplateKey } from '@/utils/tools';
import { GETGENERATEFOEM, GETPERSONNEL, URL_TRANSFERCONTACTS, URL_UPLOAD } from '../api';
import { get, post } from '@/utils/request';

const globalPopup = inject<GlobalPopup>('globalPopup')
const emits = defineEmits(['refreshData']);
const props = defineProps<{
    data: any
}>()
const allLoading = reactive({
    contactsTemplateRefLoading: false,
    editContactsSaveLoading: false,
    transferLoading: false
})
const allVisible = reactive({
    editContactsVisible: false,
    transferVisible: false
})
const allText = reactive({
    operationText: '认领联系人'
})
const contactsTemplate = ref({
    list: [],
    config: {}
})
const contactsTemplateValue = ref({})
const contactsTemplateRef = ref<typeof GenerateForm>()
const contactsTemplateRefKey = ref(1)
const info: any = ref({})
const transferValue = ref('')
const transferOptions = ref<optionType[]>([])

function operationCli(flag: boolean) {
    transferValue.value = flag ? '' : info.value.ownerId
    allText.operationText = flag ? '认领联系人' : '转移联系人'
    showVisible('transferVisible')
}

function transferBusiness(flag: boolean) {
    const url = flag ? URL_TRANSFERCONTACTS : ''
    const formVal = flag ? { id: info.value.id, ownerId: transferValue.value } : {}
    allLoading.transferLoading = true
    post(url, { ...formVal }).then((_res) => {
        closeVisible('transferVisible')
        globalPopup?.showSuccess('转移成功')
        emits('refreshData')
    }).finally(() => {
        allLoading.transferLoading = false
    })
}

function editInfo(row: any) {
    showVisible('editContactsVisible')
    const templateKey = getTemplateKey(contactsTemplate.value.list)
    const formVal: templateKey = { id: row.id }
    for (let i in templateKey) {
        if (row[templateKey[i]] || row[templateKey[i]] == 0) {
            formVal[templateKey[i]] = templateKey[i] == 'sex' ? row[templateKey[i]] + '' : row[templateKey[i]]
        }
    }
    setTemplateVal(formVal)
}

function editContactsSave(flag: boolean = false) {
    contactsTemplateRef.value?.getData().then((res: any) => {
        let formVal = getFromValue({ ...contactsTemplateValue.value, ...res })
        allLoading.editContactsSaveLoading = true
        post(URL_UPLOAD, { ...formVal }).then((_res) => {
            allVisible.editContactsVisible = flag
            globalPopup?.showSuccess('保存成功')
            emits('refreshData')
        }).finally(() => {
            allLoading.editContactsSaveLoading = false
        })
    }).catch((_err: any) => {
        console.log(_err)
        globalPopup?.showError('请填写完整')
    })
}

function setTemplateVal(val: any = {}) {
    contactsTemplateValue.value = val
    allLoading.contactsTemplateRefLoading = true
    setTimeout(() => {
        contactsTemplateRefKey.value++
        allLoading.contactsTemplateRefLoading = false
    }, 1000);
}

function showVisible(type: keyof typeof allVisible) {
    allVisible[type] = true
}

function closeVisible(type: keyof typeof allVisible) {
    allVisible[type] = false
}

const formItems = reactive([
    { label: '联系人', key: 'contactsName', value: '', labelClass: 'w-20 text-right text-gray-500', width: '48%' },
    { label: '客户', key: 'productName', value: '', labelClass: 'w-22 text-right text-gray-500', width: '48%' },
    { label: '电话', key: 'phone', value: '', labelClass: 'w-22 text-right text-gray-500', width: '48%' },
    { label: '邮箱', key: 'email', value: '', labelClass: 'w-22 text-right text-gray-500', width: '48%' },
    { label: '职务', key: 'position', value: '', labelClass: 'w-22 text-right text-gray-500', width: '48%' },
    { label: '性别', key: 'sexValue', value: '', labelClass: 'w-22 text-right text-gray-500', width: '48%' },
    { label: '地址', key: 'address', value: '', labelClass: 'w-22 text-right text-gray-500', width: '48%' },
    { label: '负责人', key: 'inchargerName', value: '', labelClass: 'w-22 text-right text-gray-500', width: '48%' },
    { label: '创建人', key: 'creatorName', value: '', labelClass: 'w-22 text-right text-gray-500', width: '48%' },
    { label: '创建时间', key: 'createTime', value: '', labelClass: 'w-22 text-right text-gray-500', width: '48%' },
    { label: '备注', key: 'remark', value: '', labelClass: 'w-22 text-right text-gray-500', width: '100%' },
])

watchEffect(() => {
    const { data } = props
    info.value = data
    formItems.forEach(item => {
        item.value = info.value[item.key];
    });
});

async function getSystemField() {
    const { data } = await post(GETPERSONNEL, {})
    transferOptions.value = data.map((item: any) => {
        const { id, name, phone, jobNumber } = item
        return {
            value: id,
            label: name
        }
    })

    const datas = await get(GETGENERATEFOEM)
    contactsTemplate.value = JSON.parse(datas.data[0].config)
}

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

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

        .w-20,
        .w-22 {
            width: 80px;
        }
    }
}
</style>
