<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" readonly clearable placeholder="点击选择项目"
                        @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="附件" 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.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" />
                                </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'


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

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 jobList = ref([])
const getJobList = async () => {
    let res = await projectjobtypeLists()
    jobList.value = res.lists
}
getJobList()

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

// 表单数据
const formData = reactive({
    "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) => {
    console.log(e)
    formData.project_id = e.id
    formData.project_code = e.project_code
    formData.project_name = e.name
    showDialog.value = 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 formRules = reactive<any>({
    org_id: [{
        required: true,
        message: '请输入组织id',
        trigger: ['blur']
    }],
    dept_id: [{
        required: true,
        message: '请输入部门id',
        trigger: ['blur']
    }],
    project_id: [{
        required: true,
        message: '请输入项目id',
        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]
        }
    }
    console.log(data)
    console.log(formData, "formdata")
}

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 = (row: any) => {
    // 删除 row
    if (formData.labor_budget_detail.length <= 1) return
    const index = formData.labor_budget_detail.indexOf(row);
    formData.labor_budget_detail.splice(index, 1);
};

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