<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" @change="getSummaries" 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_amount" clearable disabled 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_rate" clearable disabled 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="56">

                        </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="row.cost" @input="costinput(row, $index)" /> </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="预算清单" 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-row>
                <!-- <el-dialog v-model="showDialog" title="选择客户" width="70%">
                    <customDialog @customEvent="customEvent"></customDialog>
                </el-dialog> -->
                <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 customDialog from '@/components/custom-dialog/index.vue'
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 type { TableColumnCtx } from 'element-plus'
import { apiProjectbudgetAdd, apiProjectbudgetEdit, apiProjectbudgetDetail } from '@/api/project_total_budget'
import { toChinesNum } from "@/utils/util";
import { getAllProjectTypes } from '@/api/projecttype'
import { timeFormat } from '@/utils/util'
import { isEmail, isIdCard, isPhone } from '@/utils/validate'
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import type { PropType } from 'vue'
import configs from "@/config"
import useUserStore from "@/stores/modules/user";
import { number } from 'echarts/core'
const protype = reactive([])
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const active = ref(0)
const formDataannex = reactive([])
const list1 = reactive([])
const list2 = reactive([])


const project_amount = ref(0)
const project_rate = ref(0)

const tableData = reactive([{
    name: "材料/设备成本(元)",
    text: '用于控制材料成本',
    cost: "", rate: "",
    cl_cost: ''
},
{
    name: "分包成本(元)",
    text: '用于控制分包成本', cost: "", rate: "",
    fb_cost: '',
},
{
    name: "人工成本(元)",
    text: '用于控制工时成本及项目人力成本', cost: "", rate: "",
    rg_cost: ''
},
{
    name: "费用成本(元)",
    text: '用于控制费用报销及差旅报销', cost: "", rate: "",
    fy_cost: ''
},
{
    name: "机械 & 工具成本(元)",
    text: '用于控制机械及设备成本', cost: "", rate: "",
    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 userInfo = userStore.userInfo
const personnel = ref<any>()
// console.log(userInfo, '222222')
// 上传文件
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 checkPhone = (rule: any, value: any, callback: (arg0: Error) => any) => {

    if (value && !/^1\d{10}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
    } else {
        callback()
    }

}
const userEmail = (rule: any, value: string, callback: (arg0: Error | undefined) => void) => {

    // const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
    // // if (!value) {
    // //     return callback(new Error('邮箱不能为空'))
    // // }


    if (value && !mailReg.test(value)) {
        callback(new Error('请输入正确的邮箱格式'))
    } else {
        callback()
    }

};
// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}
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 totalenum = ref('')
const showDialog = ref(false)
const showDialog1 = ref(false)
const showDialog2 = ref(false)
const customEvent = (e: any) => {
    formData.customer_id = e.id;
    custom_name.value = e.name;
    showDialog.value = 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 updateCost = () => {

    for (let i = 0; i < tableData.length; i++) {
        const row = tableData[i];

        if (row.cost && row.cost > 0) {
            row.rate = (row.cost / Number(totalenum.value)).toFixed(2) + '%';
        } else {
            row.rate = ''
        }

    }
};


//监听合同金额
// const contractamount = (e) => {
//     console.log(e)
//     if (project_amount.value != 0) {
//         project_amount.value = e - Number(project_amount.value)
//         project_rate.value = (Number(project_amount.value) / Number(e)).toFixed(2) + '%'
//     }
//     console.log(project_rate.value, project_amount.value)
// }

//监听获取成本%
const costinput = (row, index) => {

    row.rate = (row.cost / Number(totalenum.value)).toFixed(2) + '%'

    if (index == 0) {
        formData.cl_cost = row.cost
    } else if (index == 2) {
        formData.fb_cost = row.cost
    } else if (index == 3) {
        formData.rg_cost = row.cost
    } else if (index == 4) {
        formData.fy_cost = row.cost
    } else if (index == 5) {
        formData.jj_cost = row.cost
    }




}


//打开弹窗

const userclick = () => {
    // console.log(personnel.value, '1111111')
    personnel.value.open()

}
//确认
const submituser = (e: any) => {
    formData.project_manager = e.id;
    manage_name.value = e.name;
}
interface Product {
    id: string
    name: string
    text: string
    cost: number
    rate: string
    cl_cost: number

}
interface SummaryMethodProps<T = Product> {
    columns: TableColumnCtx<T>[]
    data: T[]
}
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] = ''
            return
        }
        if (column.label === '成本占比') {
            sums[index] = ''
            return
        }

        const values = data.map((item: any) => Number(item[column.property]))

        if (!values.every((value) => Number.isNaN(value))) {

            sums[index] = `${values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!Number.isNaN(value)) {
                    return prev + curr
                } else {
                    return prev
                }
            }, 0)}`
        } else {
            sums[index] = 'N/A'
        }

    })
    // console.log(sums)
    totalenum.value = sums[2]
    project_amount.value = sums[2]
    return sums
}


//监听输入
const amountinput = (e) => {
    // console.log(e)
    if (e && e > 0) {
        formData.amount_daxie = toChinesNum(e)
    }
}
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑总预算表' : '新增总预算表'
})

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


// 表单验证
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>) => {
    if (data.budget_list && data.budget_list.length > 0) {

        const arry1 = data.budget_list.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex, arry1)

    }


    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

    tableData[0].cost = data.cl_cost

    tableData[1].cost = data.fb_cost

    tableData[2].cost = data.rg_cost

    tableData[3].cost = data.fy_cost

    tableData[4].cost = data.jj_cost


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

    }
    getlist1(formData.org_id)
}

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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.budget_list = formDataannex.map((item: any) => item.uri)
    }

    console.log(formRef.value?.validate(), '22222222')
    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')
}

watch(
    [totalenum, project_amount, project_rate,], (newValue, oldValue) => {
        updateCost();
        if (formData && formData.contract_amount && project_amount.value) {
            project_amount.value = Number(formData.contract_amount) - Number(project_amount.value);
            project_rate.value = (Number(project_amount.value) / Number(formData.contract_amount)).toFixed(2) + '%';
        }
        // console.log(formData.contract_amount, project_amount.value)
    },

)

watch(
    () => formData.contract_amount,
    (newValue, oldValue) => {

        if (project_amount.value) {
            project_amount.value = Number(formData.contract_amount) - Number(project_amount.value);
            project_rate.value = (Number(project_amount.value) / Number(formData.contract_amount)).toFixed(2) + '%';
        }
    }
)

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