<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="650px" @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: 'blur' }]">
                    <el-input v-model="project_name" readonly clearable placeholder="请输入项目名称" :disabled="project" />
                </el-form-item>
                <el-form-item label="项目编码" prop="project_id">
                    <el-input v-model="project_code" disabled clearable placeholder="系统自动填写" />
                </el-form-item>
                <el-form-item label="客户名称" prop="project_id">
                    <el-input v-model="custom_name" disabled clearable placeholder="系统自动填写" />
                </el-form-item>
                <el-form-item label="需求名称" prop="customer_demand_id">
                    <el-input v-model="customer_demand_name" clearable placeholder="输入需求名称" @click="showDialog1 = true" />
                </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="submission_time">
                    <el-date-picker class="flex-1 !flex" v-model="formData.submission_time" clearable
                        value-format="YYYY-MM-DD" placeholder="选择提交时间">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="方案内容" prop="solution_content">
                    <el-input v-model="formData.solution_content" clearable placeholder="请输入方案内容" />
                </el-form-item>
                <el-form-item label="客户反馈" prop="customer_feedback">
                    <el-input v-model="formData.customer_feedback" clearable placeholder="请输入客户反馈" />
                </el-form-item>
                <el-form-item label="附12件" prop="field127">
                    <annexUpload :annex="formData.annex" @handleAvatarSuccess="handleAvatarSuccess_four"
                        @delFile="delFileFn" />
                </el-form-item>
            </el-form>
            <el-dialog v-model="showDialog" title="选择项目" width="70%">
                <projectTable @customEvent="customEvent"></projectTable>
            </el-dialog>

            <div v-if="showDialog1">
                <el-dialog v-model="showDialog1" title="选择需求" width="70%" :z-index="99999">
                    <customerdemand @customEvent="customEvent1" :productid="formData.project_id">
                    </customerdemand>
                </el-dialog>
            </div>
        </popup>


    </div>
</template>

<script lang="ts" setup name="customerDemandSolutionEdit">
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 customerdemand from "@/components/customerdemand/index.vue"
import { apiCustomerDemandSolutionAdd, apiCustomerDemandSolutionEdit, apiCustomerDemandSolutionDetail } from '@/api/customer_demand_solution'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'


// 上传文件
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) }
// 表单数据
const formData = reactive({
    id: '',
    org_id: '',
    dept_id: '',
    project_id: '',
    customer_demand_id: '',
    theme: '',
    submission_time: '',
    solution_content: '',
    customer_feedback: '',
    annex: [],
})


let props = defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    },
    project: Object
})
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 customer_demand_name = ref('')
const formDataannex = reactive([])

const showDialog = ref(false)
const showDialog1 = 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 customEvent1 = (e: any) => {
    formData.customer_demand_id = e.id;
    customer_demand_name.value = e.theme;

    showDialog1.value = false;
};
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 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)
    }
    console.log(jobs)
    project_name.value = data.project_name
    custom_name.value = data.custom_name
    project_code.value = data.project_code
    customer_demand_name.value = data.customer_demand_name
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    //@ts-ignore
    formData.submission_time = timeFormat(formData.submission_time, 'yyyy-mm-dd')
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiCustomerDemandSolutionDetail({
        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 apiCustomerDemandSolutionEdit(data)
        : await apiCustomerDemandSolutionAdd(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>
