<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="点击选择项目" @click="showDialog = true"
                        :disabled="project" />
                </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="附件" 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-col :span="24">
                    <div style="margin-bottom: 30px;">费用预算清单</div>
                    <div style="margin-bottom: 30px;">
                        <el-table :data="formData.cost_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="scope">
                                    <el-input v-model="scope.row.first_level_subject" @click="openDialog1(scope)" readonly
                                        placeholder="点击选择" />
                                </template>
                                <!-- <template #default="scope">
                                    <div style="display: flex; align-items: center">
                                        <el-icon @click="openDialog1(scope)">
                                            <timer />
                                        </el-icon>
                                    </div>
                                </template> -->

                            </el-table-column>

                            <el-table-column label="单位">
                                <template #default="{ row }"> <el-input v-model="row.unit" />
                                </template></el-table-column>
                            <el-table-column label="预算金额">
                                <template #default="{ row }">
                                    <el-input v-model="row.amount" type="number" />
                                </template>
                            </el-table-column>
                            <el-table-column label="编制标准">
                                <template #default="{ row }">
                                    <el-input v-model="row.standard" />
                                </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" :is_budget="1"></projectDialog>
            </el-dialog>
            <el-dialog v-model="showDialog1" title="选择科目" width="70%">
                <projectcostTemLists @customEvent="customEvent1"></projectcostTemLists>
            </el-dialog>

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

<script lang="ts" setup name="projectCostBudgetEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiProjectCostBudgetAdd, apiProjectCostBudgetEdit, apiProjectCostBudgetDetail } from '@/api/project_cost_budget'
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import projectDialog from '@/components/project/index.vue'
import projectcostTemLists from '@/components/projectcostTemLists/index.vue'

import configs from "@/config"
import useUserStore from "@/stores/modules/user";
import { apiProjectCostBudgetDetailLists } from "@/api/project_cost_budget_detail.ts"


const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const list1 = reactive([])
const list2 = reactive([])
const showDialog = ref(false)
const showDialog1 = ref(false)


let props = defineProps({
    project: Object
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')


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

// 表单数据
const formData = reactive({
    id: '',
    "org_id": '',
    "dept_id": '',
    "project_id": '',
    project_code: "",
    "remark": "",
    "annex": [],
    project_name: "",
    "cost_budget_detail": [
        {
            "project_cost_temp_id": '',
            first_level_subject: "",
            "unit": "",
            "amount": 0,
            "standard": "",
            "remark": ""
        }
    ]
})
const customEvent = (e: any) => {
    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);

// 获取点击行的index
let rowIndex = 0
const openDialog1 = (e: any) => {
    rowIndex = e.$index
    showDialog1.value = true
}
const customEvent1 = (e: any) => {
    formData.cost_budget_detail[rowIndex].first_level_subject = e.first_level_subject
    formData.cost_budget_detail[rowIndex].project_cost_temp_id = e.id
    showDialog1.value = false
}


// 表单验证
const formRules = reactive<any>({
    project_id: [{
        required: true,
        message: '请输入项目id',
        trigger: ['blur']
    }],
    cost_budget_code: [{
        required: true,
        message: '请输入费用预算单号',
        trigger: ['blur']
    }],
    org_id: [{
        required: true,
        message: '请输入组织id',
        trigger: ['blur']
    }],
    dept_id: [{
        required: true,
        message: '请输入部门id',
        trigger: ['blur']
    }]
})

// 上传文件
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 setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    getlist1(data.org_id)
    let res = await apiProjectCostBudgetDetailLists({ cost_budget_id: data.id })
    formData.cost_budget_detail = []
    Object.assign(formData.cost_budget_detail, res.lists)

}

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


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiProjectCostBudgetEdit(data)
        : await apiProjectCostBudgetAdd(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.cost_budget_detail.indexOf(row);
    formData.cost_budget_detail.splice(index + 1, 0, {});
};

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

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