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

                            <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="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>

                    <el-table :data="tablist1">
                        <el-table-column label="序号">
                            <template #default="{ row }">

                                <el-button @click="handleAdd(row)" size="small">+</el-button>
                                <el-button @click="handleDelete(row)" size="small">-</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="供应方式" prop="name1">

                            <template #default="{ row, $index }">
                                <el-input v-model="row.name1" readonly @click="subjectmu(row, $index)" />
                            </template>
                        </el-table-column>
                        <el-table-column label="材料编码" prop="name2">

                            <template #default="{ row }">
                                <el-input v-model="row.name2" readonly />
                            </template></el-table-column>
                        <el-table-column label="材料名称" prop="use_to">

                            <template #default="{ row }">
                                <el-input v-model="row.use_to" /> </template>
                        </el-table-column>
                        <el-table-column label="规格型号" prop="amount">

                            <template #default="{ row }">
                                <el-input v-model="row.amount" type="number" /> </template>
                        </el-table-column>

                        <el-table-column label="品牌" prop="remark">

                            <template #default="{ row }">
                                <el-input v-model="row.remark" /> </template>
                        </el-table-column>

                        <el-table-column label="参数说明" prop="remark">

                            <template #default="{ row }">
                                <el-input v-model="row.remark" /> </template>
                        </el-table-column>
                        <el-table-column label="单位" prop="remark">

                            <template #default="{ row }">
                                <el-input v-model="row.remark" /> </template>
                        </el-table-column>
                        <el-table-column label="数量" prop="remark">

                            <template #default="{ row }">
                                <el-input v-model="row.remark" /> </template>
                        </el-table-column>
                        <el-table-column label="备注" prop="remark">

                            <template #default="{ row }">
                                <el-input v-model="row.remark" /> </template>
                        </el-table-column>
                    </el-table>


                </el-row>

                <el-dialog v-model="showDialog1" title="选择项目" width="70%">
                    <projectDialog @customEvent="customEvent1" contract_type="2"></projectDialog>
                </el-dialog>
            </el-form>
        </popup>

    </div>
</template>

<script lang="ts" setup name="projectEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { toChinesNum } from "@/utils/util";
import projectDialog from '@/components/project/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";
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 custom_name = ref('')
const tablist1 = reactive([{}])
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 handleAdd = (row: any) => {
    // 在 row 后面插入一行数据
    const index = tablist1.indexOf(row);
    tablist1.splice(index + 1, 0, {});
};

const handleDelete = (row: any) => {
    // 删除 row
    const index = tablist1.indexOf(row);
    tablist1.splice(index, 1);
};
const handleAdd1 = (row: any) => {
    // 在 row 后面插入一行数据
    const index = tablist2.indexOf(row);
    tablist2.splice(index + 1, 0, {});
};
//验证
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 amountinput = (e) => {
    if (e && e > 0) {
        formData.invoicing_amount_daxie = toChinesNum(e)
    }
}
// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}
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 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;
    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: '',
    customer_id: '',
    contract_id: '',
    approve_id: '',
    invoicing_date: "",
    period: "",
    accumulate_amount: '',
    accumulated_payments_received: '',
    tax_rate: "",
    invoice_type: '',
    invoicing_amount: '',
    invoicing_amount_daxie: "",
    tax: '',
    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.contract_name;
    contract_no.value = data.contract.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)
    }

    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()

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

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

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



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