<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="140px" :rules="formRules">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="客户" prop="customer_id" @click="showDialog = true" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="custom_name" readonly clearable placeholder="请选择客户" />
                        </el-form-item> </el-col><el-col :span="8">
                        <el-form-item label="投标编号" prop="buy_bidding_document_id" @click="showDialog1 = true" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="bidding_code" readonly clearable placeholder="请选择购买标书" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="项目名称" prop="buy_bidding_document_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="document_name" readonly clearable placeholder="请选择购买标书" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="项目编码" prop="buy_bidding_document_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="document_code" readonly clearable placeholder="请选择购买标书" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="合同名称" prop="contract_name" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.contract_name" clearable placeholder="请输入合同名称" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="合同编号" prop="contract_code" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.contract_code" clearable placeholder="请输入合同编号" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="合同类型" prop="contract_type" :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-select class="flex-1" v-model="formData.contract_type" clearable 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_pricing_method" :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-select class="flex-1" v-model="formData.contract_pricing_method" 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="party_a">
                            <el-input v-model="formData.party_a" clearable placeholder="请输入甲方" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="甲方通讯地址" prop="party_a_contact_address">
                            <el-input v-model="formData.party_a_contact_address" clearable placeholder="请输入甲方通讯地址" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="甲方主要负责人" prop="party_a_diretor">
                            <el-input v-model="formData.party_a_diretor" clearable placeholder="请输入甲方主要负责人" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="甲方电话" prop="party_a_phone" :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                            <el-input v-model="formData.party_a_phone" clearable placeholder="请输入甲方电话" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="甲方手机" prop="party_a_mobile">
                            <el-input v-model="formData.party_a_mobile" clearable placeholder="请输入甲方手机" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="甲方邮箱" prop="party_a_email" :rules="[{ validator: userEmail, trigger: 'blur' }]">
                            <el-input v-model="formData.party_a_email" clearable placeholder="请输入甲方邮箱" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="乙方" prop="party_b" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.party_b" clearable placeholder="请输入乙方" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="乙方通讯地址" prop="party_b_contact_address">
                            <el-input v-model="formData.party_b_contact_address" clearable placeholder="请输入乙方通讯地址" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="乙方主要负责人" prop="party_b_diretor">
                            <el-input v-model="formData.party_b_diretor" clearable placeholder="请输入乙方主要负责人" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="乙方电话" prop="party_b_phone" :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                            <el-input v-model="formData.party_b_phone" clearable placeholder="请输入乙方电话" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="乙方手机" prop="party_b_mobile">
                            <el-input v-model="formData.party_b_mobile" clearable placeholder="请输入乙方手机" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="乙方邮箱" prop="party_b_email" :rules="[{ validator: userEmail, trigger: 'blur' }]">
                            <el-input v-model="formData.party_b_email" clearable placeholder="请输入乙方邮箱" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="金额" prop="amount">
                            <el-input v-model="formData.amount" clearable placeholder="请输入金额" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="金额大写" prop="amount_daxie">
                            <el-input v-model="formData.amount_daxie" clearable placeholder="请输入金额大写" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="业务负责人" prop="business_director">
                            <el-input v-model="formData.business_director" clearable placeholder="请输入业务负责人" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="合同状态" prop="contract_status">
                            <el-input v-model="formData.contract_status" clearable placeholder="请输入合同状态" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="合同有效期" prop="expire">
                            <el-date-picker class="flex-1 !flex" v-model="formData.expire" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择合同有效期">
                            </el-date-picker>
                        </el-form-item></el-col><el-col :span="8">

                        <el-form-item label="签约日期" prop="contract_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.contract_date" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择签约日期">
                            </el-date-picker>
                        </el-form-item></el-col><el-col :span="8">

                        <el-form-item label="主要条款" prop="main_content">
                            <el-input v-model="formData.main_content" clearable placeholder="请输入主要条款" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" clearable placeholder="请输入备注" />
                        </el-form-item></el-col><el-col :span="24">
                        <el-form-item label="附件" prop="field127">
                            <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_four" ref="upload">
                                <el-button type="primary">
                                    上传
                                </el-button>
                            </el-upload>

                            <div>
                                <div v-for="(item, index) in formDataannex" 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="delFileFn(index)">x</span>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <reviewprocess />
        </popup>
        <el-dialog v-model="showDialog" title="选择客户" width="70%">

            <customDialog @customEvent="customEvent"></customDialog>



        </el-dialog>
        <el-dialog v-model="showDialog1" title="选择标书" width="70%">
            <biddocumentTable @customEvent="customEvent1"></biddocumentTable>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="contractEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import biddocumentTable from "@/components/biddocument/index.vue"
import reviewprocess from '@/components/reviewprocess/index.vue'

import { apiContractAdd, apiContractEdit, apiContractDetail } from '@/api/contract'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
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 formDataannex = reactive([])
import configs from "@/config"
const base_url = configs.baseUrl + configs.urlPrefix
import useUserStore from "@/stores/modules/user";
const showDialog = ref(false)
const showDialog1 = ref(false)
const custom_name = ref('')
const document_name = ref('')
const document_code = ref('')
const bidding_code = ref('')
const userStore = useUserStore();
//验证
const checkPhone = (rule: any, value: any, callback: (arg0: Error) => any) => {

    if (value && !/^1\d{10}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
    } else {
        callback()
    }

}
const userEmail = (rule: any, value: string, callback: (arg0: Error | undefined) => void) => {

    const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
    // // if (!value) {
    // //     return callback(new Error('邮箱不能为空'))
    // // }


    if (value && !mailReg.test(value)) {
        callback(new Error('请输入正确的邮箱格式'))
    } else {
        callback()
    }

};
// 上传文件
const handleAvatarSuccess_four = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}

//获取值
const customEvent = (e: any) => {
    formData.customer_id = e.id;
    custom_name.value = e.name;
    console.log(custom_name.value, e.name)
    showDialog.value = false;
};
const customEvent1 = (e: any) => {
    formData.buy_bidding_document_id = e.id;
    document_name.value = e.project_name;
    document_code.value = e.project_code
    bidding_code.value = e.bid_document_no
    showDialog1.value = false;
};

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

// 表单数据
const formData = reactive({
    id: '',
    approve_id: '',
    customer_id: '',
    buy_bidding_document_id: '',
    contract_name: '',
    contract_code: '',
    contract_type: '',
    contract_pricing_method: '',
    party_a: '',
    party_a_contact_address: '',
    party_a_diretor: '',
    party_a_phone: '',
    party_a_mobile: '',
    party_a_email: '',
    party_b: '',
    party_b_contact_address: '',
    party_b_diretor: '',
    party_b_phone: '',
    party_b_mobile: '',
    party_b_email: '',
    amount: '',
    amount_daxie: '',
    business_director: '',
    contract_status: '',
    expire: '',
    contract_date: '',
    main_content: '',
    remark: '',
    annex: '',
})


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

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    if (data.annex.length > 0) {
        if (data.annex.includes(",")) {
            const arry1 = data.annex.split(',').map((item: any, index: any) => {
                return {
                    name: `文件${index + 1}`,
                    uri: item
                };
            });
            Object.assign(formDataannex, arry1)
        } else {
            const arry1 = [{ name: `文件1`, uri: data.annex }]
            Object.assign(formDataannex, arry1)

        }
    }


    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    custom_name.value = data.custom.name
    document_name.value = data.document.bid_company_name
    document_code.value = data.document.bid_document_no
    bidding_code.value = data.document.bid_document_no

}

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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item) => item.uri).toString()
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiContractEdit(data)
        : await apiContractAdd(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>
