<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="auto" :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="8">
                        <el-form-item label="项目名称" prop="project_id" @click="showDialog2 = true"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="project_name" clearable placeholder="请输入项目名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目编码" prop="project_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="project_code" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同金额(元)" prop="contract_amount"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.contract_amount" type="number" clearable placeholder="请输入合同金额(元)" />

                        </el-form-item>
                    </el-col>
                </el-row>
                <br />
                <el-row>
                    <el-table :data="tableData" :summary-method="getSummaries" show-summary>
                        <el-table-column label="序号" type="index" width="120">
                        </el-table-column>
                        <el-table-column label="分项">
                            <template #default="{ row, $index }">
                                <div>{{ row.name }}</div>
                                <div>{{ row.text }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column label="预算成本" prop="cost">
                            <template #default="{ row, $index }">
                                <el-input v-model="formData[row.value]" @change="calColumnRate" />
                            </template>
                        </el-table-column>
                        <el-table-column label="成本占比" prop="rate" width="156">
                            <template #default="{ row }">
                                {{ row.rate }}
                            </template>
                        </el-table-column>
                    </el-table>
                </el-row>

                <el-row style="margin: 20px 0;">
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" type="textarea" clearable placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目经理" prop="project_manager"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.project_manager" clearable placeholder="请输入项目经理" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="预算日期" prop="budget_date"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-date-picker v-model="formData.budget_date" clearable type="date" value-format="YYYY-MM-DD "
                                placeholder="选择预算日期">
                            </el-date-picker>

                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="预算清单">
                            <uploadAnnex :formData="formData" value='budget_list'></uploadAnnex>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-dialog v-model="showDialog1" title="选择合同" width="70%">
                    <salescontractDialog @customEvent="customEvent1"></salescontractDialog>
                </el-dialog>

                <el-dialog v-model="showDialog2" title="选择项目" width="70%">
                    <projectDialog @customEvent="customEvent2"></projectDialog>
                </el-dialog>
                <personnelselector ref="personnel" @confirm="submituser" type="1"></personnelselector>
            </el-form>
        </popup>

    </div>
</template>

<script lang="ts" setup name="projectEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import salescontractDialog from '@/components/salescontract/index.vue'
import projectDialog from '@/components/project/index.vue'
import { apiProjectbudgetAdd, apiProjectbudgetEdit, apiProjectbudgetDetail } from '@/api/project_total_budget'
import { getAllProjectTypes } from '@/api/projecttype'
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import type { PropType } from 'vue'
const protype = reactive([])
const list1 = reactive([])
const list2 = reactive([])
const project_amount = ref(0)

const tableData = reactive([{
    name: "材料/设备成本(元)",
    text: '用于控制材料成本',
    rate: "",
    value: 'cl_cost',
},
{
    name: "分包成本(元)",
    text: '用于控制分包成本',
    rate: "",
    value: 'fb_cost',

},
{
    name: "人工成本(元)",
    text: '用于控制工时成本及项目人力成本',
    rate: "",
    value: 'rg_cost',

},
{
    name: "费用成本(元)",
    text: '用于控制费用报销及差旅报销',
    rate: "",
    value: 'fy_cost',

},
{
    name: "机械 & 工具成本(元)",
    text: '用于控制机械及设备成本',
    rate: "",
    value: 'jj_cost',

},

])
const contract_name = ref('')
const project_name = ref('')
const project_code = ref('')
const contract_no = ref('')
const custom_name = ref('')
const manage_name = ref('')
const personnel = ref<any>()


defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<Popup>>()
const mode = ref('add')

const showDialog1 = ref(false)
const showDialog2 = ref(false)

const customEvent1 = (e: any) => {
    formData.contract_id = e.id;
    contract_name.value = e.contract_name;
    contract_no.value = e.contract_code
    showDialog1.value = false;
};

const customEvent2 = (e: any) => {
    formData.project_id = e.id;
    project_name.value = e.name;
    project_code.value = e.project_code;
    custom_name.value = e.custom_name;
    showDialog2.value = false;
};

//打开弹窗

const userclick = () => {
    personnel.value.open()

}
//确认
const submituser = (e: any) => {
    formData.project_manager = e.id;
    manage_name.value = e.name;
}

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

// 表单数据
const formData = reactive({
    id: '',
    org_id: "",
    dept_id: "",
    project_id: "",
    contract_amount: 0,
    contract_id: '',
    cl_cost: 0,
    fb_cost: 0,
    rg_cost: 0,
    fy_cost: 0,
    jj_cost: 0,
    remark: "",
    budget_list: [],
    budget_date: "",
    project_manager: "",
    approve_detail: {}
})


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

})

//获取所有组织
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 setFormData = async (data: Record<any, any>) => {
    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

    if (data && data.contract_name) {
        contract_name.value = data.contract_name;

    }
    getlist1(formData.org_id)
    calColumnRate()
}

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


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()

    const data = { ...formData }
    mode.value == 'edit'
        ? await apiProjectbudgetEdit(data)
        : await apiProjectbudgetAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

    getAllProjectTypes().then((res) => {
        protype.splice(0, protype.length, ...res);
    })
    getlist()

}

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



//获取项目总利润
const totalAmout = computed(() => {
    return Number(formData.contract_amount) - (Number(formData.cl_cost) + Number(formData.fb_cost) + Number(formData.rg_cost) + Number(formData.fy_cost) + Number(formData.jj_cost) || 0)

})


// 计算每行的成本占比
const calColumnRate = (index) => {
    tableData.forEach((item, index) => {
        item.rate = Number(formData[item.value] / (Number(formData.contract_amount) - totalAmout.value)).toFixed(2) || "0.00%"
    });

}
// 计算项目利润率
const project_rate = computed(() => {
    let num = ((totalAmout.value / Number(formData.contract_amount)).toFixed(2)) * 100 + "%"
    return num
})

// 表尾合计
const getSummaries = (param: SummaryMethodProps) => {
    const { columns, data } = param
    const sums: string[] = []
    columns.map((column, index) => {

        if (column.label == '序号') {
            sums[index] = '项目利润:'
            return
        }
        if (column.label == '分项') {
            sums[index] = totalAmout.value || 0
            sums[index].toFixed(2)
            return
        }
        if (column.label == '预算成本') {
            sums[index] = "项目利润率:"
            return
        }
        if (column.label == '成本占比') {
            sums[index] = project_rate.value || "0.00%"
            return
        }
    })

    return sums
}



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