<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="contract_id" @click="showDialog1 = true"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="contract_no" clearable readonly placeholder="请输入合同编号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同名称" prop="contract_id">
                            <el-input v-model="contract_name" clearable disabled placeholder="系统自动填写" />
                        </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="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="contract_id">
                            <el-input v-model="project_name" disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目编码" prop="contract_id">
                            <el-input v-model="project_code" disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="8">
                        <el-form-item label="日期" prop="return_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.return_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="period"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-select class="flex-1" v-model="formData.period" disabled 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="12">
                        <el-button type="primary" @click="showDialog3 = true">选择待回款计划</el-button>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="收款性质" prop="contacts">
                            <el-select class="flex-1" v-model="formData.collection_type" clearable placeholder="请选择收款性质">
                                <el-option v-for="(item, index) in dictData.collection_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="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="amount_daxie">
                            <el-input v-model="amount_daxie" disabled placeholder="系统自动填写" />

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="开票状态" prop="contacts">
                            <el-select class="flex-1" v-model="formData.invoice_status" clearable placeholder="请选择开票状态">
                                <el-option v-for="(item, index) in dictData.invoice_status" :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="contacts">
                            <el-select class="flex-1" v-model="formData.pay_type" clearable placeholder="请选择付款方式">
                                <el-option v-for="(item, index) in dictData.pay_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="return_total_amount">
                            <el-input v-model="return_total_amount" disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="款项说明" prop="return_desc">
                            <el-input v-model="formData.return_desc" clearable placeholder="请输入款项说明" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="收款人" prop="receiver">
                            <el-input v-model="formData.receiver" clearable placeholder="请输入收款人" />
                        </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>
                <div style="margin: 20px 0;">付款银行信息</div>

                <el-row :gutter="10">

                    <el-col :span="8">
                        <el-form-item label="账户编码" @click="showDialog2 = true">
                            <el-input v-model="account_sn" readonly clearable placeholder="请选择收款账户" />
                        </el-form-item>

                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="开户银行" prop="deposit_bank">
                            <el-input v-model="deposit_bank" clearable disabled placeholder="请输入开户银行" />
                        </el-form-item>

                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="账号" prop="account">
                            <el-input v-model="account" clearable disabled placeholder="请输入开票公司名称" />
                        </el-form-item>
                    </el-col>
                </el-row>

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

                <el-dialog v-model="showDialog2" title="选择银行账户" width="70%">
                    <bankaccountDialog @customEvent="customEvent2"></bankaccountDialog>
                </el-dialog>
                <div v-if="showDialog3">
                    <el-dialog v-model="showDialog3" title="选择待回款计划" width="70%">
                        <pendingDialog @customEvent="customEvent3" :contract_id="formData.contract_id"></pendingDialog>
                    </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 contractDialog from '@/components/contract/index.vue'
import bankaccountDialog from '@/components/bankaccount/index.vue'
import pendingDialog from '@/components/pending_paymentplan/index.vue'
import { apireturnedrecordAdd, apireturnedrecordEdit, apireturnedrecordDetail } from '@/api/recordsPayment'
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('isaccrued,pay_type,invoice_status,pay_period,collection_type')
const protype = reactive([])
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const return_total_amount = ref('')
const formDataannex = reactive([])
const contract_name = ref('')
const project_name = ref('')
const project_code = ref('')
const project_amount = ref('')
const contract_no = ref('')
const custom_name = ref('')
const account_sn = ref('')
const account = ref('')
const deposit_bank = ref('')


// 上传文件
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)
}
let props = defineProps({
    project: Object
})
if (props.project) {
    project_name.value = props.project.name
    project_code.value = props.project.project_code
    custom_name.value = props.project.custom_name
}
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const amount_daxie = ref('')
const showDialog = ref(false)
const showDialog1 = ref(false)
const showDialog2 = ref(false)
const showDialog3 = ref(false)

const customEvent1 = (e: any) => {
    formData.contract_id = e.id;
    project_name.value = e.project_name;
    project_code.value = e.project_code;
    custom_name.value = e.custom_name;
    contract_name.value = e.contract_name;
    contract_no.value = e.contract_code
    formData.period = ''
    showDialog1.value = false;
};
const customEvent2 = (e: any) => {
    formData.bank_account_id = e.id;
    account_sn.value = e.account_sn;
    account.value = e.account;
    deposit_bank.value = e.deposit_bank;
    showDialog2.value = false;
}

const customEvent3 = (e: any) => {
    formData.finance_returned_money_id = e.id;
    formData.period = e.period
    formData.amount = e.amount
    if (e && e.amount) {
        amount_daxie.value = toChinesNum(e)
    }
    showDialog3.value = false;
}

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

// 表单数据
const formData = reactive({
    id: '',
    contract_id: '',
    finance_returned_money_id: 0,
    return_date: "",
    period: "",
    amount: 0,
    collection_type: '',
    invoice_status: '',
    pay_type: '',
    return_desc: "",
    receiver: "",
    bank_account_id: "",

    remark: "",
    annex: []
})


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

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    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]
        }
    }
    custom_name.value = data.custom_name
    project_name.value = data.project_name
    project_code.value = data.project_code
    project_amount.value = data.contract_amount
    contract_name.value = data.contract_name;
    contract_no.value = data.contract_code
    account_sn.value = data.bank_account_info.account_sn;
    account.value = data.bank_account_info.account;
    deposit_bank.value = data.bank_account_info.deposit_bank;
    if (data.amount) {
        amount_daxie.value = toChinesNum(data.amount)
    }


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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item: any) => item.uri)
    }

    console.log(formRef.value?.validate(), '22222222')
    await formRef.value?.validate()


    const data = { ...formData }
    mode.value == 'edit'
        ? await apireturnedrecordEdit(data)
        : await apireturnedrecordAdd(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>
