<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="550px" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <el-form-item label="组织" prop="org_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                    <el-select class="flex-1" v-model="formData.org_id" clearable placeholder="请选择组织" @change="area_change">
                        <el-option v-for="(item, index) in orglist" :key="index" :label="item.name"
                            :value="parseInt(item.id)" />
                    </el-select>
                </el-form-item>
                <el-form-item label="部门" prop="dept_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                    <el-select class="flex-1" v-model="formData.dept_id" clearable placeholder="请选择部门">
                        <el-option v-for="(item, index) in jobs" :key="index" :label="item.name"
                            :value="parseInt(item.id)" />
                    </el-select>
                </el-form-item>
                <el-form-item label="项目名称" prop="project_id" @click="showDialog = true"
                    :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                    <el-input v-model="project_name" clearable placeholder="请选择项目" :disabled="project" />
                </el-form-item>
                <el-form-item label="项目编码" prop="project_id">
                    <el-input v-model="project_code
                        " clearable disabled placeholder="系统自动填写" />
                </el-form-item>
                <el-form-item label="客户名称" prop="project_id">
                    <el-input v-model="custom_name
                        " clearable disabled placeholder="系统自动填写" />
                </el-form-item>
                <el-form-item label="需求主题" prop="theme">
                    <el-input v-model="formData.theme" clearable placeholder="请输入需求主题" />
                </el-form-item>
                <el-form-item label="需求提供人" prop="supplier">
                    <el-input v-model="formData.supplier" clearable placeholder="请输入需求提供人" />
                </el-form-item>
                <el-form-item label="提供人联系方式" prop="supplier_contacts"
                    :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                    <el-input v-model="formData.supplier_contacts" clearable placeholder="请输入提供人联系方式" />
                </el-form-item>
                <el-form-item label="重要程度" prop="importance">
                    <el-radio-group v-model="formData.importance" placeholder="请选择重要程度">
                        <el-radio v-for="(item, index) in dictData.importance" :key="index" :label="parseInt(item.value)">
                            {{ item.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="记录时间" prop="recording_time">
                    <el-date-picker class="flex-1 !flex" v-model="formData.recording_time" clearable type="date"
                        value-format="YYYY-MM-DD" placeholder="选择记录时间">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="需求内容" prop="demand_content">
                    <el-input v-model="formData.demand_content" clearable placeholder="请输入需求内容" />
                </el-form-item>
                <el-form-item label="附件" prop="field127">
                    <annexUpload :annex="formData.annex" @handleAvatarSuccess="handleAvatarSuccess_four"
                        @delFile="delFileFn" />
                </el-form-item>
            </el-form>
        </popup>
        <el-dialog v-model="showDialog" title="选择项目" width="70%">
            <projectTable @customEvent="customEvent"></projectTable>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="customerDemandEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import projectTable from "@/components/project/index.vue"
import { apiCustomerDemandAdd, apiCustomerDemandEdit, apiCustomerDemandDetail } from '@/api/customer_demand'
import { useDictData } from '@/hooks/useDictOptions'
// 上传文件
import annexUpload from "@/components/annexUpload/index.vue"
const handleAvatarSuccess_four = (response: any) => {
    // @ts-ignore
    response.code != 0 ? formData.annex.push({ uri: response.data.uri, name: response.data.name }) : ElMessage.error(response.msg);
};
// 删除上传的文件
const delFileFn = (index: number) => { formData.annex.splice(index, 1) }

let props = defineProps({
    project: Object
})
const { dictData } = useDictData('importance')

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const orglist = reactive([])
const jobs = reactive([])
const project_name
    = ref('')
const project_code
    = ref('')
const custom_name
    = ref('')
const formDataannex = reactive([])




const getlista = () => {
    getAll().then((res) => {
        // orglist = res.data

        Object.assign(orglist, res)

    })
}

const area_change = (e: any) => {
    formData.org_id = e
    let data = { 'org_id': e }
    // console.log(data)
    deptAll(data).then((res) => {

        Object.assign(jobs, res)

    })
}
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑客户需求' : '新增客户需求'
})

// 表单数据
const formData = reactive({
    id: '',
    org_id: '',
    dept_id: '',
    project_id: '',
    theme: '',
    supplier: '',
    supplier_contacts: '',
    importance: '',
    recording_time: '',
    demand_content: '',
    annex: [],
})

// dialog
const showDialog = ref(false)
const customEvent = (e: any) => {
    formData.project_id = e.id;
    project_name.value = e.name;
    project_code
        .value = e.project_code;
    custom_name
        .value = e.custom_name;
    showDialog.value = false;
};

if (props.project) {
    customEvent(props.project)
}
// 表单验证
const formRules = reactive<any>({

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    deptAll({ 'org_id': data.org_id }).then((res) => {
        Object.assign(jobs, res)
    })
    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)
    }
    project_name.value = data.project_name
    custom_name.value = data.custom_name
    project_code.value = data.project_code
    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 apiCustomerDemandDetail({
        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 apiCustomerDemandEdit(data)
        : await apiCustomerDemandAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

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


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