<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="600px" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
                <el-form-item label="项目名称" prop="project_id">
                    <el-input v-model="formData.project_name" clearable placeholder="点击选择" readonly
                        @click="showDialog = true" />
                </el-form-item>
                <!-- <el-form-item label="申请单号" prop="trip_apply_code">
                    <el-input v-model="formData.trip_apply_code" disabled clearable placeholder="后台zi" />
                </el-form-item> -->
                <el-form-item label="出差起始地" prop="origin_address" label-width="100px">
                    <el-input v-model="formData.origin_address" clearable placeholder="请输入出差起始地" />
                </el-form-item>
                <el-form-item label="出差目的地" prop="target_address" label-width="100px">
                    <el-input v-model="formData.target_address" clearable placeholder="请输入出差目的地" />
                </el-form-item>
                <el-form-item label="交通工具" prop="traffic">
                    <!-- <el-input v-model="formData.traffic" clearable placeholder="请输入交通工具" /> -->
                    <el-select v-model="formData.traffic" placeholder="请选择" class="flex-1">
                        <el-option :label="item.name" :value="item.value" v-for="item in dictData.traffic"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="出差时间" prop="start_date">
                    <el-date-picker class="flex-1 !flex" v-model="formData.start_date" clearable value-format="YYYY-MM-DD "
                        placeholder="请输入出差时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="end_date">
                    <el-date-picker class="flex-1 !flex" v-model="formData.end_date" clearable value-format="YYYY-MM-DD "
                        placeholder="请输入结束时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="出差事由" prop="reason">
                    <el-input v-model="formData.reason" clearable placeholder="请输入出差事由" />
                </el-form-item>
                <el-form-item label="历时天数" prop="days">
                    <el-input v-model="formData.days" clearable placeholder="请输入历时天数" type="number" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" clearable placeholder="请输入备注" />
                </el-form-item>
                <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 formData.annex" 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-form>

            <el-dialog v-model="showDialog" title="选择项目" width="70%">
                <projectDialog @customEvent="customEvent"></projectDialog>
            </el-dialog>

        </popup>
    </div>
</template>

<script lang="ts" setup name="projectTripApplyEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiProjectTripApplyAdd, apiProjectTripApplyEdit, apiProjectTripApplyDetail } from '@/api/project_trip_apply'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import projectDialog from '@/components/project/index.vue'
import configs from "@/config"
import useUserStore from "@/stores/modules/user";
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'


const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();

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 popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑项目财务-出差申请' : '新增项目财务-出差申请'
})

// 表单数据
const formData = reactive({
    id: '',
    "project_id": '',
    "project_name": '',
    "origin_address": '',
    "target_address": '',
    "traffic": '',
    "start_date": "",
    "end_date": "",
    "reason": "",
    "remark": "",
    "annex": [],
    days: ""
})
// 上传文件
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 customEvent = (e) => {
    console.log(e)
    formData.project_id = e.id
    formData.project_name = e.name
    showDialog.value = false
}

// 表单验证
const formRules = reactive<any>({
    project_id: [{
        required: true,
        message: '请输入项目id',
        trigger: ['blur']
    }],
    trip_apply_code: [{
        required: true,
        message: '请输入申请单号',
        trigger: ['blur']
    }],
    origin_address: [{
        required: true,
        message: '请输入出差起始地',
        trigger: ['blur']
    }],
    target_address: [{
        required: true,
        message: '请输入出差目的地',
        trigger: ['blur']
    }],
    traffic: [{
        required: true,
        message: '请输入交通工具',
        trigger: ['blur']
    }],
    start_date: [{
        required: true,
        message: '请输入出差时间',
        trigger: ['blur']
    }],
    end_date: [{
        required: true,
        message: '请输入结束时间',
        trigger: ['blur']
    }]
})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    formData.traffic = String(formData.traffic)
}

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


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiProjectTripApplyEdit(data)
        : await apiProjectTripApplyAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

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

const delFileFn = (index: number) => {
    formData.annex.splice(index, 1)
}

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