<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="90%" @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-card class="mb-2">
                    <!-- <div class="tit">客户基本资料</div> -->
                    <div class="tit">
                        <el-steps :active="active" finish-status="success">
                            <el-step title="会计" />
                            <el-step title="财务负责人" />
                            <el-step title="总经理" />
                        </el-steps>
                    </div>
                    <el-row>
                        <el-col :span="8">

                            <el-form-item label="年份" prop="years">
                                <el-date-picker class="flex-1 !flex" v-model="formData.years" clearable type="year"
                                    value-format="YYYY" placeholder="选择年份">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="制单时间" prop="document_preparation_time">
                                <el-date-picker class="flex-1 !flex" v-model="formData.document_preparation_time" clearable
                                    type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="选择制单时间">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="总合计" prop="date">
                                <el-input v-model="totalmoeny" readonly placeholder="请输入总合计"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="备注" prop="remark">
                                <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注"
                                    :autosize="{ minRows: 4, maxRows: 4 }" :style="{ width: '100%' }"></el-input>
                            </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" :key="index"
                                        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-card>



                <el-card class="mb-2">
                    <div class="tit">预算明细</div>
                    <el-table :data="tableData" :summary-method="getSummaries" show-summary>
                        <el-table-column label="序号" width="105px">
                            <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="一级科目" prop="name1">
                            <template #default="{ row, column, $index }">
                                <el-input v-model="row.name1" @click="subjectmu(row, column, $index)" />
                            </template>
                        </el-table-column>
                        <el-table-column label="二级科目" prop="name2">
                            <template #default="{ row }"> <el-input v-model="row.name2" /> </template></el-table-column>
                        <el-table-column label="1月" prop="month1">
                            <template #default="{ row }"> <el-input v-model="row.month1" type="number" />
                            </template></el-table-column>

                        <el-table-column label="2月" prop="month2">
                            <template #default="{ row }">
                                <el-input v-model="row.month2" type="number" />
                            </template>
                        </el-table-column>

                        <el-table-column label="3月" prop="month3">
                            <template #default="{ row }"> <el-input v-model="row.month3" type="number" />
                            </template></el-table-column>

                        <el-table-column label="4月" prop="month4">
                            <template #default="{ row }">
                                <el-input v-model="row.month4" type="number" />
                            </template>
                        </el-table-column>
                        <el-table-column label="5月" prop="month5">
                            <template #default="{ row }">
                                <el-input v-model="row.month5" type="number" />
                            </template>
                        </el-table-column>
                        <el-table-column label="6月" prop="month6">
                            <template #default="{ row }">
                                <el-input v-model="row.month6" type="number" />
                            </template>
                        </el-table-column>
                        <el-table-column label="7月" prop="month7">
                            <template #default="{ row }">
                                <el-input v-model="row.month7" type="number" />
                            </template>
                        </el-table-column>
                        <el-table-column label="8月" prop="month8">
                            <template #default="{ row }">
                                <el-input v-model="row.month8" type="number" />
                            </template>
                        </el-table-column>
                        <el-table-column label="9月" prop="month9">
                            <template #default="{ row }">
                                <el-input v-model="row.month9" type="number" />
                            </template>
                        </el-table-column>
                        <el-table-column label="10月" prop="month10">
                            <template #default="{ row }">
                                <el-input v-model="row.month10" type="number" />
                            </template>
                        </el-table-column>
                        <el-table-column label="11月" prop="month11">
                            <template #default="{ row }">
                                <el-input v-model="row.month11" type="number" />
                            </template>
                        </el-table-column>
                        <el-table-column label="12月" prop="month12">
                            <template #default="{ row }">
                                <el-input v-model="row.month12" type="number" />
                            </template>
                        </el-table-column>

                        <!-- 其他列 -->
                    </el-table>
                </el-card>

            </el-form>
            <reviewprocess :list="list" />
        </popup>
        <el-dialog v-model="showDialog" title="选择科目" width="70%">
            <costDialog @customEvent="customEvent"></costDialog>

        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="customEdit">

import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiadjustAdd, apiadjustEdit, apiadjustDetail } from '@/api/cost_budget_adjust'
import { timeFormat } from '@/utils/util'
import reviewprocess from '@/components/reviewprocess/index.vue'
import costDialog from '@/components/cost_subject/index.vue'
import type { PropType } from 'vue'
import type { TableColumnCtx } from 'element-plus'
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import configs from "@/config"
const base_url = configs.baseUrl + configs.urlPrefix
import useUserStore from "@/stores/modules/user";
const userStore = useUserStore();
const formDataannex = reactive([])
const totalmoeny = ref('')
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
// 上传文件
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 list1 = reactive([])
const list2 = reactive([])
const num = ref(0)
interface Product {
    id: string
    name1: string
    name2: string
    month1: number
    month2: number
    month3: number
    month4: number
    month5: number
    month6: number
    month7: number
    month8: number
    month9: number
    month10: number
    month11: number
    month12: number
}

interface SummaryMethodProps<T = Product> {
    columns: TableColumnCtx<T>[]
    data: T[]
}
// 表单数据
const formData = reactive({
    id: '',
    dept_id: '',
    org_id: '',
    approve_id: 0,
    years: "",
    document_preparation_time: "",
    remark: "",
    annex: [],
    detail: [

    ]
})

//科目
const subjectmu = (row, i, a) => {
    // console.log(row, i, a)
    num.value = a
    showDialog.value = true
}

const tableData = ref([
    // 表格数据
    { name1: "", name2: "", month1: ' ', month2: ' ', month3: ' ', month4: ' ', month5: ' ', month6: ' ', month7: ' ', month8: ' ', month9: ' ', month10: ' ', month11: ' ', month12: ' ', },
]);
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
        }
        // console.log(columns)
        const values = data.map((item: any) => Number(item[column.property]))
        console.log(values)
        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'
        }
    })
    if (sums.length > 0) {
        const kkarr1 = sums.slice(3, sums.length)
        const kkarr2 = kkarr1.map((item: any) => Number(item))
        totalmoeny.value = kkarr2.reduce((prev, curr) => {
            const value = Number(curr)
            if (!Number.isNaN(value)) {
                return prev + curr
            } else {
                return prev
            }
        }, 0)

    }
    return sums
}


const handleAdd = (row) => {
    // 在 row 后面插入一行数据
    const index = tableData.value.indexOf(row);
    tableData.value.splice(index + 1, 0, { name1: "", name2: "", month1: ' ', month2: ' ', month3: ' ', month4: ' ', month5: ' ', month6: ' ', month7: ' ', month8: ' ', month9: ' ', month10: ' ', month11: ' ', month12: ' ', });
};

const handleDelete = (row) => {
    // 删除 row
    const index = tableData.value.indexOf(row);
    tableData.value.splice(index, 1);
};
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const active = ref(0)
const showDialog = ref(false)

const next = () => {
    if (active.value++ > 2) active.value = 0
}
const list = reactive([])
const datas = reactive({
    provinceOptions: [],
    cityOptions: [],
    areaOptions: [],
});

const customEvent = (e: any) => {
    tableData.value[num.value].name1 = e.subject1;
    tableData.value[num.value].name2 = e.subject2;
    tableData.value[num.value].cost_subject_id = e.id;


    showDialog.value = false;
};

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑公司年度管理费用预算调整' : '新增公司年度管理费用预算调整'
})



// 表单验证
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)

    }


    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }

    }
    if (data.detail && data.detail.length > 0) {
        tableData.value = data.detail.map((item, i) => {
            if (item.subject && item.subject.subject1) {
                item.name1 = item.subject.subject1
            }
            if (item.subject && item.subject.subject2) {
                item.name2 = item.subject.subject2
            }

            return item
        })
        // console.log(arry2, '22222222')
    }
    // console.log(formData, '2222222222')


}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiadjustDetail({
        id: row.id
    })
    setFormData(data)
}
//获取所有组织
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 handleSubmit = async () => {
    // console.log(tableData.value)
    // formData.detail=
    if (tableData.value.length > 0) {
        const arr1 = tableData.value.map(({ name1, name2, ...rest }) => rest)
        Object.assign(formData.detail, arr1)
    }
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item: any) => item.uri)
    }

    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiadjustEdit(data)
        : await apiadjustAdd(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>
<style lang="scss" scoped>
.tit {
    font-size: 1.2em;
    margin-bottom: 10px;
}

:deep(.my-label) {
    width: 150px;
}</style>


