<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" 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" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <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">
                        <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">
                        <div style="margin-bottom: 30px;">分包预算清单</div>
                        <div style="margin-bottom: 30px;">
                            <el-table :data="tableData">
                                <el-table-column label="序号">
                                    <template #default="{ row }">
                                        <el-button @click="handleAdd(row)">+</el-button>
                                        <el-button @click="handleDelete(row)">-</el-button> </template>
                                </el-table-column>

                                <el-table-column label="工作类型">
                                    <template #default="{ row }"> <el-input v-model="row.work_type" />
                                    </template></el-table-column>
                                <el-table-column label="工作内容">
                                    <template #default="{ row }"> <el-input v-model="row.work_content" />
                                    </template></el-table-column>

                                <el-table-column label="项目特征">
                                    <template #default="{ row }">
                                        <el-input v-model="row.project_features" />
                                    </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, $index }">
                                        <el-input v-model="row.num" @input="subtractji1(row, $index)" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="单价" prop="price">
                                    <template #default="{ row, $index }">
                                        <el-input v-model="row.price" @input="subtractji1(row, $index)" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="金额" prop="amount">
                                    <template #default="{ row }">
                                        <el-input v-model="row.amount" />
                                    </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-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 { subpackagdetailLists } from '@/api/project_subpackage_budget_detail'
import prodctTable from '@/components/product/index.vue'
import { subpackagebudgetAdd, subpackagebudgetEdit, subpackagebudgetDetail } from '@/api/project_subpackage_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 person_name = ref('')
const idcard = 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: '',
    subpackage_budget_detail: [],
    remark: '',
    annex: [],
    approve_detail: {}
})


//获取值
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) => {
    // formData.project_person_id = e.id
    // idcard.value = e.idcard
    // person_name.value = e.name

    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 subtractji1 = (row: any, index: any) => {
    const num = Number(row.num) || 0;
    const price = Number(row.price) || 0;
    row.amount = num * price
}
//获取所有组织
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: any) => {
    subpackagdetailLists({ 'page_no': 1, 'page_size': 20, subpackage_budget_id: id }).then((res) => {

        tableData.value = res.lists.map((item: any) => ({
            "id": item.id,
            "work_type": item.work_type,
            "work_content": item.work_content,
            "project_features": item.project_features,
            "unit": item.unit,
            "num": item.num,
            "amount": item.amount,
            "price": item.price,
            "remark": item.remark
        }))
    })

}



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

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 subpackagebudgetDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    formData.annex = formDataannex.map((item: any) => item.uri)
    if (tableData.value.length > 0) {
        formData.subpackage_budget_detail = tableData.value.map((item: any) => ({
            'id': item.id,
            "work_type": item.work_type,
            "work_content": item.work_content,
            "project_features": item.project_features,
            "unit": item.unit,
            "num": item.num,
            "price": item.price,
            "remark": item.remark
        }))
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await subpackagebudgetEdit(data)
        : await subpackagebudgetAdd(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>
