<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="project_id">
                    <el-input v-model="formData.project_name" readonly clearable placeholder="点击选择项目"
                        @click="showDialog = true" />
                </el-form-item>
                <el-form-item label="调整日期" prop="adjust_date">
                    <!-- <el-input v-model="formData.adjust_date" clearable placeholder="请输入调整日期" /> -->
                    <el-date-picker class="flex-1 !flex" v-model="formData.adjust_date" clearable value-format="YYYY-MM-DD "
                        placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="调整金额" prop="adjust_amount">
                    <el-input v-model="formData.adjust_amount" clearable placeholder="请输入调整金额" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" 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 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-form>
            <el-dialog v-model="showDialog" title="选择项目" width="70%">
                <projectDialog @customEvent="customEvent"></projectDialog>
            </el-dialog>
        </popup>
    </div>
</template>

<script lang="ts" setup name="projectCostAdjustmentEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiProjectCostAdjustmentAdd, apiProjectCostAdjustmentEdit, apiProjectCostAdjustmentDetail } from '@/api/project_cost_adjustment'
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";

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 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 popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑项目财务-成本调整' : '新增项目财务-成本调整'
})

// 表单数据
const formData = reactive({
    id: '',
    "project_id": '',
    "adjust_date": "",
    "adjust_amount": "",
    "remark": "",
    "annex": [],
    project_name: ""
})

const customEvent = (e: any) => {
    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']
    }],
    adjust_date: [{
        required: true,
        message: '请输入调整日期',
        trigger: ['blur']
    }],
    adjust_amount: [{
        required: true,
        message: '请输入调整金额',
        trigger: ['blur']
    }],
    add_user: [{
        required: true,
        message: '请输入添加人',
        trigger: ['blur']
    }],
    update_user: [{
        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]
        }
    }


}

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


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

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

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



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