<template>
    <div class="relatedTasks pl-4 pr-4 pt-3 pb-3 h-full flex flex-col">
        <div class="flex justify-between">
            <div class="title">相关商机</div>
            <div v-permission="['businessAddAnEdit']">
                <el-button type="primary" @click="editNewBusiness()">新建商机</el-button>
            </div>
        </div>
        <div class="flex-1 overflow-auto pt-3">
            <el-table :data="relatedTaskstable" border style="width: 100%;height: 300px;">
                <el-table-column prop="taskName" label="商机名称">
                    <template #default="scope">
                        <el-button link type="primary" size="large" @click="toDetail(scope.row)">{{
                            scope.row.name
                            }}</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="customerName" label="客户名称" width="130" />
                <el-table-column prop="inchargerName" label="负责人" width="130">
                    <template #default="scope">
                        <TextTranslation translationTypes="userName" :translationValue="scope.row.inchargerName"></TextTranslation>
                    </template>
                </el-table-column>
                <el-table-column prop="amountOfMoney" label="商机金额" width="130" />
                <el-table-column prop="expectedTransactionDate" label="预计成交时间" width="200" />
                <el-table-column prop="stageValue" label="商机阶段" width="140" />
                <el-table-column prop="creatorName" label="创建人" width="130">
                    <template #default="scope">
                        <TextTranslation translationTypes="userName" :translationValue="scope.row.creatorName"></TextTranslation>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="130" />
            </el-table>
        </div>

        <el-dialog v-model="allVisible.newBusinessisible" 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(false)" :loading="allLoading.businessSaveLading"
                            :disabled="allLoading.newBusinessSaveLading">保存</el-button>
                        <el-button @click="closeVisible('newBusinessisible')">取消</el-button>
                    </div>
                </div>
            </template>
            <div class="h-[60vh] overflow-y-auto scroll-bar pt-3" v-loading="allLoading.generateFormLading">
                <GenerateForm ref="businessTemplateRef" :data="businessTemplate" :value="businessTemplateValue"
                    :key="businessTemplateKey" />
                <div>相关产品</div>
                <RelatedProducts ref="relatedProductsRef" :productTableList="productTableList"
                    :productTableListValue="productTableListValue" />
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { get, post } from '@/utils/request';
import { ref, reactive, onMounted, onUnmounted, defineExpose, inject, watchEffect } from 'vue'
import { GenerateForm } from '@zmjs/form-design';
import RelatedProducts from '@/components/relatedProducts/relatedProducts.vue'
import { GETTABLELIST } from '@/pages/product/api';
import { GETGENERATEFOEM, UPDATEINSET } from '@/pages/business/api';
import { judgmentaAmounteEqual, setTemplateDataDisable } from '@/utils/tools';
import { formatDate, formatDateTime } from '@/utils/times';
import router from '@/router';

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

const information = ref<any>({})
const relatedTaskstable = ref([])
const relatedProductsRef = ref<typeof RelatedProducts>()
const businessTemplateRef = ref<typeof GenerateForm>() // 自定义表单dom
const businessTemplateValue = ref({})
const businessTemplateKey = ref(1)
const productTableList = ref([])
const productTableListValue = ref([])
const businessTemplate = ref({
    config: {},
    list: []
}) // 自定义表单数据
const allVisible = reactive({
    newBusinessisible: false
})
const allLoading = reactive({
    generateFormLading: false,
    newBusinessSaveLading: false,
    businessSaveLading: false
})

function toDetail(row: any) {
    router.push({
        path: `/business/detail`,
        query: { id: row.id }
    })
}

function editBusiness(visibles: boolean) {
    businessTemplateRef.value?.getData().then((res: any) => {
        let productTableListData = relatedProductsRef?.value?.returnData()
        if (!productTableListData || judgmentaAmounteEqual({ ...businessTemplateValue.value, ...res }, productTableListData)) {
            return
        }
        productTableListData.forEach((item: any) => {
            delete item.id
        })
        let newForm = {
            ...res,
            expectedTransactionDate: res.expectedTransactionDate ? formatDate(new Date(res.expectedTransactionDate)) : '',
            businessItemProductList: productTableListData ? JSON.stringify(productTableListData) : []
        }
        allLoading.businessSaveLading = true
        post(UPDATEINSET, { ...businessTemplateValue.value, ...newForm }).then((_res) => {
            allVisible.newBusinessisible = visibles
            globalPopup?.showSuccess('保存成功')
            emits('refreshData')
        }).finally(() => {
            allLoading.businessSaveLading = false
        })
    }).catch((_err: any) => {
        console.log(_err)
        globalPopup?.showError('请填写完整')
    })
}

function editNewBusiness() {
    showVisible('newBusinessisible')
    allLoading.generateFormLading = true
    businessTemplateValue.value = { customerId: information.value.id }
    productTableListValue.value = []
    setTimeout(() => {
        businessTemplateRef.value && businessTemplateRef.value.reset()
        businessTemplateKey.value++
        allLoading.generateFormLading = false
    }, 500)
}

async function getSystemField() {
    const datas = await get(GETGENERATEFOEM)
    let newConfig = JSON.parse(datas.data[0].config)
    newConfig.list = setTemplateDataDisable(newConfig.list, ['customerId'])
    businessTemplate.value = newConfig
}

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

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

function getProductTableList() {
    post(GETTABLELIST, { pageIndex: -1, pageSize: -1 }).then((res) => {
        if (res.code == 'ok') {
            const { record, total } = res.data
            productTableList.value = record.map((item: any) => {
                const { id, productName, productCode, unit, unitName, typeName, type, price, inventory } = item
                return {
                    id,
                    productId: id,
                    productName,
                    productCode,
                    unit,
                    unitName,
                    price,
                    type,
                    typeName,
                    inventory,
                    quantity: '',
                    discount: '',
                    totalPrice: ''
                }
            })
        }
    })
}

watchEffect(() => {
    const { data } = props
    information.value = data
    relatedTaskstable.value = (data.businessOpportunitys || [])
})

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