<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="org_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-select v-model="formData.org_id" clearable placeholder="请选择组织" @change="deptrmt">
                                <el-option v-for="(item, index) in list1" :key="index" :label="item.name" :value="item.id" />
                            </el-select> </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="请选择部门" prop="dept_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-select v-model="formData.dept_id" clearable placeholder="请选择部门">
                                <el-option v-for="(item, index) in list2" :key="index" :label="item.name" :value="item.id" />
                            </el-select></el-form-item> </el-col>

                    <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" readonly clearable placeholder="请选择供应商" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="供应商编码">
                            <el-input v-model="supplier_code" clearable readonly placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同名称" prop="reimburser" @click="showDialog2 = true">
                            <el-input v-model="contract_name" clearable 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_type">
                            <el-select v-model="contract_type" clearable disabled placeholder="系统自动填写">
                                <el-option v-for="(item, index) in dictData.contract_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="reimburser">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目编码" prop="project_code">
                            <el-input v-model="project_code" clearable disabled placeholder="系统自动填写" />

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


                    <el-col :span="8">
                        <el-form-item label="票据编号" prop="acceptance_bill_id" @click="showDialog1 = true">
                            <el-input v-model="bill_sn" readonly clearable placeholder="请输入票据编号" />

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

                    <el-col :span="8">
                        <el-form-item label="开户银行" prop="acceptance_bill_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="deposit_bank" clearable placeholder="请输入开户银行" />

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="账户编码" prop="acceptance_bill_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="account_sn" clearable placeholder="请输入账户编码" />

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">

                        <el-form-item label="汇票类型" prop="acceptance_bill_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-radio-group v-model="bill_type" placeholder="请选择汇票类型">
                                <el-radio v-for="(item, index) in dictData.bill_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="汇票承兑银行" prop="acceptance_bill_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="draft_acceptance_bank" readonly clearable placeholder="请输入汇票承兑银行" />

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="汇票到期日期" prop="acceptance_bill_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-date-picker class="flex-1 !flex" v-model="bill_due_date" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择汇票到期日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="付款日期" prop="payment_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.payment_date" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择付款日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>


                    <el-col :span="8">
                        <el-form-item label="金额" prop="amount" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <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" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.amount_daxie" readonly clearable placeholder="请输入金额大写" />

                        </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="showDialog1" title="选择汇票" width="70%">
                    <acceptanceDialog @customEvent="customEvent1"></acceptanceDialog>
                </el-dialog>

                <el-dialog v-model="showDialog2" title="选择合同" width="70%">
                    <subcontractDialog @customEvent="customEvent2"></subcontractDialog>
                </el-dialog>

                <el-dialog v-model="showDialog" title="选择供应商" width="70%">
                    <supplierDialog @customEvent="customEvent"></supplierDialog>
                </el-dialog>

            </el-form>
        </popup>

    </div>
</template>

<script lang="ts" setup name="projectEdit">
import supplierDialog from '@/components/supplier/index.vue'
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import acceptanceDialog from '@/components/acceptance/index.vue'
import subcontractDialog from '@/components/procurementsubcontracting_selector/index.vue'
import { transferbillAdd, transferbillEdit, transferbillDetail } from '@/api/transfer_bill'
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 { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import configs from "@/config"
import useUserStore from "@/stores/modules/user";

const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const active = ref(0)
const formDataannex = reactive([])
const contract_name = ref('')
const contract_no = ref('')
const customer_name = ref('')
const project_name = ref('')
const project_code = ref('')
const contract_type = ref('')
const bill_sn = ref('')
const bill_type = ref('')
const bill_due_date = ref('')
const deposit_bank = ref('')
const account_sn = ref('')
const draft_acceptance_bank = ref('')
const supplier_code = ref('')
const supplier_name = ref('')
const list1 = reactive([])
const list2 = reactive([])
const userInfo = userStore.userInfo
console.log(userInfo, '222222')
// 上传文件
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)
}





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 amount_daxie = ref('')
const showDialog = ref(false)
const showDialog1 = ref(false)
const showDialog2 = ref(false)





const customEvent = (e: any) => {
    formData.supplier_id = e.id;
    supplier_code.value = e.supplier_code
    supplier_name.value = e.supplier_name
    showDialog.value = false;
};


const customEvent1 = (e: any) => {
    formData.acceptance_bill_id = e.id
    bill_sn.value = e.bill_sn
    bill_due_date.value = e.bill_due_date
    draft_acceptance_bank.value = e.draft_acceptance_bank
    bill_type.value = e.bill_type
    deposit_bank.value = e.account
    account_sn.value = e.account_sn
    showDialog1.value = false;
};


const customEvent2 = (e: any) => {
    formData.procurement_contract_id = e.id
    contract_name.value = e.contract_name;
    contract_no.value = e.contract_no;
    project_name.value = e.project_name;
    project_code.value = e.project_code;
    contract_type.value = e.contract_type;
    showDialog2.value = false;
};



//获取所有组织
const getlist = () => {
    getAll().then((res) => {
        Object.assign(list1, res)

    })
}
//获取部门
const deptrmt = (e: any) => {
    formData.dept_id = ''
    getlist1(e)

}
//获取所有部门
const getlist1 = (id: any) => {
    deptAll({ 'org_id': id }).then((res) => {
        list2.splice(0, list2.length, ...res)
    })
}

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



// 表单数据
const formData = reactive({
    id: '',
    org_id: '',
    dept_id: '',
    supplier_id: '',
    procurement_contract_id: '',
    acceptance_bill_id: '',
    payment_date: "",
    amount: "",
    amount_daxie: "",
    remark: "",
    annex: ""

})


// 表单验证
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.dept_id) {
        getlist1(data.org_id)
    }
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    customer_name.value = data.custom.name
    contract_name.value = data.contract.contract_name;
    contract_no.value = data.contract.contract_no;
    project_name.value = data.project.name;
    project_code.value = data.project.project_code;
    contract_type.value = data.contract.contract_type;
    bill_sn.value = data.acceptance.bill_sn
    bill_due_date.value = data.acceptance.bill_due_date
    draft_acceptance_bank.value = data.acceptance.draft_acceptance_bank
    bill_type.value = data.acceptance.bill_type
    deposit_bank.value = data.bankAccount.deposit_bank
    account_sn.value = data.bankAccount.account_sn



    // bill_sn.value = data.acceptance.bill_sn
    if (data.amount) {
        toChinesNum(data.amount)
    }




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


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





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


    const data = { ...formData }
    mode.value == 'edit'
        ? await transferbillEdit(data)
        : await transferbillAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

    getlist()
}

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



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