<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="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="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="invoicing_date"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">

                            <el-date-picker class="flex-1 !flex" v-model="formData.invoicing_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="project_amount">
                            <el-input v-model="project_amount" clearable disabled placeholder="系统自动填写" />
                        </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="accumulate_amount">
                            <el-input v-model="accumulate_amount" clearable placeholder="请输入累计开票金额" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="累计回款金额" prop="accumulated_payments_received">
                            <el-input v-model="accumulated_payments_received" clearable placeholder="请输入累计回款金额" />
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="8">
                        <el-form-item label="税率" prop="tax_rate">

                            <el-select class="flex-1" v-model="formData.tax_rate" clearable placeholder="请选择税率">
                                <el-option v-for="(item, index) in dictData.tax_rate" :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.invoice_type" clearable placeholder="请选择发票类型">
                                <el-option v-for="(item, index) in dictData.invoice_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="invoicing_amount">
                            <el-input v-model="formData.invoicing_amount" clearable placeholder="请输入开票金额(含税)"
                                @change="amountinput" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="金额大写" prop="invoicing_amount_daxie">
                            <el-input v-model="invoicing_amount_daxie" disabled clearable placeholder="请输入金额大写" />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="8">
                        <el-form-item label="开票金额(税额)" prop="tax">
                            <el-input v-model="formData.tax" clearable placeholder="请输入开票金额(税额)" />
                        </el-form-item>
                    </el-col> -->
                    <!-- <el-col :span="8">
                        <el-form-item label="开票金额(非税)" prop="amount_including_tax">
                            <el-input v-model="formData.amount_including_tax" clearable placeholder="请输入开票金额(非税)" />
                        </el-form-item>
                    </el-col> -->


                    <el-col :span="24">
                        <el-form-item label="开票内容" prop="content">
                            <el-input v-model="formData.content" type="textarea" clearable placeholder="请输入开票内容" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="发票编号" prop="invoice_no">
                            <el-input v-model="formData.invoice_no" 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="annex">
                            <el-input v-model="formData.annex" clearable placeholder="请输入附件" />
                        </el-form-item> -->
                        <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="开票公司名称" prop="invoicing_company_name">
                            <el-input v-model="formData.invoicing_company_name" clearable placeholder="请输入开票公司名称" />
                        </el-form-item>

                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="纳税人识别号" prop="taxpayer_identification_number">
                            <el-input v-model="formData.taxpayer_identification_number" clearable placeholder="请输入纳税人识别号" />
                        </el-form-item>

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

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

                    </el-col> <el-col :span="8">
                        <el-form-item label="开户地址及电话" prop="address_phone">
                            <el-input v-model="formData.address_phone" clearable placeholder="请输入开户地址及电话" />
                        </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="收票地址" prop="receiving_address">
                            <el-input v-model="formData.receiving_address" clearable placeholder="请输入收票地址" />
                        </el-form-item>

                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人" prop="contacts">
                            <el-input v-model="formData.contacts" clearable placeholder="请输入联系人" />
                        </el-form-item>

                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系电话" prop="phone" :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                            <el-input v-model="formData.phone" clearable placeholder="请输入联系电话" />
                        </el-form-item>

                    </el-col> <el-col :span="8">
                        <el-form-item label="邮寄时间" prop="mailing_time">

                            <el-date-picker class="flex-1 !flex" v-model="formData.mailing_time" 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="mailing_type">
                            <el-input v-model="formData.mailing_type" clearable placeholder="请输入邮寄方式" />
                        </el-form-item>

                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="邮寄单号" prop="mailing_no">
                            <el-input v-model="formData.mailing_no" clearable placeholder="请输入邮寄单号" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-dialog v-model="showDialog" title="选择客户" width="70%">
                    <customDialog @customEvent="customEvent"></customDialog>
                </el-dialog>
                <el-dialog v-model="showDialog1" title="选择合同" width="70%">
                    <contractDialog @customEvent="customEvent1" :project_id="project?.id || ''"></contractDialog>
                </el-dialog>
            </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 { toChinesNum } from "@/utils/util";
import contractDialog from '@/components/contract/index.vue'
import { apiinvoiceapplyAdd, apiinvoiceapplyEdit, apiinvoiceapplyDetail } from '@/api/InvoicingRequests'
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 { computed } from "vue"
import { useDictData } from '@/hooks/useDictOptions'
const { dictData } = useDictData('pay_period,invoice_type,tax_rate')

const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const active = ref(0)
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 next = () => {
    if (active.value++ > 3) active.value = 0
}
// 上传文件
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 checkPhone = (rule: any, value: any, callback: (arg0: Error) => any) => {

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

}




let invoicing_amount_daxie = computed(() => {
    return toChinesNum(formData.invoicing_amount)
})


// 删除上传的文件
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 showDialog = ref(false)
const showDialog1 = ref(false)

const customEvent = (e: any) => {
    formData.customer_id = e.id;
    custom_name.value = e.name;
    showDialog.value = false;
};
const customEvent1 = (e: any) => {
    formData.contract_id = e.id;
    custom_name.value = e.custom_name;
    project_name.value = e.project_name;
    project_code.value = e.project_code;
    contract_name.value = e.contract_name;
    contract_no.value = e.contract_code
    project_amount.value = e.amount

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

// 表单数据
const formData = reactive({
    id: '',
    contract_id: '',

    invoicing_date: "",
    period: "",

    tax_rate: "",
    invoice_type: '',
    invoicing_amount: '',

    amount_including_tax: '',
    content: "",
    invoice_no: "",
    remark: "",
    annex: [],
    invoicing_company_name: "",
    taxpayer_identification_number: "",
    deposit_bank: "",
    bank_accnout: "",
    address_phone: "",
    receiving_address: "",
    contacts: "",
    phone: "",
    mailing_time: "",
    mailing_type: "",
    mailing_no: ""
})


// 表单验证
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]
        }
    }
    if (formData.invoicing_amount) {
        toChinesNum(formData.invoicing_amount)
    }
    custom_name.value = data.custom_name
    project_name.value = data.contract_name;
    project_code.value = data.contract_code
    project_amount.value = data.contract_amount
    contract_name.value = data.contract_name;
    contract_no.value = data.contract_code


}
const getDetail = async (row: Record<string, any>) => {
    const data = await apiinvoiceapplyDetail({
        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 apiinvoiceapplyEdit(data)
        : await apiinvoiceapplyAdd(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>
