<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="140px" :rules="formRules">
                <el-tabs v-model="activeName" @tab-click="handleClick">
                    <el-tab-pane label="基本信息" name="first">
                        <el-row>

                            <el-col :span="8">
                                <el-form-item label="建档人" prop="create_user_id">
                                    <el-input v-model="create_user_name" readonly clearable placeholder="请输入建档人" />
                                </el-form-item></el-col>
                            <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_code">
                                    <el-input v-model="formData.supplier_code" readonly clearable placeholder="系统默认生成" />
                                </el-form-item></el-col>
                            <el-col :span="8">
                                <el-form-item label="供应商名称" prop="supplier_name" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                                    <el-input v-model="formData.supplier_name" clearable placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="供应商简介" prop="supplier_introduction">
                                    <el-input v-model="formData.supplier_introduction" type="textarea" clearable placeholder="请输入" />
                                </el-form-item></el-col>

                            <el-col :span="8">
                                <el-form-item label="品牌类别" prop="brand_category">
                                    <el-input v-model="formData.brand_category" clearable placeholder="请输入" />
                                </el-form-item></el-col>
                            <el-col :span="24">
                                <el-form-item label="供应商照片" prop="supplier_photos">
                                    <material-picker v-model="formData.supplier_photos" />
                                </el-form-item></el-col>
                            <el-col :span="24">
                                <el-form-item label="供应商分组" label-width="130px" prop="supplier_group">
                                    <el-radio-group v-model="formData.supplier_group" placeholder="请选择供应商分组">
                                        <el-radio v-for="(item, index) in dictData.supplier_group" :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="供应商分类" label-width="130px" prop="supplier_category">
                                    <el-radio-group v-model="formData.supplier_category" placeholder="请选择供应商分类">
                                        <el-radio v-for="(item, index) in dictData.supplier_category" :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="供应商等级" label-width="130px" prop="supplier_grade">
                                    <el-radio-group v-model="formData.supplier_grade" placeholder="请选择供应商等级">
                                        <el-radio v-for="(item, index) in dictData.supplier_grade" :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="contacts">
                                    <el-input v-model="formData.contacts" clearable placeholder="请输入" />
                                </el-form-item></el-col>
                            <el-col :span="24">
                                <el-form-item label="性别" label-width="130px" prop="contacts_sex">
                                    <el-radio-group v-model="formData.contacts_sex" placeholder="请选择性别">
                                        <el-radio v-for="(item, index) in dictData.sex" :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="birthday">

                                    <el-date-picker v-model="formData.birthday" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择出生日期" clearable></el-date-picker>
                                </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="email" :rules="[{ validator: userEmail, trigger: 'blur' }]">

                                    <el-input v-model="formData.email" clearable placeholder="请输入" /> </el-form-item></el-col>


                            <el-col :span="8">
                                <el-form-item label="地址" prop="address">
                                    <el-input v-model="formData.address" clearable placeholder="请输入" />
                                </el-form-item></el-col>


                            <el-col :span="8">
                                <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-tab-pane>
                    <el-tab-pane label="开票信息" name="second">
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label="开票公司名称" prop="invoice_company_name">
                                    <el-input v-model="formData.invoice_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="bank_name">
                                    <el-input v-model="formData.bank_name" clearable placeholder="请输入" />
                                </el-form-item></el-col>
                            <el-col :span="8">
                                <el-form-item label="开户名称" prop="bank_accnout_name">
                                    <el-input v-model="formData.bank_accnout_name" clearable placeholder="请输入" />
                                </el-form-item></el-col>
                            <el-col :span="8">
                                <el-form-item label="账号" prop="bank_account">
                                    <el-input v-model="formData.bank_account" clearable placeholder="请输入" />
                                </el-form-item></el-col>
                            <el-col :span="8">
                                <el-form-item label="开户地址" prop="bank_address">
                                    <el-input v-model="formData.bank_address" clearable placeholder="请输入" />
                                </el-form-item></el-col>
                            <el-col :span="8">
                                <el-form-item label="期初未开票金额(元)" prop="init_invoice_amount">
                                    <el-input v-model="formData.init_invoice_amount" type="number" clearable placeholder="请输入" />
                                </el-form-item></el-col>

                        </el-row>
                    </el-tab-pane>
                    <el-tab-pane label="账期管理" name="third">

                        <el-col :span="8">
                            <el-form-item label="授信额度(元)" prop="credit_limit">
                                <el-input v-model="formData.credit_limit" type="number" clearable placeholder="请输入" />
                            </el-form-item></el-col>
                        <el-col :span="8">
                            <el-form-item label="账期(元)" prop="account_period">
                                <el-input v-model="formData.account_period" type="number" clearable placeholder="请输入" />
                            </el-form-item></el-col>
                    </el-tab-pane>
                </el-tabs>

            </el-form>
            <reviewprocess />
        </popup>
        <el-dialog v-model="showDialog" title="选择项目" width="70%">
            <projectTable @customEvent="customEvent"></projectTable>

        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="bidBiddingDecisionEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import reviewprocess from '@/components/reviewprocess/index.vue'

import projectTable from "@/components/project/index.vue"

import { apisupplierAdd, apisupplierEdit, apisupplierDetail } from '@/api/suppler_list'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const create_user_name = ref('')
const project_name = ref('')
const project_code = ref('')
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const showDialog = ref(false)
const list1 = reactive([])
const list2 = reactive([])
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import configs from "@/config"
const base_url = configs.baseUrl + configs.urlPrefix
import useUserStore from "@/stores/modules/user";

const userStore = useUserStore();
const userInfo = userStore.userInfo
const formDataannex = reactive([])
// 上传文件
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)
}
//获取值
const customEvent = (e: any) => {
    formData.project_id = e.id;
    project_name.value = e.custom_name
    project_code.value = e.project_code
    showDialog.value = false;
};
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑供应商管理' : '新增供应商管理'
})

//分页点击
const activeName = ref('first')

const handleClick = (tab: TabsPaneContext, event: Event) => {
    // console.log(tab, event)
}
//获取所有组织
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 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 deptrmt = (e: any) => {
    formData.dept_id = ''
    getlist1(e)

}
//获取所有部门
const getlist1 = (id: any) => {
    deptAll({ 'org_id': id }).then((res) => {
        Object.assign(list2, res)
    })
}
// 表单数据
const formData = reactive({
    id: '',
    dept_id: '',
    org_id: '',
    create_user_id: "",
    supplier_code: "",
    supplier_name: "",
    supplier_introduction: "",
    brand_category: "",
    supplier_photos: "",
    supplier_group: "",
    supplier_category: "",
    supplier_grade: "",
    contacts: "",
    contacts_sex: "",
    birthday: "",
    phone: "",
    email: "",
    address: "",
    remark: "",
    annex: "",
    invoice_company_name: "",
    taxpayer_identification_number: "",
    bank_name: "",
    bank_accnout_name: "",
    bank_account: "",
    bank_address: "",
    init_invoice_amount: "",
    credit_limit: "",
    account_period: ""
})


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


}

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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = JSON.stringify(formDataannex.map((item: any) => item.uri))
    }
    if (formData.supplier_photos.length > 0) {
        formData.supplier_photos = JSON.stringify(formData.supplier_photos)
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apisupplierEdit(data)
        : await apisupplierAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    if (!formData.create_user_id) {

        create_user_name.value = userInfo.name
        formData.create_user_id = userInfo.id
    }
    popupRef.value?.open()
    getlist()
}

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



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