<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="85vw" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
                <div
                    style="display: flex; flex-direction: row-reverse; justify-content: flex-start;margin-bottom: 30px;">

                    <el-select class="w-[180px]" v-model="formData.dept_id" clearable placeholder="请选择部门">
                        <el-option v-for="(item, index) in list2" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                    <el-select class="w-[180px]" v-model="formData.org_id" clearable placeholder="请选择组织"
                        @change="deptrmt">
                        <el-option v-for="(item, index) in list1" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                </div>
                <el-form-item label="项目名称" prop="project_id">
                    <el-input v-model="formData.project_name" clearable placeholder="点击选择项目" :disabled="project"
                        @click="showDialog = true" />
                </el-form-item>
                <el-form-item label="项目编码" prop="remark">
                    <el-input v-model="formData.project_code" disabled clearable placeholder="系统自动输入" />
                </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="附件">
                        <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-col :span="24">
                    <div style="margin-bottom: 30px;">机器预算清单</div>
                    <div style="margin-bottom: 30px;">
                        <el-table :data="formData.equipment_budget_detail">
                            <el-table-column label="序号">
                                <template #default="{ row }">
                                    <el-button @click="handleAdd(row)" size="small">+</el-button>
                                    <el-button @click="handleDelete(row)" size="small">-</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column label="机具类别">
                                <template #default="{ row }">
                                    <el-input v-model="row.type" placeholder="请输入" />
                                </template></el-table-column>
                            <el-table-column label="机具名称">
                                <template #default="{ row }"> <el-input v-model="row.name" />
                                </template></el-table-column>
                            <el-table-column label="规格型号">
                                <template #default="{ row }">
                                    <el-input v-model="row.spec" />
                                </template>
                            </el-table-column>
                            <el-table-column label="单价">
                                <template #default="{ row }">
                                    <el-input v-model="row.price" type="number" />
                                </template>
                            </el-table-column>
                            <el-table-column label="预算数量">
                                <template #default="{ row }">
                                    <el-input v-model="row.num" type="number" />
                                </template>
                            </el-table-column>
                            <el-table-column label="单位">
                                <template #default="{ row }">
                                    <el-input v-model="row.unit" type="number" />
                                </template>
                            </el-table-column>
                            <!-- <el-table-column label="金额">
                                <template #default="{ row }">
                                    <el-input v-model="row.price" type="number" />
                                </template>
                            </el-table-column> -->
                            <el-table-column label="备注" prop="remark">
                                <template #default="{ row }">
                                    <el-input v-model="row.remark" />
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </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="projectEquipmentBudgetEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiProjectEquipmentBudgetAdd, apiProjectEquipmentBudgetEdit, apiProjectEquipmentBudgetDetail } from '@/api/project_equipment_budget'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import configs from "@/config"
import useUserStore from "@/stores/modules/user";
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import projectDialog from '@/components/project/index.vue'
import { apiProjectEquipmentBudgetDetailLists } from "@/api/project_equipment_budget_detail.ts"

const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const list1 = reactive([])
const list2 = reactive([])
const showDialog = ref(false)
const props = defineProps({
    project: Object
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')



// 上传文件
const handleAvatarSuccess_four = (response: any) => {
    formData.annex ||= []
    // @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: '',
    "org_id": '',
    "dept_id": '',
    "project_id": 0,
    "project_name": '',
    project_code: "",
    "remark": "",
    "annex": [],
    "equipment_budget_detail": [
        {
            "type": "",
            "name": "",
            "spec": "",
            "unit": "",
            "num": 0,
            "price": 0,
            "remark": ""
        }
    ],
    approve_detail: {},
    approve_id: 0
})

const customEvent = (e) => {
    formData.project_id = e.id
    formData.project_code = e.project_code
    formData.project_name = e.name
    showDialog.value = false
}
if (props.project) customEvent(props.project)

// 表单验证
const formRules = reactive<any>({
    org_id: [{
        required: true,
        message: '请输入组织id',
        trigger: ['blur']
    }],
    dept_id: [{
        required: true,
        message: '请输入部门id',
        trigger: ['blur']
    }],
    project_id: [{
        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]
        }
    }

    let res = await apiProjectEquipmentBudgetDetailLists({ equipment_budget_id: data.id })
    formData.equipment_budget_detail = []
    Object.assign(formData.equipment_budget_detail, res.lists)
}

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


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

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

}

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

//获取所有组织
const getlist = () => {
    getAll().then((res) => {
        Object.assign(list1, res)
        if (res.length > 0 && !formData.org_id) {
            formData.org_id = res[0].id
            deptAll({ 'org_id': res[0].id }).then((res) => {
                if (res.length > 0) {
                    Object.assign(list2, res)
                    formData.dept_id = res[0].id
                }
            })
        }
    })
}
//获取部门
const deptrmt = (e: any) => {
    formData.dept_id = ''
    getlist1(e)
}

//获取所有部门
const getlist1 = (id: any) => {
    deptAll({ 'org_id': id }).then((res) => {
        list2.splice(0, list2.length, ...res)
    })
}

const handleAdd = (row: any) => {
    // 在 row 后面插入一行数据
    const index = formData.equipment_budget_detail.indexOf(row);
    formData.equipment_budget_detail.splice(index + 1, 0, {});
};

const handleDelete = (row: any) => {
    // 删除 row
    if (formData.equipment_budget_detail.length <= 1) return
    const index = formData.equipment_budget_detail.indexOf(row);
    formData.equipment_budget_detail.splice(index, 1);
};

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