<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"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]" @click="showDialog = true">
                            <el-input v-model="supplier_name" readonly clearable placeholder="请选择供应商" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="供应商编码" prop="supplier_id">
                            <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="w-[400px]">
                                <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_no" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同名称" prop="contract_id" @click="showDialog1 = true">
                            <el-input v-model="contract_name" clearable placeholder="请选择项目" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="contract_name">
                            <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="invoicing_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.invoicing_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="commitor">
                            <el-input v-model="formData.commitor" clearable placeholder="请输入提交人" />

                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="发票类型" prop="invoice_type"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-radio-group v-model="formData.invoice_type" placeholder="请选择发票类型">
                                <el-radio v-for="(item, index) in dictData.invoice_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="发票编号">
                            <el-input v-model="formData.invoice_no" clearable placeholder="请输入发票编号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="发票金额" prop="invoice_amount"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.invoice_amount" clearable placeholder="请输入发票金额"
                                @input="amountinput" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="发票金额大写" prop="invoice_amount_daxie">
                            <el-input v-model="formData.invoice_amount_daxie" clearable disabled placeholder="请输入金额大写" />

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

                    <el-col :span="8">
                        <el-form-item label="发票税率" prop="invoice_tax_rate">
                            <el-select v-model="formData.invoice_tax_rate" placeholder="请选择" @change="amountinput"
                                class="w-[400px]">
                                <el-option :label="item.name" :value="item.value"
                                    v-for="item in dictData.tax_rate"></el-option>
                            </el-select>

                            <!-- <dict-value :options="dictData.tax_rate" :value="row.tax_rate" /> -->
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="税额" prop="tax" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.tax" disabled clearable placeholder="请输入税额" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="不含税金额" prop="amount_excluding_tax"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.amount_excluding_tax" clearable disabled placeholder="请输入不含税金额" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="收票日期" prop="receipt_date"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-date-picker class="flex-1 !flex" v-model="formData.receipt_date" clearable
                                value-format="YYYY-MM-DD" placeholder="选择收票日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <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="field87">
                            <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%">
                    <suppliertable @customEvent="customEvent" :project_id="project?.id || ''"></suppliertable>
                </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 suppliertable from '@/components/supplier/index.vue'
import subcontractingDialog from '@/components/procurementsubcontracting_selector/index.vue'
import subcontracting from '@/components/procurementsubcontracting_selector/subcontracting.vue'
import { apifinancereceiptAdd, apifinancereceiptEdit, apifinancereceiptDetail } from '@/api/receiptrecord'
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('invoice_type,contract_type,tax_rate')

const protype = reactive([])
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 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 checkPhone = (rule: any, value: any, callback: (arg0: Error) => any) => {
    if (value && !/^1\d{10}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
    } else {
        callback()
    }
}


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

const resetFormData = () => {
    project_name.value = ""
    project_code.value = ''
    contract_no.value = ""
    contract_name.value = ''
}
const customEvent = (e: any) => {
    formData.supplier_id = e.id;
    supplier_code.value = e.supplier_code
    supplier_name.value = e.supplier_name
    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;
};

//获取税率Name
const getTaxValue = (value) => {
    let i = dictData.tax_rate.findIndex((item) => item.value == value)
    return (dictData.tax_rate[i]?.name / 100) || 0
}

//监听输入
const amountinput = (e) => {
    formData.tax = formData.invoice_amount * getTaxValue(formData.invoice_tax_rate)
    formData.amount_excluding_tax = formData.invoice_amount - formData.tax
    formData.invoice_amount_daxie = toChinesNum(formData.invoice_amount)
}


// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑收票记录表' : '新增收票记录表'
})

// 表单数据
const formData = reactive({
    id: '',
    supplier_id: '',
    contract_id: '',
    invoicing_date: "",
    commitor: '',
    invoice_type: '',
    invoice_no: "",
    invoice_amount: '',
    invoice_amount_daxie: "",
    invoice_tax_rate: "",
    tax: "",
    amount_excluding_tax: "",
    receipt_date: "",
    remark: "",
    annex: "",
    contract_cate: 1
})


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

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    if (data.return_desc && data.return_desc.length > 0) {
        const arry1 = data.return_desc.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex, arry1)
    }
    if (data.invoice_amount_daxie) {
        toChinesNum(data.invoice_amount_daxie)
    }
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    supplier_name.value = data.supplier_name
    supplier_code.value = data.supplier_code
    contract_no.value = data.contract_no
    contract_name.value = data.contract_name
    project_name.value = data.project_name
    project_code.value = data.project_code
    amountinput()


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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.return_desc = formDataannex.map((item: any) => item.uri).toString()
    }
    await formRef.value?.validate()


    const data = { ...formData }



    mode.value == 'edit'
        ? await apifinancereceiptEdit(data)
        : await apifinancereceiptAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

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

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

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

formData.commitor = userInfo.name

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