<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="120px" :rules="formRules">


                <el-row>
                    <el-col :span="8">
                        <el-form-item label="单据类型" prop="supplier_id" @click="showDialog = true">
                            <el-input v-model="supplier_contract_name" readonly clearable placeholder="请选择供应商" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="账户编码" prop="supplier_id" @click="showDialog = true">
                            <el-input v-model="supplier_contract_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_contract_no" disabled clearable placeholder="系统自动填写" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="账号" prop="contract_name">
                            <el-input v-model="formData.contract_name" clearable placeholder="由系统自动生成" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同编号" prop="contract_no">
                            <el-input v-model="formData.contract_no" clearable placeholder="请输入供应商合同号" />
                        </el-form-item> </el-col>

                    <el-col :span="8">
                        <el-form-item label="日期" prop="start_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.start_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="amount">
                            <el-input v-model="formData.amount" clearable placeholder="请输入经办人" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="金额" prop="amount_daxie">
                            <el-input v-model="formData.amount_daxie" clearable placeholder="请输入金额" />
                        </el-form-item> </el-col>


                    <el-col :span="24">
                        <el-form-item label="是否生成凭证" prop="pay_type">
                            <el-radio-group v-model="formData.pay_type" placeholder="请选择是否生成凭证">
                                <el-radio v-for="(item, index) in dictData.pay_type" :key="index"
                                    :label="parseInt(item.value)">
                                    {{ item.name }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item> </el-col>
                    <el-col :span="24">
                        <el-form-item label="凭证编号" prop="main_content">
                            <el-input v-model="formData.main_content" clearable placeholder="请输入凭证编号" />
                        </el-form-item> </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" 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>


            </el-form>
        </popup>

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

<script lang="ts" setup name="procurementContractEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { toChinesNum } from "@/utils/util";
import supplierTable from '@/components/supplier/index.vue'
import { apiadministrativeAdd, apiadministrativeEdit, apiadministrativeDetail } from '@/api/administrative'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
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 supplier_contract_name = ref('')
const supplier_contract_no = ref('')
const formDataannex = reactive([])
const tableData = reactive([])
const list1 = reactive([])
const list2 = reactive([])
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import feedback from '@/utils/feedback'
import configs from "@/config"
const base_url = configs.baseUrl + configs.urlPrefix
import useUserStore from "@/stores/modules/user";
const userStore = useUserStore();
// 上传文件
const handleAvatarSuccess_four = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        feedback.msgError(response.msg);
        return;
    }
    formDataannex.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}

//监听金额大写输入
const amountinput = (e) => {
    // console.log(e)
    if (e && e > 0) {
        formData.amount_daxie = toChinesNum(e)
    }
}

//获取所有组织
const getlist = () => {
    getAll().then((res) => {
        Object.assign(list1, res)
        if (res.length > 0 && !formData.org_id) {
            formData.org_id = res[0].id
            deptAll({ 'org_id': res[0].id }).then((res) => {
                if (res.length > 0) {
                    Object.assign(list2, res)
                    formData.dept_id = res[0].id
                }

            })
        }
    })
}
//获取部门
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 popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑收支流水表' : '新增收支流水表'
})

// 表单数据
const formData = reactive({
    id: '',
    dept_id: '',
    org_id: '',
    supplier_id: 0,
    contract_no: "",
    contract_name: "",
    procurement_type: 0,
    asset_apply_no: "",
    start_date: "",
    end_date: "",
    signing_date: "",
    pay_type: '',
    amount: '',
    amount_daxie: "",
    main_content: "",
    remark: "",
    annex: []
})
const customEvent = (e: any) => {
    supplier_contract_name.value = e.supplier_name
    formData.supplier_id = e.id
    supplier_contract_no.value = e.supplier_code
    showDialog.value = false;

};

// 表单验证
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)
    }

    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]
        }
    }
    if (data.amount_daxie) {
        amountinput(data.amount_daxie)
    }
    //@ts-ignore
    formData.signing_date = timeFormat(formData.signing_date, 'YYYY-MM-DD ')
}

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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item) => item.uri)
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiadministrativeEdit(data)
        : await apiadministrativeAdd(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>
