<script setup lang="ts">
    import { reactive, ref, toRefs } from 'vue'
    import { onLoad, onShow } from '@dcloudio/uni-app'
    import { useUserStore } from '@/store/modules/user'
    import { useGlobSetting } from '/@/hooks/setting'
    import * as LinghuoyonggongAPI from '@/api/model/linghuoyonggong'
    import { getCalculateAge } from '@/utils/date'
    import * as UserInfoAPI from '@/api/model/userInfo'
    import { useDictStore } from '@/store/modules/dict'
    import AreaPicker from '@/components/AreaPicker/index.vue'

    const dictStore = useDictStore()
    const userStore = useUserStore()
    const globSetting = useGlobSetting()
    
    onLoad((option) => {
        if (option && option.id) {
            uni.setNavigationBarTitle({ title: '编辑劳动力池' })
            getDetails(option.id)
        } else {
            uni.setNavigationBarTitle({ title: '登记劳动力池' })
            getCurrentAddressInfo()
        }
        getDictVal()
    })

    onShow(() => {
        initDict()
    })

    const skillPopupRef = ref(null)
    const tempWorkersParam = reactive({
        id: null,
        name: '',
        mobile: '',
        gender: 1,
        birthday: '',
        edu: 1,
        eduZh: '',
        attr: '普通工',
        skill: '',
    })

    const DictData = reactive({
        sexArr: [],
        educationArr: [],
        socialattributesArr: [],
        isSkillPopupShow: false,
        skillOptionsVal: [],
    })

    const pageData = reactive({
        loading: false,
        isActive: false,
        isPersonPopupShow: false,
        datePickerShow: false,
        attrPickerShow: false,
        dictValArr: [],
        dictType: '',
        
        laborParam: {
            id: null,
            lon: '',
            lat: '',
            contactName: '',
            contactMobile: '',
            provinceName: '湖南省',
            provinceCode: '43',
            cityName: '',
            cityCode: '',
            districtName: '',
            districtCode: '',
            townName: '',
            townCode: '',
            villageName: '',
            villageCode: '',
            addr: '',
        },
        workersParam: [],
        actionType: 'add',
        editWorkersIndex: 0,
        showArea: false,
    })

    const { laborParam, workersParam } = toRefs(pageData)

    async function initDict() {
        // ...
    }

    function getDictVal() {
        LinghuoyonggongAPI.gitListByCodeDict({ code: 'sex' }).then(res => DictData.sexArr = res)
        LinghuoyonggongAPI.gitListByCodeDict({ code: 'education' }).then(res => DictData.educationArr = res)
        LinghuoyonggongAPI.gitListByCodeDict({ code: 'socialattributes' }).then(res => DictData.socialattributesArr = res)
        queryByCategoryAndCode(0, null)
    }

    function queryByCategoryAndCode(code, e) {
        LinghuoyonggongAPI.queryByCategoryAndCode({ category: 1, code }).then((res) => {
            if (res.length) {
                const dataArr = res.map(i => ({ text: i.name, value: i.code }))
                if (!DictData.skillOptionsVal.length) {
                    DictData.skillOptionsVal = dataArr
                } else {
                    skillPopupRef.value.setRequestData(dataArr, e.layer)
                }
            } else {
                skillPopupRef.value.end()
            }
        })
    }

    function handleAreaConfirm(e) {
        const areaAttr = ['province', 'city', 'district', 'town', 'village']
        const { text, value } = e
        for (let i = 0; i < text.length; i++) {
            pageData.laborParam[`${areaAttr[i]}Name`] = text[i]
            pageData.laborParam[`${areaAttr[i]}Code`] = value[i]
        }
        pageData.laborParam.villageName = text[text.length - 1]
        pageData.laborParam.villageCode = value[value.length - 1]
        pageData.laborParam.addr = e.fullText
        pageData.isActive = true
    }

    function selectCompleteSkill(e) {
        const valText = e.text[e.text.length - 1]
        if (tempWorkersParam.skill.length) {
            const arr = tempWorkersParam.skill.split('、')
            if (arr.length < 3) tempWorkersParam.skill += `、${valText}`
            else uni.showToast({ title: '最多选3项', icon: 'none' })
        } else {
            tempWorkersParam.skill = valText
        }
        DictData.isSkillPopupShow = false
    }

    function changeSkill(e) {
        queryByCategoryAndCode(e.value, e)
    }

    function attrChange(e) {
        if (pageData.dictType == 'education') {
            tempWorkersParam.eduZh = e.value
            const item = DictData.educationArr.find(i => i.itemText == e.value)
            if (item) tempWorkersParam.edu = Number(item.itemValue)
        } else {
            tempWorkersParam.attr = e.value
        }
        pageData.attrPickerShow = false
    }

    function dateBirthChange(e) {
        tempWorkersParam.birthday = e.result
        pageData.datePickerShow = false
    }

    function openAddPersonPopup() {
        Object.assign(tempWorkersParam, {
            id: null, name: '', mobile: '', gender: 1, birthday: '', edu: 1, eduZh: '', attr: '普通工', skill: ''
        })
        pageData.actionType = 'add'
        pageData.isPersonPopupShow = true
    }

    function editPersonPopup(index) {
        const item = pageData.workersParam[index]
        Object.assign(tempWorkersParam, item)
        tempWorkersParam.eduZh = returnDictZhVel('edu', item.edu)
        pageData.actionType = 'edit'
        pageData.editWorkersIndex = index
        pageData.isPersonPopupShow = true
    }

    function addPersonData() {
        if (!tempWorkersParam.name || !tempWorkersParam.mobile || !tempWorkersParam.birthday) {
            uni.showToast({ title: '请完善人员信息', icon: 'none' })
            return
        }
        if (pageData.actionType == 'edit') {
            pageData.workersParam[pageData.editWorkersIndex] = JSON.parse(JSON.stringify(tempWorkersParam))
        } else {
            pageData.workersParam.push(JSON.parse(JSON.stringify(tempWorkersParam)))
        }
        pageData.isPersonPopupShow = false
    }

    function delPersonData() {
        uni.showModal({
            title: '提示',
            content: '确定移除该人员吗？',
            success: (res) => {
                if (res.confirm) {
                    pageData.workersParam.splice(pageData.editWorkersIndex, 1)
                    pageData.isPersonPopupShow = false
                }
            }
        })
    }

    function returnDictZhVel(type, val) {
        const arr = type == 'gender' ? DictData.sexArr : DictData.educationArr
        const item = arr.find(i => Number(i.itemValue) == val)
        return item ? item.itemText : ''
    }

    function onPickerTap(type) {
        pageData.dictType = type
        const arr = type == 'education' ? DictData.educationArr : DictData.socialattributesArr
        pageData.dictValArr = arr.map(i => i.itemText)
        pageData.attrPickerShow = true
    }

    function getCurrentAddressInfo() {
        const loc = uni.getStorageSync('location')
        if (!loc) return
        UserInfoAPI.location({ lon: loc.lon, lat: loc.lat }).then(res => {
            pageData.laborParam.lon = loc.lon
            pageData.laborParam.lat = loc.lat
        })
    }

    function getDetails(id) {
        pageData.loading = true
        LinghuoyonggongAPI.getLaborAppDetail({ id }).then(res => {
            pageData.laborParam = { ...pageData.laborParam, ...res }
            pageData.laborParam.addr = res.villageName
            pageData.workersParam = res.workers || []
            pageData.isActive = true
        }).finally(() => pageData.loading = false)
    }

    function submitLaborAdd() {
        if (!pageData.laborParam.villageName || !pageData.laborParam.contactName) {
            uni.showToast({ title: '请完善基本信息', icon: 'none' })
            return
        }
        if (!pageData.workersParam.length) {
            uni.showToast({ title: '请至少添加一名人员', icon: 'none' })
            return
        }
        const formData = { laborParam: pageData.laborParam, workersParam: pageData.workersParam }
        LinghuoyonggongAPI.postLaborAdd(formData).then(() => {
            uni.showToast({ title: '发布成功', icon: 'success' })
            setTimeout(() => uni.navigateBack(), 1500)
        })
    }

    function getCurrentDate() {
        const d = new Date()
        return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
    }
</script>

<template>
    <view class="page">
        <!-- 头部氛围 -->
        <view class="form-header">
            <text class="title">劳动力池登记</text>
            <text class="subtitle">登记本村劳动力，实现高效务工对接</text>
        </view>

        <view class="container">
            <fui-form ref="formRef">
                <!-- 基础信息卡片 -->
                <view class="section-card">
                    <view class="card-title">
                        <view class="line"></view>
                        <text>村镇基本信息</text>
                    </view>
                    
                    <view class="form-item">
                        <text class="label"><text class="red">*</text>所在村落</text>
                        <view class="picker-box" @click="pageData.showArea = true">
                            <view class="picker-inner">
                                <text v-if="!pageData.isActive" class="placeholder">请选择所在村镇</text>
                                <text v-else class="value">{{ pageData.laborParam.addr }}</text>
                                <fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon>
                            </view>
                        </view>
                    </view>

                    <fui-input label="负责人" placeholder="联系人姓名" v-model="laborParam.contactName" required label-size="28" />
                    <fui-input label="联系电话" type="tel" placeholder="负责人手机号" v-model="laborParam.contactMobile" required label-size="28" />
                </view>

                <!-- 人员列表卡片 -->
                <view class="section-card">
                    <view class="card-title flex-between">
                        <view class="flex-row">
                            <view class="line"></view>
                            <text>待工人员名单</text>
                        </view>
                        <view class="add-btn" @tap="openAddPersonPopup">
                            <fui-icon name="plus" :size="32" color="#5db66f"></fui-icon>
                            <text>添加成员</text>
                        </view>
                    </view>

                    <view v-if="!workersParam.length" class="empty-list">
                        <text>暂未添加成员，请点击上方“添加成员”</text>
                    </view>

                    <view v-for="(item, index) in workersParam" :key="index" class="person-item" @tap="editPersonPopup(index)">
                        <view class="person-left">
                            <view class="p-avatar" :class="'bg-' + (index % 4)">{{ item.name.substring(0, 1) }}</view>
                            <view class="p-info">
                                <view class="p-name-row">
                                    <text class="p-name">{{ item.name }}</text>
                                    <text class="p-tag">{{ item.attr }}</text>
                                </view>
                                <text class="p-meta">{{ getCalculateAge(item.birthday) }}岁 · {{ returnDictZhVel('gender', item.gender) }} · {{ returnDictZhVel('edu', item.edu) }}</text>
                            </view>
                        </view>
                        <fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon>
                    </view>
                </view>

                <view class="submit-box">
                    <fui-button text="确认发布劳动力池" radius="100rpx" background="#5db66f" @click="submitLaborAdd" />
                </view>
            </fui-form>
        </view>

        <!-- 人员编辑弹窗 -->
        <fui-bottom-popup :show="pageData.isPersonPopupShow" @close="pageData.isPersonPopupShow = false">
            <view class="popup-content">
                <view class="pop-header">
                    <text class="pop-title">{{ pageData.actionType == 'edit' ? '编辑人员信息' : '添加人员信息' }}</text>
                    <fui-icon name="close" :size="40" color="#ccc" @click="pageData.isPersonPopupShow = false"></fui-icon>
                </view>
                
                <view class="pop-form-scroll">
                    <view class="pop-form">
                        <fui-input label="姓名" placeholder="请输入姓名" v-model="tempWorkersParam.name" required label-size="28" :padding="['32rpx', '0']" />
                        <fui-input label="手机号" type="tel" placeholder="请输入手机号" v-model="tempWorkersParam.mobile" required label-size="28" :padding="['32rpx', '0']" />
                        
                        <view class="form-row-item">
                            <view class="row-label"><text class="red">*</text>性别</view>
                            <fui-radio-group v-model="tempWorkersParam.gender" class="radio-group">
                                <fui-label inline v-for="s in DictData.sexArr" :key="s.id" class="mr-60">
                                    <view class="flex-row align-center">
                                        <fui-radio :value="Number(s.itemValue)" color="#5db66f" :scaleRatio="0.9" />
                                        <text class="radio-text">{{ s.itemText }}</text>
                                    </view>
                                </fui-label>
                            </fui-radio-group>
                        </view>

                        <fui-input label="出生日期" placeholder="请选择" v-model="tempWorkersParam.birthday" @click="pageData.datePickerShow = true" disabled required label-size="28" :padding="['32rpx', '0']">
                            <template #suffix><fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon></template>
                        </fui-input>
                        
                        <fui-input label="学历" placeholder="请选择" v-model="tempWorkersParam.eduZh" @click="onPickerTap('education')" disabled required label-size="28" :padding="['32rpx', '0']">
                            <template #suffix><fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon></template>
                        </fui-input>
                        
                        <fui-input label="人员属性" placeholder="请选择" v-model="tempWorkersParam.attr" @click="onPickerTap('socialattributes')" disabled required label-size="28" :padding="['32rpx', '0']">
                            <template #suffix><fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon></template>
                        </fui-input>
                        
                        <fui-input label="技能" placeholder="请选择(最多3项)" v-model="tempWorkersParam.skill" @click="DictData.isSkillPopupShow = true" disabled required label-size="28" :padding="['32rpx', '0']">
                            <template #suffix><fui-icon name="arrowright" :size="32" color="#ccc"></fui-icon></template>
                        </fui-input>
                    </view>
                </view>

                <view class="pop-footer">
                    <view v-if="pageData.actionType == 'edit'" class="footer-btn-outline danger" @tap="delPersonData">
                        移除人员
                    </view>
                    <view v-else class="footer-btn-outline" @tap="pageData.isPersonPopupShow = false">
                        取消
                    </view>
                    <view class="footer-btn-primary" @tap="addPersonData">
                        保存信息
                    </view>
                </view>
            </view>
        </fui-bottom-popup>

        <!-- 各种选择器 -->
        <AreaPicker v-model:show="pageData.showArea" :layer="5" rootCode="43" title="选择所在村镇" @confirm="handleAreaConfirm" />
        <fui-date-picker :show="pageData.datePickerShow" type="3" min-date="1950-01-01" :max-date="getCurrentDate()" @change="dateBirthChange" @cancel="pageData.datePickerShow = false" />
        <fui-picker :show="pageData.attrPickerShow" :options="pageData.dictValArr" @change="attrChange" @cancel="pageData.attrPickerShow = false" />
        <fui-bottom-popup :show="DictData.isSkillPopupShow">
            <view class="skill-pop">
                <view class="pop-title">选择擅长技能</view>
                <fui-cascader ref="skillPopupRef" :options="DictData.skillOptionsVal" stepLoading @change="changeSkill" @complete="selectCompleteSkill" />
            </view>
        </fui-bottom-popup>
        
        <fui-toast ref="toastRef" />
        <fui-loading isFixed v-if="pageData.loading" />
    </view>
</template>

<style lang="scss" scoped>
    .page {
        min-height: 100vh;
        background-color: #f4f7f5;
        font-family: 'DingTalk Sans', sans-serif;
    }

    .form-header {
        background-color: #5db66f;
        padding: 60rpx 40rpx 120rpx;
        color: #fff;
        .title { font-size: 48rpx; font-weight: bold; display: block; letter-spacing: 2rpx; }
        .subtitle { font-size: 24rpx; opacity: 0.8; margin-top: 12rpx; display: block; }
    }

    .container {
        padding: 24rpx;
        margin-top: -80rpx;
        position: relative;
        z-index: 10;
    }

    .section-card {
        background-color: #fff;
        border-radius: 32rpx;
        padding: 40rpx 32rpx;
        margin-bottom: 28rpx;
        box-shadow: 0 8rpx 20rpx rgba(0,0,0,0.02);
        
        .card-title {
            margin-bottom: 40rpx;
            display: flex;
            align-items: center;
            .line { width: 8rpx; height: 36rpx; background-color: #5db66f; border-radius: 4rpx; margin-right: 20rpx; }
            text { font-size: 34rpx; font-weight: 800; color: #1a1a1a; letter-spacing: 1rpx; }
            &.flex-between { justify-content: space-between; }
            .flex-row { display: flex; align-items: center; }
            .add-btn {
                display: flex;
                align-items: center;
                background-color: #f0f9f1;
                padding: 12rpx 28rpx;
                border-radius: 100rpx;
                transition: all 0.2s;
                &:active { background-color: #e6f5e8; transform: scale(0.96); }
                text { font-size: 24rpx; color: #5db66f; margin-left: 8rpx; font-weight: bold; }
            }
        }
    }

    .form-item {
        padding: 36rpx 0;
        border-bottom: 1rpx solid #f8f8f8;
        display: flex;
        align-items: center;
        &:last-child { border-bottom: none; }
        .label { 
            font-size: 28rpx; 
            color: #1a1a1a; 
            width: 180rpx; 
            flex-shrink: 0; 
            font-weight: 500;
            .red { color: #ff4d4f; margin-right: 6rpx; } 
        }
        .picker-box {
            flex: 1;
            .picker-inner {
                display: flex;
                align-items: center;
                justify-content: space-between;
                width: 100%;
                .placeholder { color: #ccc; font-size: 28rpx; }
                .value { color: #333; font-weight: 500; font-size: 28rpx; flex: 1; margin-right: 10rpx; }
            }
        }
    }

    .empty-list {
        text-align: center;
        padding: 100rpx 0;
        font-size: 26rpx;
        color: #94a3b8;
        border: 2rpx dashed #f1f5f9;
        border-radius: 24rpx;
        background-color: #f8fafc;
    }

    .person-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 36rpx 0;
        border-bottom: 1rpx solid #f8f8f8;
        &:last-child { border-bottom: none; }
        &:active { background-color: #fafafa; border-radius: 12rpx; }
        
        .person-left {
            display: flex;
            align-items: center;
            .p-avatar {
                width: 96rpx; height: 96rpx; border-radius: 48rpx; color: #fff;
                display: flex; align-items: center; justify-content: center; font-size: 40rpx; font-weight: 800;
                box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
                &.bg-0 { background: linear-gradient(135deg, #5db66f 0%, #45a058 100%); }
                &.bg-1 { background: linear-gradient(135deg, #465cff 0%, #3a4cd9 100%); }
                &.bg-2 { background: linear-gradient(135deg, #fa8c16 0%, #e67e22 100%); }
                &.bg-3 { background: linear-gradient(135deg, #ff4d4f 0%, #e74c3c 100%); }
            }
            .p-info {
                margin-left: 28rpx;
                .p-name-row {
                    display: flex; align-items: center;
                    .p-name { font-size: 32rpx; font-weight: bold; color: #1e293b; }
                    .p-tag { 
                        font-size: 20rpx; color: #5db66f; background-color: #e6f5e8; 
                        padding: 4rpx 16rpx; border-radius: 8rpx; margin-left: 20rpx; 
                        font-weight: bold;
                    }
                }
                .p-meta { font-size: 24rpx; color: #64748b; margin-top: 10rpx; display: block; }
            }
        }
    }

    .submit-box { 
        padding: 60rpx 30rpx 100rpx;
        :deep(.fui-button) {
            box-shadow: 0 8rpx 24rpx rgba(93, 182, 111, 0.3);
        }
    }

    .popup-content {
        background-color: #fff; border-radius: 40rpx 40rpx 0 0;
        display: flex; flex-direction: column; max-height: 88vh;
        
        .pop-header {
            display: flex; justify-content: space-between; align-items: center; 
            padding: 40rpx 40rpx 30rpx;
            .pop-title { 
                font-size: 36rpx; 
                font-weight: 800; 
                color: #1a1a1a;
                letter-spacing: 1rpx;
            }
        }
        
        .pop-form-scroll { 
            flex: 1; 
            overflow-y: auto; 
            padding: 0 40rpx;
            /* 隐藏滚动条 */
            &::-webkit-scrollbar { display: none; }
        }
        
        .pop-form { 
            padding-bottom: 60rpx; 
        }
        
        .form-row-item {
            padding: 36rpx 0; 
            border-bottom: 1rpx solid #f5f5f5;
            display: flex; 
            align-items: center;
            
            .row-label { 
                font-size: 28rpx; 
                color: #1a1a1a; 
                width: 180rpx; 
                flex-shrink: 0; 
                font-weight: 500;
                .red { color: #ff4d4f; margin-right: 6rpx; } 
            }
            
            .radio-group { 
                display: flex; 
                align-items: center; 
                flex: 1;
            }
            
            .radio-text { 
                font-size: 28rpx; 
                color: #333; 
                margin-left: 16rpx; 
            }
        }
        
        .pop-footer { 
            padding: 32rpx 40rpx calc(50rpx + env(safe-area-inset-bottom));
            display: flex; 
            gap: 28rpx; 
            background-color: #fff;
            border-top: 1rpx solid #f5f5f5;
            box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.02);
            
            .footer-btn-outline {
                flex: 1; 
                height: 92rpx; 
                border-radius: 46rpx; 
                border: 2rpx solid #f0f0f0;
                display: flex; 
                align-items: center; 
                justify-content: center;
                color: #64748b; 
                font-size: 28rpx; 
                font-weight: bold;
                transition: all 0.2s;
                &:active { background-color: #f8fafc; }
                &.danger { color: #ff4d4f; border-color: #ffeef0; }
            }
            
            .footer-btn-primary {
                flex: 2; 
                height: 92rpx; 
                border-radius: 46rpx; 
                background: linear-gradient(135deg, #5db66f 0%, #45a058 100%);
                display: flex; 
                align-items: center; 
                justify-content: center;
                color: #fff; 
                font-size: 30rpx; 
                font-weight: bold;
                box-shadow: 0 10rpx 24rpx rgba(93, 182, 111, 0.25);
                transition: all 0.2s;
                &:active { transform: scale(0.98); opacity: 0.9; }
            }
        }
    }

    .mr-60 { margin-right: 60rpx; }
    .align-center { align-items: center; }

    /* 统一字体穿透优化 */
    :deep(.fui-input__label), 
    :deep(.fui-input__input),
    :deep(.fui-textarea__textarea),
    :deep(.fui-textarea__label) {
        font-family: 'DingTalk Sans', system-ui !important;
        color: #333 !important;
    }
    
    :deep(.uni-input-placeholder),
    :deep(.uni-textarea-placeholder) {
        font-family: 'DingTalk Sans' !important;
        font-size: 28rpx !important;
    }

    :deep(.fui-button) {
        font-family: 'DingTalk Sans' !important;
        font-weight: bold !important;
    }

    .skill-pop { background-color: #fff; padding: 40rpx; border-radius: 40rpx 40rpx 0 0; .pop-title { font-size: 32rpx; font-weight: bold; text-align: center; margin-bottom: 40rpx; } }
</style>
