<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="80%" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules" inline>
                <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="8">
                        <el-form-item label="项目名称" prop="project_id" @click="showDialog = true"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="project_name" readonly clearable placeholder="请输入项目名称" :disabled="project" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目编码" prop="project_id">
                            <el-input v-model="project_code" disabled clearable placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <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 formDataannex" 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">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" type="textarea" style="width:60vw" clearable
                                placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <div style=" display: flex;justify-content: flex-end;margin-bottom: 30px;">
                            <el-button @click="showDialog1 = true" type="primary" plain>选择材料</el-button>
                            <el-button type="primary" plain>清空</el-button>
                        </div>
                    </el-col>


                    <el-col :span="24">
                        <div style="margin-bottom: 30px;">材料预算清单</div>
                        <div style="margin-bottom: 30px;">
                            <el-table :data="tableData">
                                <el-table-column label="序号" type="index">
                                </el-table-column>

                                <el-table-column label="材料名称">
                                    <template #default="{ row }"> <el-input v-model="row.name" disabled />
                                    </template></el-table-column>
                                <el-table-column label="材料编码">
                                    <template #default="{ row }"> <el-input v-model="row.code" disabled />
                                    </template></el-table-column>

                                <el-table-column label="规格型号">
                                    <template #default="{ row }">
                                        <el-input v-model="row.specs" disabled />
                                    </template>
                                </el-table-column>

                                <el-table-column label="品牌">
                                    <template #default="{ row }">
                                        <el-input v-model="row.brand" disabled />
                                    </template>
                                </el-table-column>
                                <el-table-column label="参数说明">
                                    <template #default="{ row }">
                                        <el-input v-model="row.parameter_description" disabled />
                                    </template>
                                </el-table-column>
                                <el-table-column label="单位" prop="unit">
                                    <template #default="{ row }">
                                        <el-input v-model="row.unit" disabled />
                                    </template>
                                </el-table-column>
                                <el-table-column label="数量" prop="num">
                                    <template #default="{ row }">
                                        <el-input v-model="row.num" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="金额" prop="price">
                                    <template #default="{ row }">
                                        <el-input v-model="row.price" />
                                    </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-column label="管理" prop="amount_including_tax">
                                    <template #default="{ row }">
                                        <!-- <el-button @click="handleAdd(row)">+</el-button> -->
                                        <el-button @click="handleDelete(row)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-col>

                </el-row>
            </el-form>
            <el-dialog v-model="showDialog" title="选择项目" width="70%">
                <projectDialog @customEvent="customEvent"></projectDialog>
            </el-dialog>
            <div v-if="showDialog1">
                <el-dialog v-model="showDialog1" title="选择产品" width="70%">
                    <prodctTable @customEvent="customEvent1" :project_id='formData.project_id'></prodctTable>
                </el-dialog>
            </div>
        </popup>
    </div>
</template>

<script lang="ts" setup name="procurementContractEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import projectDialog from '@/components/project/index.vue'
import { MaterialbudgetDetailLists } from '@/api/project_material_budget_detail'
import prodctTable from '@/components/product/index.vue'
import { apiMaterialbudgetAdd, apiMaterialbudgetEdit, apiMaterialbudgetDetail } from '@/api/project_material_budget'
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 showDialog = ref(false)
const showDialog1 = ref(false)
const project_name = ref('')
const project_code = ref('')
const tableData = ref([])
const list1 = reactive([])
const list2 = reactive([])
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import configs from "@/config"
import useUserStore from "@/stores/modules/user";
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const formDataannex = reactive([])
// 表单数据
const formData = reactive({
    id: '',
    dept_id: '',
    org_id: '',
    project_id: '',
    material_budget_detail: [],
    remark: '',
    annex: [],
})


//获取值
const customEvent = (e) => {
    formData.project_id = e.id
    project_name.value = e.name
    project_code.value = e.project_code
    showDialog.value = false

}
if (props.project) customEvent(props.project);

const customEvent1 = (e) => {

    tableData.value.push({
        "material_id": e.id,
        "name": e.name,
        "code": e.code,
        'parameter_description': e.parameter_description,
        "brand": e.brand,
        "unit": e.unit,
        "specs": e.specs,
        "num": e.num,
        "price": e.price,
        "remark": e.remark
    })
    showDialog1.value = false

}
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑材料预算' : '新增材料预算'
})
// 上传文件
const handleAvatarSuccess_four = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex.push(
        { uri: response.data.uri, name: response.data.name }


    );
};

// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}



//获取所有组织
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 budgetDetailLists = (id) => {
    MaterialbudgetDetailLists({ 'page_no': 1, 'page_size': 20, material_budget_id: id }).then((res) => {

        tableData.value = res.lists.map((item: any) => ({
            "id": item.id,
            "material_id": item.material_id,
            "name": item.material_name,
            "code": item.material_code,
            'parameter_description': item.material_parameter_description,
            "brand": item.material_brand,
            "unit": item.material_unit,
            "specs": item.material_specs,
            "num": item.num,
            "price": item.price,
            "remark": item.remark
        }))
    })

}





const handleDelete = (row: any) => {
    // 删除 row
    const index = tableData.value.indexOf(row);
    tableData.value.splice(index, 1);
};

// 表单验证
const formRules = reactive<any>({

})




// 获取详情
const setFormData = async (data: Record<any, any>) => {
    if (data.annex && data.annex.length > 0) {

        const arry1 = data.annex.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex, arry1)
    }
    budgetDetailLists(data.id)
    if (data.dept_id) {
        getlist1(data.org_id)
    }
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    project_name.value = data.project_name
    project_code.value = data.project_code


}

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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item: any) => item.uri)
    }
    if (tableData.value.length > 0) {
        formData.material_budget_detail = tableData.value.map((item: any) => ({
            'id': item.id,
            "material_id": item.material_id,
            "num": item.num,
            "price": item.price,
            "remark": item.remark
        }))
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiMaterialbudgetEdit(data)
        : await apiMaterialbudgetAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

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


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