<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="60%" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="auto" :rules="formRules">
                <el-row>
                    <el-col :span="12">
                        <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-col><el-col :span="12">
                        <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-col><el-col :span="12">
                        <el-form-item label="项目名称" prop="project_id" @click="showDialog = true"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="project_name" readonly clearable placeholder="请输入项目名称" :disabled="project" />
                        </el-form-item></el-col><el-col :span="12">
                        <el-form-item label="项目编码" prop="project_id">
                            <el-input v-model="project_code" disabled clearable placeholder="系统自动填写" />
                        </el-form-item></el-col><el-col :span="12">
                        <el-form-item label="客户名称" prop="project_id">
                            <el-input v-model="custom_name" disabled placeholder="系统自动填写" />
                        </el-form-item></el-col><el-col :span="12">
                        <el-form-item label="需求名称" prop="customer_demand_id" @click="demandclck">
                            <el-input v-model="customer_demand_name" clearable readonly placeholder="请选择需求" />
                        </el-form-item></el-col><el-col :span="12">

                        <el-form-item label="联系人" prop="contact_id" @click="showDialog2 = true">
                            <el-input v-model="contact_name" clearable readonly placeholder="请选择联系人" />
                        </el-form-item></el-col><el-col :span="12">

                        <el-form-item label="联系电话" prop="contact_phone"
                            :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                            <el-input v-model="contact_phone" clearable disabled placeholder="系统自动填写" />
                        </el-form-item></el-col><el-col :span="24">
                        <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-col><el-col :span="12">
                        <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="date"
                                value-format="YYYY-MM-DD" placeholder="选择报价日期">
                            </el-date-picker>
                        </el-form-item></el-col>
                    <el-col :span="24">

                        <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-col><el-col :span="12">
                        <el-form-item label="技术人员" 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-col><el-col :span="12">
                        <el-form-item label="概算金额" prop="estimate_amount">
                            <el-input v-model="formData.estimate_amount" clearable placeholder="请输入概算金额" />
                        </el-form-item></el-col><el-col :span="12">
                        <el-form-item label="要求" prop="ask">
                            <el-input v-model="formData.ask" 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-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%">
                    <customerdemand @customEvent="customEvent1" :productid="formData.project_id"></customerdemand>
                </el-dialog>
            </div>
            <div v-if="showDialog2">
                <el-dialog v-model="showDialog2" title="选择联系人" width="70%">
                    <contactsTable @customEvent="customEvent2" :custom_id="customid"></contactsTable>
                </el-dialog>
            </div>
        </popup>
    </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 { useDictData } from '@/hooks/useDictOptions'
import { getAdminsByDept } from '@/api/common'
import { apiProjectEstimateAdd, apiProjectEstimateEdit, apiProjectEstimateDetail } from '@/api/project_estimate'
let props = defineProps({
    project: Object
})
const emit = defineEmits(['success', 'close'])
const { dictData } = useDictData('estimate_source,invoice_type')

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 customid = ref('')
const formDataannex = reactive([])
import configs from "@/config"
const base_url = configs.baseUrl + configs.urlPrefix
import useUserStore from "@/stores/modules/user";
import feedback from '@/utils/feedback'

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)
}
// 表单数据
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: ''
})

// dialog
const showDialog = ref(false)
const showDialog1 = ref(false)
const showDialog2 = ref(false)


const customEvent = (e: any) => {
    formData.project_id = e.id;
    customid.value = e.custom_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) => {
    // 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 demandclck = () => {
    if (formData.project_id) {
        showDialog1.value = true;
    } else {
        feedback.msgError('请先选择项目')
    }
}

//验证
const checkPhone = (rule: any, value: any, callback: (arg0: Error) => any) => {

    if (value && !/^1\d{10}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
    } else {
        callback()
    }

}
// 弹窗标题
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)
    })

    // console.log(jobs)
    contact_name.value = data.contact_name
    contact_phone.value = data.contact_phone

    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]
        }
    }
    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)
    }
    //@ts-ignore
    // formData.quotation_date = timeFormat(formData.quotation_date, 'YYYY-MM-DD ')
}

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)
    }
    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>
