<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="80%" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="160px" :rules="formRules">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="合同名称" prop="contract_id" @click="showDialog = true"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="contract_name" readonly clearable placeholder="请选择项目合同" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="合同编号" prop="contract_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="contract_code" disabled clearable placeholder="请选择合同"
                                :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="项目名称" prop="contract_id">
                            <el-input v-model="project_name" clearable disabled placeholder="请选择合同"
                                :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="客户名称" prop="contract_id">
                            <el-input v-model="custom_name" clearable disabled placeholder="请选择合同"
                                :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]" />
                        </el-form-item></el-col>

                    <el-col :span="8">
                        <el-form-item label="合同类型" prop="contract_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-select v-model="contract_type" clearable disabled placeholder="请选择合同类型" class=" flex-1">
                                <el-option v-for="(item, index) in dictData.contract_type" :key="index"
                                    :label="item.name" :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同计价方式" prop="contract_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-select class="flex-1" v-model="contract_pricing_method" disabled clearable
                                placeholder="请选择合同计价方式">
                                <el-option v-for="(item, index) in dictData.contract_pricing_method" :key="index"
                                    :label="item.name" :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item>
                    </el-col>


                    <el-col :span="8">
                        <el-form-item label="业务负责人" prop="contract_id">
                            <el-input v-model="business_director" readonly clearable placeholder="请选择人员"
                                :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]" />
                        </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="洽商单名称" prop="negotiation_name">
                            <el-input v-model="formData.negotiation_name" clearable placeholder="请输入洽商单名称" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="洽商编号" prop="negotiation_no">
                            <el-input v-model="negotiation_no" disabled clearable placeholder="系统自动生成" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="洽商金额" prop="negotiation_amount">
                            <el-input v-model="formData.negotiation_amount" clearable placeholder="请输入洽商金额" />
                        </el-form-item></el-col><el-col :span="24">
                        <el-form-item label="洽商类别" prop="negotiation_type">
                            <el-radio-group v-model="formData.negotiation_type" placeholder="请选择洽商类别">
                                <el-radio v-for="(item, index) in dictData.negotiation_type" :key="index"
                                    :label="parseInt(item.value)">
                                    {{ item.name }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="成本金额（人工）" prop="labor_costs">
                            <el-input v-model="formData.labor_costs" clearable placeholder="请输入成本金额（人工）" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="成本金额（材料" prop="material_costs">
                            <el-input v-model="formData.material_costs" clearable placeholder="请输入成本金额（材料" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="洽商质保金额" prop="warranty_amount">
                            <el-input v-model="formData.warranty_amount" clearable placeholder="请输入洽商质保金额" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="洽商质保到期时间" prop="warranty_expire_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.warranty_expire_date" 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="profit">
                            <el-input v-model="profit" clearable disabled placeholder="请输入利润" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="利润率" prop="profit_rate">
                            <el-input v-model="profit_rate" disabled clearable placeholder="请输入利润率" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="洽商内容" prop="negotiation_content">
                            <el-input v-model="formData.negotiation_content" clearable placeholder="请输入洽商内容" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="具体说明" prop="negotiation_detail">
                            <el-input v-model="formData.negotiation_detail" clearable placeholder="请输入具体说明" />
                        </el-form-item></el-col><el-col :span="24">
                        <el-form-item label="签证报价表" prop="negotiation_quotation">
                            <uploadAnnex :formData="formData" value="negotiation_quotation"></uploadAnnex>
                        </el-form-item></el-col><el-col :span="24">
                        <el-form-item label="洽商依据" prop="negotiation_basis">
                            <uploadAnnex :formData="formData" value="negotiation_basis"></uploadAnnex>
                        </el-form-item></el-col>
                </el-row>

            </el-form>
            <el-dialog v-model="showDialog" title="选择合同" width="70%">
                <proontractTable @customEvent="customEvent" :project_id="project?.id || ''"></proontractTable>
            </el-dialog>
        </popup>

    </div>
</template>

<script lang="ts" setup name="contractNegotiationEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiContractNegotiationAdd, apiContractNegotiationEdit, apiContractNegotiationDetail } from '@/api/contract_negotiation'
import proontractTable from "@/components/contract/index.vue"
import { useDictData } from '@/hooks/useDictOptions'
let props = defineProps({
    project: Object
})
const { dictData } = useDictData('negotiation_type,contract_type,contract_pricing_method')
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const showDialog = ref(false)
const contract_name = ref('')
const contract_code = ref('')
const project_name = ref('')
const custom_name = ref('')
const business_director = ref('')
const contract_type = ref('')
const profit_rate = ref(0)
const negotiation_no = ref('')
const profit = ref(0)
const contract_pricing_method = ref('')

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑合同洽商' : '新增合同洽商'
})

// 表单数据
const formData = reactive({
    id: '',
    contract_id: '',
    negotiation_name: '',
    negotiation_no: '',
    negotiation_amount: '',
    negotiation_type: '',
    labor_costs: '',
    material_costs: '',
    warranty_amount: '',
    warranty_expire_date: '',
    negotiation_content: '',
    negotiation_detail: '',
    negotiation_quotation: [],
    negotiation_basis: [],
})

if (props.project) {
    project_name.value = props.project.name
    custom_name.value = props.project.custom_name

}
//获取值
const customEvent = (e: any) => {
    formData.contract_id = e.id;
    contract_name.value = e.contract_name;
    contract_code.value = e.contract_code
    custom_name.value = e.custom_name
    business_director.value = e.business_director_name
    contract_type.value = e.contract_type
    project_name.value = e.project_name
    contract_pricing_method.value = e.contract_pricing_method
    showDialog.value = false;
};
// 表单验证
const formRules = reactive<any>({
})

watch(
    () => formData.negotiation_amount,
    () => {
        const laborCosts = Number(formData.labor_costs) || 0;
        const materialCosts = Number(formData.material_costs) || 0;;
        const negotiationAmount = Number(formData.negotiation_amount) || 0;;
        profit.value = negotiationAmount - (laborCosts + materialCosts);
        profit_rate.value = (profit.value / negotiationAmount).toFixed(2)
    },
    {
        // 开启深度监听
        deep: true,
    }
)
watch(
    () => formData.labor_costs,
    () => {
        const laborCosts = Number(formData.labor_costs) || 0;
        const materialCosts = Number(formData.material_costs) || 0;;
        const negotiationAmount = Number(formData.negotiation_amount) || 0;;
        profit.value = negotiationAmount - (laborCosts + materialCosts);
        profit_rate.value = (profit.value / negotiationAmount).toFixed(2)
    },
    {
        // 开启深度监听
        deep: true,
    }
)
watch(
    () => formData.material_costs,
    () => {
        const laborCosts = Number(formData.labor_costs) || 0;
        const materialCosts = Number(formData.material_costs) || 0;;
        const negotiationAmount = Number(formData.negotiation_amount) || 0;;
        profit.value = negotiationAmount - (laborCosts + materialCosts);
        profit_rate.value = (profit.value / negotiationAmount).toFixed(2)
    },
    {
        // 开启深度监听
        deep: true,
    }
)

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

    business_director.value = data.business_director
    contract_name.value = data.contract_name
    contract_code.value = data.contract_code
    project_name.value = data.project_name
    custom_name.value = data.custom_name
    contract_type.value = data.contract_type
    contract_pricing_method.value = data.contract_pricing_method

}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiContractNegotiationDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {

    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiContractNegotiationEdit(data)
        : await apiContractNegotiationAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

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



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