<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="auto" :rules="formRules">
                <el-row :gutter="10">
                    <el-col :span="8">
                        <el-form-item label="供应商名称" prop="supplier_id" @click="showDialog = true"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="supplier_name" clearable readonly placeholder="请选择供应商" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="供应商编码" prop="supplier_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="supplier_code" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同类型" prop="contract_cate">
                            <el-select v-model="formData.contract_cate" placeholder="请选择" @change="resetFormData"
                                class="flex-1">
                                <el-option label="采购合同" :value="1"></el-option>
                                <el-option label="分包合同" :value="2"></el-option>
                            </el-select>

                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="合同名称" prop="contract_no">
                            <el-input v-model="contract_name" readonly @click="showDialog1 = true" placeholder="点击选择" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同编号" prop="contract_no">
                            <el-input v-model="contract_no" clearable disabled placeholder="系统自动填写" />
                        </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="请选择项目" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目编码" prop="contract_id">
                            <el-input v-model="project_code" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="8">
                        <el-form-item label="计划付款日期" prop="pay_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.pay_date" clearable
                                value-format="YYYY-MM-DD" placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="期次" prop="period"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-select class="flex-1" v-model="formData.period" clearable placeholder="请选择期次">
                                <el-option v-for="(item, index) in dictData.pay_period" :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="amount">
                            <el-input v-model="formData.amount" clearable placeholder="请输入金额" @input="amountinput" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="外币备注" prop="foreign_currency_remark">
                            <el-input v-model="formData.foreign_currency_remark" clearable placeholder="请输入外币备注" />

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="状态" prop="status">
                            <el-select class="flex-1" v-model="formData.status" clearable placeholder="请选择状态">
                                <el-option v-for="(item, index) in dictData.pay_status" :key="index" :label="item.name"
                                    :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" type="textarea" 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-dialog v-model="showDialog" title="选择供应商" width="70%">
                    <supplier @customEvent="customEvent" :project_id="project?.id || ''"></supplier>
                </el-dialog>
                <div v-if="formData.contract_cate == 1 && showDialog1">
                    <el-dialog v-model="showDialog1" title="选择采购合同" width="70%">
                        <subcontractingDialog @customEvent="customEvent1" :supplier_id="formData.supplier_id">
                        </subcontractingDialog>
                    </el-dialog>
                </div>

                <div v-if="formData.contract_cate == 2 && showDialog1">
                    <el-dialog v-model="showDialog1" title="选择分包合同" width="70%">
                        <subcontracting @customEvent="customEvent1" :supplier_id="formData.supplier_id">
                        </subcontracting>
                    </el-dialog>
                </div>
            </el-form>
        </popup>

    </div>
</template>

<script lang="ts" setup name="projectEdit">
import customDialog from '@/components/custom-dialog/index.vue'
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import supplier from '@/components/supplier/index.vue'
import subcontractingDialog from '@/components/procurementsubcontracting_selector/index.vue'
import subcontracting from '@/components/procurementsubcontracting_selector/subcontracting.vue'
import { paymentplanAdd, paymentplanEdit, paymentplanDetail } from '@/api/paymentplan'
import { toChinesNum } from "@/utils/util";
import { getAllProjectTypes } from '@/api/projecttype'
import { timeFormat } from '@/utils/util'
import { isEmail, isIdCard, isPhone } from '@/utils/validate'
import type { PropType } from 'vue'
import configs from "@/config"
import useUserStore from "@/stores/modules/user";
import { useDictData } from '@/hooks/useDictOptions'

const { dictData } = useDictData('pay_status,pay_period')
const protype = reactive([])
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const formDataannex = reactive([])
const contract_name = ref('')
const project_name = ref('')
const project_code = ref('')
const project_amount = ref('')
const contract_no = ref('')
const supplier_name = ref('')
const supplier_code = ref('')
const userInfo = userStore.userInfo
// 上传文件
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 props = defineProps({
    project: Object
})

if (props.project) {
    project_name.value = props.project.name
    project_code.value = props.project.project_code
}

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const foreign_currency_remark = ref('')
const showDialog = ref(false)
const showDialog1 = ref(false)

const customEvent = (e: any) => {
    formData.supplier_id = e.id;
    supplier_name.value = e.supplier_name;
    supplier_code.value = e.supplier_code;
    resetFormData()
    showDialog.value = false;
};
const customEvent1 = (e: any) => {
    formData.contract_id = e.id;
    project_name.value = e.project_name;
    project_code.value = e.project_code;
    contract_name.value = e.contract_name;
    contract_no.value = e.contract_no

    showDialog1.value = false;
};
const resetFormData = () => {
    project_name.value = ""
    project_code.value = ''
    contract_no.value = ""
    contract_name.value = ''
}


//监听输入
const amountinput = (e) => {
    // console.log(e)
    if (e && e > 0) {
        formData.foreign_currency_remark = toChinesNum(e)
    }
}
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑付款计划表' : '新增付款计划表'
})



// 表单数据
const formData = reactive({
    id: '',
    supplier_id: 1,
    contract_id: "",
    pay_date: '',
    period: "",
    amount: "",
    foreign_currency_remark: "",
    status: '',
    remark: "",
    annex: [],
    contract_cate: 1
})


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

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    console.log(data)
    if (data.annex && data.annex.length > 0) {

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

    }

    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    project_name.value = data.project?.name || data.project_name
    project_code.value = data.project?.project_code || data.project_code
    project_amount.value = data.contract?.amount || data.amount
    contract_name.value = data.contract?.contract_name || data.contract_name
    contract_no.value = data.contract?.contract_no || data.contract_no
    formData.contract_cate = data.contract_type
    supplier_code.value = data.supplier_code;
    supplier_name.value = data.supplier_name;
    // supplier_code

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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item: any) => item.uri)
    }
    await formRef.value?.validate()
    const data = { ...formData }
    mode.value == 'edit'
        ? await paymentplanEdit(data)
        : await paymentplanAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

    getAllProjectTypes().then((res) => {

        protype.splice(0, protype.length, ...res);
    })
}

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



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