<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">
                <div style="display: flex; flex-direction: row-reverse; justify-content: flex-start;margin-bottom: 30px;">

                    <el-select class="w-[180px]" 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-select class="w-[180px]" 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>
                </div>
                <el-row :gutter="10">
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="project_id" @click="showDialog = true">
                            <el-input v-model="project_name" clearable readonly placeholder="请选择项目" />
                        </el-form-item>
                    </el-col> <el-col :span="8">
                        <el-form-item label="项目编码" prop="project_id">
                            <el-input v-model="project_code" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="仓库编码">
                            <el-input v-model="code" clearable disabled placeholder="系统自动生成" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="仓库名称" prop="name"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="formData.name" clearable placeholder="仓库名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="MRP仓库" prop="is_mrp"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <!-- <el-input v-model="project_code" clearable disabled placeholder="MRP仓库" /> -->
                            <el-switch v-model="formData.is_mrp" :active-value="1" :inactive-value="0" inline-prompt
                                active-text="是" inactive-text="否" />

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="负责人" prop="head_user" @click="userclick"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="head_user_name" readonly 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="telephone">
                            <el-input v-model="formData.telephone" clearable placeholder="请输入联系电话" />
                        </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>

                <el-dialog v-model="showDialog" title="选择项目" width="70%">
                    <projectDialog @customEvent="customEvent" contract_type="2"></projectDialog>
                </el-dialog>
            </el-form>
        </popup>
        <personnelselector ref="personnel" @confirm="submituser" type="1"></personnelselector>

    </div>
</template>

<script lang="ts" setup name="projectEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import personnelselector from '@/components/personnelselector/index.vue'
import { toChinesNum } from "@/utils/util";
import projectDialog from '@/components/project/index.vue'
import { materialwarehouseAdd, materialwarehouseEdit, materialwarehouseDetail } from '@/api/material_warehouse'
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 { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
const protype = reactive([])
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const active = ref(0)
const formDataannex = reactive([])
const head_user_name = ref('')
const project_name = ref('')
const project_code = ref('')
const code = ref('')
const list1 = reactive([])
const list2 = reactive([])
const personnel = ref<any>()
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 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 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 customEvent = (e: any) => {
    formData.project_id = e.id;
    project_name.value = e.name;
    project_code.value = e.project_code;

    showDialog.value = false;
};
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑仓库管理表' : '新增仓库管理表'
})

// 表单数据
const formData = reactive({
    id: '',
    org_id: '',
    dept_id: '',
    project_id: '',
    name: '',
    is_mrp: 1,
    head_user: '',
    address: '',
    telephone: '',
    remark: '',
    annex: [],
})

//获取所有组织
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 formRules = reactive<any>({

})

const userclick = () => {
    // console.log(personnel.value, '1111111')
    personnel.value.open()

}
//确认
const submituser = (e: any) => {
    formData.head_user = e.id;
    head_user_name.value = e.name;
}
// 获取详情
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)
    }
    getlist1(formData.org_id)
    project_name.value = data.project_name;
    project_code.value = data.project_code
    code.value = data.code
    head_user_name.value = data.head_user_name

    // contract_name.value = data.contract.contract_name;
    // contract_no.value = data.contract.contract_code


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


// 提交按钮
const handleSubmit = async () => {
    formData.annex = formDataannex.map((item: any) => item.uri)

    await formRef.value?.validate()


    const data = { ...formData }
    mode.value == 'edit'
        ? await materialwarehouseEdit(data)
        : await materialwarehouseAdd(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')
}

getlist()


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