<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="80vw" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="单据编号" prop="num">
                            <el-input v-model="formData.num" clearable placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="project">
                            <el-input v-model="formData.project_name" clearable placeholder="点击选择项目" readonly
                                @click="showDialog = true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目编号" prop="project_num">
                            <el-input v-model="formData.project_num" clearable placeholder="请输入项目编号" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="项目负责人" prop="project_director">
                            <el-input v-model="formData.project_director" clearable placeholder="请输入项目负责人" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="关联合同" prop="contract_name">
                            <el-input v-model="formData.contract_name" clearable placeholder="请输入关联合同" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="行业" prop="industry">
                            <el-select class="flex-1" v-model="formData.industry_nature" clearable
                                placeholder="请选择行业类型">
                                <el-option v-for="(item, index) in dictData.supervision_project_industry" :key="index"
                                    :label="item.name" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="项目回款总额" prop="hk">
                            <el-input v-model="formData.total_refund_amount" clearable placeholder="请输入项目回款总额"
                                type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="提成比例（%）" prop="rate">
                            <el-input v-model="formData.rate" clearable placeholder="请输入提成比例（%）" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="应提成总金额" prop="ticheng">
                            <el-input v-model="formData.ticheng" clearable placeholder="请输入应提成总金额" type="number" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="已支付总额" prop="total_pay_amount">
                            <el-input v-model="formData.total_pay_amount" clearable placeholder="请输入已支付总额"
                                type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="本次支付总额" prop="bczfze">
                            <el-input v-model="formData.bczfze" clearable placeholder="请输入本次支付总额" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="登记人" prop="djr">
                            <el-input v-model="formData.djr" clearable placeholder="请输入登记人" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="登记日期" prop="apptime">
                            <el-date-picker class="flex-1 !flex" v-model="formData.apptime" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="请选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" clearable placeholder="请输入备注" type="textarea" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-dialog v-model="showDialog" title="选择项目" width="70%">
                    <dialogTable :config="cost_project" @customEvent="customEvent">
                    </dialogTable>
                </el-dialog>
                <div v-if="showDialog3">
                    <personnelselector ref="personnel" @confirm="submituser" type="1">
                    </personnelselector>
                </div>
            </el-form>
            <div style="margin-bottom: 30px;">任务明细</div>
            <div style="margin-bottom: 30px;">
                <el-table :data="formData.project_commission_detail">
                    <template #empty>
                        <span class="cursor-pointer">暂无数据，点击添加 <el-button @click="handleAdd">+</el-button></span>
                    </template>
                    <el-table-column label="序号" width="150px">
                        <template #default="{ row }">
                            <el-button @click="handleAdd">+</el-button>
                            <el-button @click="handleDelete(row)">-</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="工程师" prop="level" width="200px">

                        <template #default="scope">
                            <el-input v-model="scope.row.engineer" @click="userclick(scope.$index, 'engineer')"
                                placeholder="点击选择" />
                        </template>
                    </el-table-column>
                    <el-table-column label="任务名称" prop="task_name" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.task_name" />
                        </template>
                    </el-table-column>
                    <el-table-column label="任务类型" prop="task_type" width="200px">

                        <template #default="{ row }">
                            <!-- {{ typeof (row.task_type) }} -->
                            <el-select class="flex-1" v-model="row.task_type" clearable placeholder="请选择任务类型">
                                <el-option v-for="(item, index) in dictData.task_type" :key="index" :label="item.name"
                                    :value="(item.value)" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="专业类型" prop="professional_type" width="200px">

                        <template #default="{ row }">
                            <el-select class="flex-1" v-model="row.professional_type" clearable placeholder="请选择专业类型">
                                <el-option v-for="(item, index) in dictData.major_type" :key="index" :label="item.name"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="造价金额" prop="zj_amount" width="200px">

                        <template #default="scope">
                            <el-input v-model="scope.row.zj_amount" type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="收款金额" prop="sk_amount" width="200px">

                        <template #default="scope">
                            <el-input v-model="scope.row.sk_amount" type="number" @blur="calcMoney" />
                        </template>
                    </el-table-column>
                    <el-table-column label="其他增减费用" prop="other_fee" width="200px">

                        <template #default="scope">
                            <el-input v-model="scope.row.other_fee" type="number" @blur="calcMoney" />
                        </template>
                    </el-table-column>
                    <el-table-column label="提成比例(%)" prop="tc_rate" width="200px">

                        <template #default="scope">
                            <el-input v-model="scope.row.tc_rate" type="number" @blur="calcMoney" />
                        </template>
                    </el-table-column>
                    <el-table-column label="应提成金额" prop="tc_amount" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.tc_amount" disabled type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="本次支付金额" prop="pay_amount" width="200px">
                        <template #default="{ row }">
                            <el-input v-model="row.pay_amount" @change="getBczfze" type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" prop="remark" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.remark" type="number" />
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </popup>
    </div>
</template>

<script lang="ts" setup name="projectCommissionEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiProjectCommissionAdd, apiProjectCommissionEdit, apiProjectCommissionDelete } from '@/api/project_commission'
import { apiProjectCommissionDetailDelete } from '@/api/project_commission_detail'
import type { PropType } from 'vue'
import { cost_project } from "@/components/dialogTable/dialogTableConfig"


defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const showDialog = ref(false)
const showDialog3 = ref(false)
const personnel = ref<any>()


// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑项目提成' : '新增项目提成'
})

// 表单数据
const formData = reactive({
    id: '',
    dataid: '',
    num: '',
    project_id: '',
    project_name: '',
    project_num: '',
    project_director: '',
    contract_name: '',
    affcontract_name: "",
    contract: {},
    industry_nature: '',
    total_refund_amount: '',
    rate: '',
    ticheng: '',
    total_pay_amount: '',
    bczfze: '',
    djr: '',
    apptime: '',
    total_invoice_amount: "",
    remark: '',
    projectInfo: {},
    project_commission_detail: []

})
const customEvent = (e) => {
    formData.project_id = e.id
    formData.project_name = e.project_name
    formData.project_num = e.project_num
    formData.project_director = e.contract.project_director
    formData.contract_name = e.contract.contract_name
    formData.industry_nature = String(e.industry)
    formData.total_refund_amount = e.total_refund_amount
    formData.total_pay_amount = e.total_pay_amount
    showDialog.value = false
}


const handleAdd = () => {
    formData.project_commission_detail.push({
        engineer: '',
        engineer_id: '',
        task_name: '',
        task_type: '',
        professional_type: '',
        zj_amount: '',
        sk_amount: '',
        tc_rate: '',
        tc_amount: '',
        pay_amount: '',
        remark: '',
        other_fee: '',
    })
}


const handleDelete = async (row: any) => {
    if (row.id) {
        await apiProjectCommissionDetailDelete({ id: row.id })
    }
    const index = formData.project_commission_detail.indexOf(row);
    formData.project_commission_detail.splice(index, 1);
    getBczfze()
}

// 金额计算
const calcMoney = () => {
    formData.project_commission_detail.forEach(item => {
        item.tc_amount = (Number(item.sk_amount || 0) + Number(item.other_fee || 0)) * (item.tc_rate / 100)
        item.tc_amount = item.tc_amount.toFixed(2)
    })
}


// 计算本次支付金额
const getBczfze = () => {
    formData.bczfze = 0
    formData.project_commission_detail.forEach(item => {
        formData.bczfze += Number(item.pay_amount)
    })
}


formData.ticheng ||= computed(() => {
    return (Number(formData.total_refund_amount) * (Number(formData.rate) / 100) || 0).toFixed(2)
})


const tableIndex = ref(0)
const tableKey = ref('')
//打开弹窗
const userclick = async (e: any, key) => {
    tableIndex.value = e
    tableKey.value = key
    showDialog3.value = true
    await nextTick()
    personnel.value.open()

}

//确认
const submituser = (e: any) => {
    formData.project_commission_detail[tableIndex.value][tableKey.value] = e.name
    formData.project_commission_detail[tableIndex.value][tableKey.value + '_id'] = e.id
    showDialog3.value = false
}

// 表单验证
const formRules = reactive<any>({

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    delete data.ticheng
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    calcMoney()
}



// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiProjectCommissionEdit(data)
        : await apiProjectCommissionAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}



defineExpose({
    open,
    setFormData,
})
</script>
