<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-row>
                    <el-col :span="12">
                        <el-form-item label="项目名称">
                            <el-input v-model="formData.project_name" clearable placeholder="点击选择项目" :disabled="project"
                                @click="showDialog = true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目编码" prop="remark">
                            <el-input v-model="formData.project_code" disabled clearable placeholder="系统自动输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" clearable placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="附件">
                            <uploadAnnex :formData="formData"></uploadAnnex>
                        </el-form-item>
                    </el-col>
                </el-row>



                <el-col :span="24">
                    <div style="margin-bottom: 30px;">人工预算清单</div>
                    <div style="margin-bottom: 30px;">
                        <el-table :data="formData.labor_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-select v-model="row.job_type_id">
                                        <el-option :label="item.type_name" :value="item.id"
                                            v-for="item in jobList"></el-option>
                                    </el-select>
                                </template></el-table-column>
                            <el-table-column label="人工说明">
                                <template #default="{ row }"> <el-input v-model="row.desc" />
                                </template></el-table-column>

                            <el-table-column label="单位">
                                <template #default="{ row }">
                                    <el-input v-model="row.unit" v-type="'unit'" />
                                </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.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" :is_budget="1"></projectDialog>
            </el-dialog>

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

<script lang="ts" setup name="projectLaborBudgetEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiProjectLaborBudgetAdd, apiProjectLaborBudgetEdit, apiProjectLaborBudgetDetail } from '@/api/project_labor_budget'
import type { PropType } from 'vue'
import projectDialog from '@/components/project/index.vue'
import { projectjobtypeLists } from "@/api/project_job_type.ts";
import configs from "@/config"
import useUserStore from "@/stores/modules/user";
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import { apiProjectLaborBudgetDetailLists, apiProjectLaborBudgetDetailDelete } from "@/api/project_labor_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 jobList = ref([])
const getJobList = async () => {
    let res = await projectjobtypeLists()
    jobList.value = res.lists
}
getJobList()

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

// 表单数据
const formData = reactive({
    id: "",
    "org_id": '',
    "dept_id": '',
    "project_id": '',
    "project_name": '',
    "project_code": '',
    "remark": "",
    "annex": [],
    "labor_budget_detail": [
        {
            "job_type_id": '',
            "desc": "",
            "unit": "",
            "num": 0,
            "price": 0,
            "remark": ""
        }

    ],

})

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']
    }],
    labor_budget_code: [{
        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 apiProjectLaborBudgetDetailLists({ labor_budget_id: data.id })
    formData.labor_budget_detail.splice(0, 9999)
    Object.assign(formData.labor_budget_detail, res.lists)
    getlist1(data.org_id)

}

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

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

const handleDelete = async (row: any) => {
    if (row.id) await apiProjectLaborBudgetDetailDelete({ id: row.id })
    // 删除 row
    const index = formData.labor_budget_detail.indexOf(row);
    formData.labor_budget_detail.splice(index, 1);
};

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