<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="请选择合同类型">
                                <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">
                            <!-- <el-input v-model="formData.negotiation_quotation" clearable placeholder="请输入签证报价表" /> -->
                            <el-upload
                                accept="doc, docx, xls, xlsx, ppt, pptx, pdf, txt, zip, rar, tar, jpg, png, gif, jpeg, webp, wmv, avi, mpg, mpeg, 3gp, mov, mp4, flv, f4v, rmvb, mkv"
                                class="upload-demo" :show-file-list="false" aria-hidden="true"
                                :headers="{ Token: userStore.token }" :action="base_url + '/upload/file'"
                                :on-success="handleAvatarSuccess_four1" ref="upload">
                                <el-button type="primary">
                                    上传
                                </el-button>
                            </el-upload>

                            <div>
                                <div v-for="(item, index) in formDataannex1" style="margin-left: 5px;display: block;">
                                    <a style="margin-left: 10px; color: #4a5dff; align-self: flex-start"
                                        :href="item.uri" target="_blank">{{ item.name }}</a>
                                    <span style="cursor: pointer;margin-left: 5px;" @click="delFileFn1(index)">x</span>
                                </div>
                            </div>
                        </el-form-item></el-col><el-col :span="24">
                        <el-form-item label="洽商依据" prop="negotiation_basis">

                            <el-upload
                                accept="doc, docx, xls, xlsx, ppt, pptx, pdf, txt, zip, rar, tar, jpg, png, gif, jpeg, webp, wmv, avi, mpg, mpeg, 3gp, mov, mp4, flv, f4v, rmvb, mkv"
                                class="upload-demo" :show-file-list="false" aria-hidden="true"
                                :headers="{ Token: userStore.token }" :action="base_url + '/upload/file'"
                                :on-success="handleAvatarSuccess_four2" ref="upload">
                                <el-button type="primary">
                                    上传
                                </el-button>
                            </el-upload>

                            <div>
                                <div v-for="(item, index) in formDataannex2" style="margin-left: 5px;display: block;">
                                    <a style="margin-left: 10px; color: #4a5dff; align-self: flex-start"
                                        :href="item.uri" target="_blank">{{ item.name }}</a>
                                    <span style="cursor: pointer;margin-left: 5px;" @click="delFileFn2(index)">x</span>
                                </div>
                            </div>
                        </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>>()

import configs from "@/config"
const base_url = configs.baseUrl + configs.urlPrefix
import useUserStore from "@/stores/modules/user";
const userStore = useUserStore();
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 formDataannex1 = reactive([])
const formDataannex2 = reactive([])
const contract_pricing_method = ref('')

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑合同洽商' : '新增合同洽商'
})
// 上传文件
const handleAvatarSuccess_four1 = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex1.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn1 = (index: number) => {
    formDataannex1.splice(index, 1)
}
// 上传文件
const handleAvatarSuccess_four2 = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex2.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn2 = (index: number) => {
    formDataannex2.splice(index, 1)
}
// 表单数据
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>) => {
    if (data.negotiation_quotation && data.negotiation_quotation.length > 0) {

        const arry1 = data.negotiation_quotation.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex1, arry1)

    }
    if (data.negotiation_basis && data.negotiation_basis.length > 0) {

        const arry1 = data.negotiation_basis.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex2, arry1)

    }
    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 () => {
    if (formDataannex1.length > 0) {
        formData.negotiation_quotation = formDataannex1.map((item) => item.uri)
    }
    if (formDataannex2.length > 0) {
        formData.negotiation_basis = formDataannex2.map((item) => item.uri)
    }
    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>
