<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="90px" :rules="formRules">
                <el-form-item label="组织" prop="org_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                    <el-select class="flex-1" readonly 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="部门" readonly prop="dept_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                    <el-select class="flex-1" v-model="formData.dept_id" clearable placeholder="请选择部门" @change="area_change1">
                        <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="请输入项目名称" />
                </el-form-item>
                <el-form-item label="项目编码" prop="project_id">
                    <el-input v-model="project_code
                        " readonly clearable placeholder="请输入项目编码" />
                </el-form-item>
                <el-form-item label="客户名称" prop="project_id">
                    <el-input v-model="custom_name
                        " readonly clearable placeholder="请输入客户名称" />
                </el-form-item>
                <el-form-item label="需求名称" prop="customer_demand_id" @click="showDialog1 = true">
                    <el-input v-model="customer_demand_name" clearable readonly placeholder="请输入需求名称" />
                </el-form-item>

                <el-form-item label="联系人" prop="contact_id" @click="showDialog2 = true">
                    <el-input v-model="contact_name" clearable readonly placeholder="请输入联系人" />
                </el-form-item>

                <el-form-item label="联系电话" prop="customer_demand_id">
                    <el-input v-model="contact_phone" clearable readonly placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="概算来源" prop="estimate_source">
                    <el-radio-group v-model="formData.estimate_source" placeholder="请选择概算来源">
                        <el-radio v-for="(item, index) in dictData.estimate_source" :key="index" :label="parseInt(item.value)">
                            {{ item.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="制单人" prop="create_user">
                    <el-input v-model="formData.create_user" clearable placeholder="请输入制单人" />
                </el-form-item>
                <el-form-item label="报价日期" prop="quotation_date">
                    <el-date-picker class="flex-1 !flex" v-model="formData.quotation_date" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择报价日期">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="发票类型" prop="invoice_type">
                    <el-radio-group v-model="formData.invoice_type" placeholder="请选择发票类型">
                        <el-radio v-for="(item, index) in dictData.invoice_type" :key="index" :label="parseInt(item.value)">
                            {{ item.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="技术人员id" prop="technician">

                    <el-select class="flex-1" v-model="formData.technician" clearable placeholder="请输入技术人员">
                        <el-option v-for="(item, index) in jlist" :key="index" :label="item.name" :value="parseInt(item.id)" />
                    </el-select>
                    <!-- <el-input v-model="formData.technician" clearable placeholder="请输入技术人员id" /> -->
                </el-form-item>
                <el-form-item label="概算金额" prop="estimate_amount">
                    <el-input v-model="formData.estimate_amount" clearable placeholder="请输入概算金额" />
                </el-form-item>
                <el-form-item label="要求" prop="ask">
                    <el-input v-model="formData.ask" 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-form>
        </popup>
        <el-dialog v-model="showDialog" title="选择项目" width="70%">
            <projectTable @customEvent="customEvent"></projectTable>
        </el-dialog>
        <el-dialog v-model="showDialog1" title="选择需求" width="70%">
            <customerdemand @customEvent="customEvent1" :productid="formData.project_id"></customerdemand>
        </el-dialog>
        <el-dialog v-model="showDialog2" title="选择需求" width="70%">
            <contactsTable @customEvent="customEvent2"></contactsTable>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="projectEstimateEdit">
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 contactsTable from "@/components/contacts/index.vue"
import { getAdminsByDept } from '@/api/common'
import { apiProjectEstimateAdd, apiProjectEstimateEdit, apiProjectEstimateDetail } from '@/api/project_estimate'
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 orglist = reactive([])
const jobs = reactive([])
const jlist = reactive([])
const project_name
    = ref('')
const project_code
    = ref('')
const custom_name
    = ref('')
const customer_demand_name = ref('')
const contact_name = ref('')
const contact_phone = ref('')
const formDataannex = reactive([])
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) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}
// dialog
const showDialog = ref(false)
const showDialog1 = ref(false)
const showDialog2 = 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;
};
const customEvent1 = (e: any) => {
    console.log(e.theme)
    formData.customer_demand_id = e.id;
    customer_demand_name.value = e.theme
    showDialog1.value = false;
};
const customEvent2 = (e: any) => {
    formData.contact_id = e.id;
    contact_name.value = e.name;
    contact_phone.value = e.phone
    showDialog2.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 area_change1 = (e: any) => {
    formData.dept_id = e
    let data = { 'dept_id': e }
    console.log(data)
    getAdminsByDept(data).then((res) => {
        Object.assign(jlist, res)
    })
}

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑项目概算' : '新增项目概算'
})

// 表单数据
const formData = reactive({
    id: '',
    org_id: '',
    dept_id: '',
    project_id: '',
    customer_demand_id: '',
    estimate_source: '',
    create_user: '',
    quotation_date: '',
    invoice_type: '',
    technician: '',
    estimate_amount: '',
    ask: '',
    annex: '',
    contact_id: ''
})


// 表单验证
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) {
        if (data.annex.includes(",")) {
            const arry1 = data.annex.split(',').map((item: any, index: any) => {
                return {
                    name: `文件${index + 1}`,
                    uri: item
                };
            });
            Object.assign(formDataannex, arry1)
        } else {
            const arry1 = [{ name: `文件1`, uri: data.annex }]
            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.quotation_date = timeFormat(formData.quotation_date, 'yyyy-mm-dd hh:MM:ss')
}

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


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