<template>
    <!-- 新增和修改人员信息 -->
    <NavBarModal :navBarTitle="navBarTitle" />
    <view
        class="add-person-container"
        :style="{
            paddingBottom: nextBtnHeight + 'px',
            paddingTop: safeAreaInsets?.top + paddingTop + 'px',
        }"
    >
        <!-- 步骤条 -->
        <view>
            <up-steps :current="currentStep">
                <up-steps-item
                    :key="item.title"
                    :title="item.title"
                    :error="item.isError"
                    v-for="item in stepList"
                />
            </up-steps>
        </view>

        <view class="person-info-container">
            <PersonIdCardForm
                ref="personIdCardFormRef"
                :idCardInfo="idCardInfo"
                :formType="formType"
                v-if="currentStep === 0"
            />
            <KeyInfoForm
                :keyInfo="keyInfo"
                :formType="formType"
                v-if="currentStep === 1"
                ref="personKeyInfoFormRef"
            />
            <ContractForm
                v-if="currentStep === 2"
                ref="personContractFormRef"
                :contractInfo="contractInfo"
                :contractImageList="contractImageList"
                :isEditContractStatus="isEditContractStatus"
            />
            <WageCardForm
                :formType="formType"
                ref="personWageCardFormRef"
                :wageCardInfo="wageCardInfo"
                :wageCardImageList="wageCardImageList"
                v-if="currentStep === 3"
            />
        </view>

        <view class="next-btn" ref="nextBtnRef">
            <up-button
                color="#0ab99c"
                text="上一步"
                @tap="onHandlePrev"
                v-if="currentStep > 0"
                style="margin-right: 10px"
            />
            <up-button
                type="primary"
                @tap="onHandleNext"
                :text="currentStep === 3 ? '提交' : '下一步'"
            />
        </view>

        <up-loading-icon
            :vertical="true"
            duration="2000"
            color="#3c9cff"
            :show="showLoading"
            textColor="#3c9cff"
            text="数据正在提交，请稍后..."
            style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%)"
        />
    </view>
</template>

<script setup name="addAndEditPerson">
import { useCommonStore } from '@/stores'
import { pathToBase64 } from 'image-tools'
import { onLoad } from '@dcloudio/uni-app'
import { ref, onMounted, nextTick } from 'vue'
import {
    getPersonInfoByIdAPI,
    updatePersonLightStatusApi,
    addPersonEntryApi,
    editPersonEntryApi,
} from '@/services/person-entry'

import PersonIdCardForm from '@/components/PersonIdCardForm/index.vue'
import KeyInfoForm from '@/components/KeyInfoForm/index.vue'
import ContractForm from '@/components/ContractForm/index.vue'
import WageCardForm from '@/components/WageCardForm/index.vue'
import NavBarModal from '@/components/NavBarModal/index.vue'
const { safeAreaInsets } = uni.getSystemInfoSync()
const commonStore = useCommonStore()
const navBarTitle = ref('新增人员信息')
const currentStep = ref(0) // 当前步骤
const nextBtnRef = ref(null) // 下一步按钮ref
const nextBtnHeight = ref(0) // 下一步按钮高度
const paddingTop = ref(54) // 顶部padding
const personIdCardFormRef = ref(null) // 身份证信息表单ref
const personKeyInfoFormRef = ref(null) // 关键信息表单ref
const personContractFormRef = ref(null) // 合同见证表单ref
const personWageCardFormRef = ref(null) // 工资卡见证表单ref
const editUploadFileList = ref([]) // 编辑时已上传文件列表
const formType = ref(1) // 表单类型
const personId = ref('') // 人员id
const einStatus = ref('') // 人员状态
const showLoading = ref(false) // 是否显示加载中

const props = defineProps({
    type: {
        type: [Number, String],
        default: 1,
    },
    id: {
        type: [Number, String],
        default: '',
    },
})

// 步骤条
const stepList = ref([
    {
        title: '身份证信息',
        isError: false,
    },
    {
        title: '关键信息',
        isError: false,
    },
    {
        title: '合同见证',
        isError: false,
    },
    {
        title: '工资卡见证',
        isError: false,
    },
])

const idCardInfo = ref({}) // 身份证信息
const keyInfo = ref({}) // 关键信息
const contractInfo = ref({}) // 合同信息
const contractImageList = ref([
    {
        type: 1,
        fileList: [],
        name: 'contract',
        title: '人员手持合同照',
    },
    // {
    //     type: 2,
    //     fileList: [],
    //     name: 'contract',
    //     title: '工作内容页',
    // },
    // {
    //     type: 3,
    //     fileList: [],
    //     name: 'contract',
    //     title: '薪酬约定页',
    // },
    // {
    //     type: 4,
    //     fileList: [],
    //     name: 'contract',
    //     title: '本人签名页',
    // },
    // {
    //     type: 5,
    //     fileList: [],
    //     name: 'contract',
    //     title: '其他照片',
    // },

    // {
    //     type: 6,
    //     fileList: [],
    //     name: 'contract',
    //     title: '附件',
    // },
]) // 合同图片
const contractStatus = ref('') // 合同状态
const isEditContractStatus = ref(false) // 编辑时是否有合同信息
const isEditWageCardStatus = ref(false) // 编辑时是否有工资卡信息
const wageCardInfo = ref({}) // 工资卡信息
const wageCardImageList = ref([
    {
        type: 1,
        fileList: [],
        name: 'wageCard',
        title: '手持银行卡、承诺书',
    },
    // {
    //     type: 2,
    //     fileList: [],
    //     name: 'wageCard',
    //     title: '银行卡照片',
    // },
    // {
    //     type: 3,
    //     fileList: [],
    //     name: 'wageCard',
    //     title: '个人工资卡承诺书',
    // },
    // {
    //     type: 4,
    //     fileList: [],
    //     name: 'wageCard',
    //     title: '其它照片',
    // },
]) // 工资卡图片
const wageCardStatus = ref('') // 工资卡状态

const imgToBase64Fun = async (path) => {
    return new Promise((resolve, reject) => {
        pathToBase64(path)
            .then((base64) => {
                resolve(base64)
            })
            .catch((error) => {
                console.error(error)
                reject(error)
            })
    })
}

// 下一步
const onHandleNext = async () => {
    try {
        if (currentStep.value === 0) {
            const res = await personIdCardFormRef.value.validateIdCardForm()
            if (res.isValid) {
                stepList.value[currentStep.value].isError = false
                currentStep.value++
                idCardInfo.value = res?.data
                nextTick(() => {
                    personKeyInfoFormRef.value.updateKeyInfoInfo()
                })
            }
        }

        if (currentStep.value === 1) {
            const res = await personKeyInfoFormRef.value.validateKeyInfoForm()
            if (res.isValid) {
                stepList.value[currentStep.value].isError = false
                currentStep.value++
                keyInfo.value = res?.data

                if (isEditContractStatus.value) {
                    nextTick(() => {
                        personContractFormRef.value.updateContractInfo()
                    })
                }
            }
        }
        if (currentStep.value === 2) {
            const res = await personContractFormRef.value.validateContractForm()
            if (res.isValid) {
                stepList.value[currentStep.value].isError = false
                currentStep.value++

                const { data, imgList, status } = res
                contractInfo.value = data
                contractImageList.value = imgList
                contractStatus.value = status

                if (isEditWageCardStatus.value) {
                    nextTick(() => {
                        personWageCardFormRef.value.updateWageCardInfo()
                    })
                }
            }
        }
        if (currentStep.value === 3) {
            const res = await personWageCardFormRef.value.validateWageCardForm()

            if (res.isValid) {
                stepList.value[currentStep.value].isError = false

                const { data, imgList, status } = res //工资卡信息
                wageCardInfo.value = data
                wageCardImageList.value = imgList
                wageCardStatus.value = status

                const params = {
                    ...idCardInfo.value,
                    ...keyInfo.value,
                }

                if (formType.value == 2) {
                    params.id = personId.value
                    params.einStatus = einStatus.value
                }

                // 处理合同
                if (contractStatus.value === 'all_filled' && !isEditContractStatus.value) {
                    params.bmWorkerContract = contractInfo.value
                }

                // 处理工资卡
                if (wageCardStatus.value === 'all_filled') {
                    params.bmWorkerWageCard = wageCardInfo.value
                }

                delete params.faceImg // 删除无关数据

                showLoading.value = true
                const API = formType.value == 2 ? editPersonEntryApi : addPersonEntryApi
                showLoading.value = false

                console.log('params--**----请求参数', params, '请求接口', API)
                const result = await API(params)
                console.log('res--**----新增或修改的结果', result)

                if (result.code === 200) {
                    //  更新红绿灯状态
                    const workerId = formType.value == 2 ? params.id : result.data
                    const res = await updatePersonLightStatusApi({
                        workerId,
                        proId: keyInfo.value.proId,
                    })

                    console.log(res, '更新红绿灯状态的结果')
                }

                if (result.code === 200) {
                    uni.$u.toast(result.msg)
                    setTimeout(() => {
                        uni.navigateBack()
                    }, 500)
                }
            }
        }
    } catch (error) {
        stepList.value[currentStep.value].isError = true
    }
}

// 上一步
const onHandlePrev = () => {
    currentStep.value--
}

// 获取按钮高度
const getButtonHeight = () => {
    // 使用uni.createSelectorQuery()获取节点信息
    const query = uni.createSelectorQuery().in(this)
    query
        .select('.next-btn')
        .boundingClientRect((data) => {
            if (data) {
                nextBtnHeight.value = data.height
            }
        })
        .exec()
}

// 获取人员信息
const getPersonInfoByIdFun = async (id) => {
    console.log(commonStore?.activeProjectId, 'commonStore?.activeProjectId', '----', id)
    const res = await getPersonInfoByIdAPI({ id, proId: commonStore?.activeProjectId })

    if (res.code === 200) {
        const {
            age,
            sex,
            name,
            nation,
            endTime,
            address,
            idNumber,
            birthday,
            startTime,
            issuingAuthority,

            proId, // 入场工程
            postId, // 工种
            subId, // 入场分包
            phone, // 手机号码
            teamId, // 入场班组
            proName, // 入场工程名称
            subName, // 入场分包名称
            teamName, // 入场班组名称
            postName, // 工种名称

            files, // 人脸图片
            bmWorkerContract, // 合同状态
            bmWorkerWageCard, // 工资卡状态
        } = res.data
        idCardInfo.value = {
            age,
            sex,
            name,
            nation,
            startTime,
            endTime,
            address,
            idNumber,
            birthday,
            issuingAuthority,
        }

        keyInfo.value = {
            proId, // 入场工程
            postId, // 工种
            subId, // 入场分包
            phone, // 手机号码
            teamId, // 入场班组
            proName, // 入场工程名称
            subName, // 入场分包名称
            teamName, // 入场班组名称
            postName, // 工种名称
            faceImg: [],
        }

        if (bmWorkerContract && Object.keys(bmWorkerContract).length > 0) {
            // 如果修改时 并且合同信息不为空 则合同信息不允许修改
            isEditContractStatus.value = true
            const {
                contractCode,
                wageCriterion,
                wageApprovedWay,
                contractStopDate,
                contractTermType,
                contractStartDate,
                files,
            } = bmWorkerContract

            contractInfo.value = {
                contractCode,
                wageCriterion,
                wageApprovedWay,
                contractStopDate,
                contractTermType,
                contractStartDate,
            }

            if (files && files.length > 0) {
                files.forEach((i) => {
                    contractImageList.value.forEach((j) => {
                        if (i.sourceType == j.type) {
                            j.fileList.push({
                                id: i.id,
                                url: i.lsUrl,
                                name: i.originFileName,
                            })
                        }
                    })
                })
            }
        }

        if (bmWorkerWageCard && Object.keys(bmWorkerWageCard).length > 0) {
            isEditWageCardStatus.value = true
            const { bankCardCode, bankName, bankBranchName, id, files, bankIdentifierCode } =
                bmWorkerWageCard

            wageCardInfo.value = {
                bankCardCode,
                bankName,
                bankBranchName,
                bankIdentifierCode,
                id,
            }

            files.forEach((i) => {
                editUploadFileList.value.push(i)
                wageCardImageList.value.forEach((j) => {
                    if (i.sourceType == j.type) {
                        j.fileList.push({
                            id: i.id,
                            url: i.lsUrl,
                            name: i.originFileName,
                        })
                    }
                })
            })
        }

        if (files && files.length > 0) {
            files.forEach((i) => {
                keyInfo.value.faceImg.push({
                    id: i.id,
                    url: i.lsUrl,
                    name: i.originFileName,
                })
            })
        }

        await nextTick(() => {
            personIdCardFormRef.value.updateIdCardInfo()
        })
    }
}

onMounted(() => {
    nextTick(() => {
        getButtonHeight()
    })
})

onLoad((options) => {
    options?.type == 1 ? (navBarTitle.value = '新增人员信息') : (navBarTitle.value = '人员信息修改')
    einStatus.value = options?.einStatus
    formType.value = options?.type
    personId.value = options?.id

    if (options?.id) {
        getPersonInfoByIdFun(options?.id)
    }
})
</script>

<style scoped lang="scss">
.add-person-container {
    height: 100%;
    display: flex;
    padding-top: 20rpx;
    box-sizing: border-box;
    flex-direction: column;
    background-color: #fff;

    .person-info-container {
        flex: 1;
        margin-top: 20rpx;
        overflow-y: auto;
    }
}

.next-btn {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
</style>
