<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="85vw" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="auto" :rules="formRules">
                <el-row>

                    <el-col :span="24">
                        <el-form-item label="项目名称" prop="project_id" @click="showDialog = true">
                            <el-input v-model="project_name" clearable placeholder="请输入项目名称" :disabled="project" />
                        </el-form-item> </el-col>
                    <el-col :span="24">
                        <el-form-item label="项目编码" prop="project_id">
                            <el-input v-model="project_code" clearable disabled placeholder="系统自动填写"
                                :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="考勤日期" prop="attendance_date">
                            <el-date-picker class="flex-1 !flex" clearable v-model="formData.attendance_date" 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="type">
                            <el-input v-model="renshu" clearable disabled placeholder="系统自动填写"
                                :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" 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-row>
                <div class="tit" style="font-size: 16px;font-weight: bold;margin-bottom: 10px;">考勤记录清单</div>
                <div style="margin-bottom: 30px;">
                    <el-table :data="formData.attendance_detail" width="100%">
                        <el-table-column label="序号">
                            <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="name">
                            <template #default="{ row }">
                                <el-input v-model="row.name" readonly placeholder="点击选择" @click="chosePersnol(row)" />
                            </template>
                        </el-table-column>
                        <el-table-column label="身份证号" prop="code">
                            <template #default="{ row }"> <el-input v-model="row.idcard" disabled placeholder="自动填写" />
                            </template></el-table-column>
                        <el-table-column label="工种" prop="specs">
                            <template #default="{ row }"> <el-input v-model="row.work_type_text" disabled
                                    placeholder="自动填写" />
                            </template></el-table-column>

                        <el-table-column label="上班时间" prop="brand">
                            <template #default="{ row }">
                                <!-- <el-date-picker clearable v-model="row.work_start_time" type="date"
                                    value-format="YYYY-MM-DD" placeholder="请选择" style="width: 100px;">
                                </el-date-picker> -->
                                <el-time-select v-model="row.work_start_time" start="06:30" step="00:15" end="23:30"
                                    placeholder="请选择" />
                            </template>
                        </el-table-column>

                        <el-table-column label="下班时间" prop="parameter_description">
                            <template #default="{ row }">
                                <!-- <el-date-picker clearable v-model="row.work_end_time" type="date" value-format="YYYY-MM-DD"
                                    placeholder="请选择" style="width: 100px;">
                                </el-date-picker> -->
                                <el-time-select v-model="row.work_end_time" start="06:30" step="00:15" end="23:30"
                                    placeholder="请选择" />
                            </template></el-table-column>
                        <el-table-column label="记工数量">
                            <template #default="{ row }">
                                <el-input v-model="row.work_record_num" type="number" />
                            </template></el-table-column>
                        <el-table-column label="日工资">
                            <template #default="{ row }">
                                <el-input v-model="row.daily_salary" type="number" />
                            </template>
                        </el-table-column>

                        <el-table-column label="日生活费" prop="price">
                            <template #default="{ row }">
                                <el-input v-model="row.daily_living" type="number" />
                            </template>
                        </el-table-column>
                        <el-table-column label="日补贴" prop="amount">
                            <template #default="{ row }">
                                <el-input v-model="row.daily_subsidy" />
                            </template>
                        </el-table-column>
                        <el-table-column label="日其他" prop="amount_including">
                            <template #default="{ row }">
                                <el-input v-model="row.daily_other" />
                            </template>
                        </el-table-column>
                        <el-table-column label="日收入" prop="remark">
                            <template #default="{ row }">
                                <el-input v-model="row.daily_income" />
                            </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-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%">
                        <projectPersonnel @customEvent="customEvent1" :project_id="formData.project_id"></projectPersonnel>
                    </el-dialog>
                </div>
            </el-form>
        </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 { attendanceRecordAdd, attendanceRecordEdit, attendanceRecordDetail } from '@/api/project_attendance_record'
import projectPersonnel from '@/components/project_personnel/index.vue'
import type { PropType } from 'vue'
import configs from "@/config"
import useUserStore from "@/stores/modules/user";
import { watch } from "vue"
import { useDictData } from '@/hooks/useDictOptions'
const { dictData } = useDictData('labor_contract_status,labor_contract_type,labor_contract_name')

let props = defineProps({
    project: Object
})
// 表单数据
const formData = reactive({
    id: '',
    project_id: '',
    attendance_date: '',
    remark: '',
    file: '',
    attendance_detail: [{}],

})

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 renshu = ref('')
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const formDataannex = reactive([])
const userInfo = userStore.userInfo

const handleAdd = (row: any) => {
    const index = formData.attendance_detail.indexOf(row);
    formData.attendance_detail.splice(index + 1, 0, {});
};
const handleDelete = (row: any) => {
    const index = formData.attendance_detail.indexOf(row);
    formData.attendance_detail.splice(index, 1);
};

//获取值
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);


let rowIndex = 0
const chosePersnol = (row) => {
    showDialog1.value = true
    rowIndex = formData.attendance_detail.indexOf(row);
}

//获取值
const customEvent1 = (e) => {
    formData.attendance_detail[rowIndex].name = e.name
    formData.attendance_detail[rowIndex].idcard = e.idcard
    formData.attendance_detail[rowIndex].work_type_text = e.work_type_text
    formData.attendance_detail[rowIndex].person_id = e.id
    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 formRules = reactive<any>({

})
let renshu = computed(() => {
    return formData.attendance_detail.length
})



// // formData.attendance_date
// watch(formData.attendance_detail, () => {
//     formData
//     console.log(556)
// })


// 获取详情
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]
        }
    }
    project_name.value = data.project_name
    project_code.value = data.project_code
    idcard.value = data.person_idcard
    person_name.value = data.person_name

}

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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item: any) => item.uri)
    }
    await formRef.value?.validate()
    formData.attendance_detail.forEach(item => {
        item.work_start_time = item.work_start_time ? formData.attendance_date + ` ${item.work_start_time}` : ""
        item.work_end_time = item.work_end_time ? formData.attendance_date + ` ${item.work_end_time}` : ""
    })
    const data = { ...formData, }
    mode.value == 'edit'
        ? await attendanceRecordEdit(data)
        : await attendanceRecordAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

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


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