<template>
    <div class='g-main'>
        <el-form :model="form">
            <div v-for="itemH in formList">
                <h5>{{ itemH.title }}</h5>
                <template v-for="itemj in itemH.form">
                    <section class="f-flex" style="flex-wrap: wrap;">
                        <el-form-item v-for="(itemk, index) in itemj.children" :key="index" label-width="160px"
                            :label="itemk.label" :class="itemk.itemType == 'textarea' ? 'textareaDidth' : ''">
                            <template v-if="itemk.itemType == 'radio1'">
                                <section class="list_item_width_1">
                                    <el-radio v-for="ns in itemk.opction" :key="ns.value" size="small"
                                        v-model.trim="form[itemj.id][itemk.formName]" :label="ns.value"
                                        @click.native="handleFormChange(itemj.id,itemk.formName,itemk.itemType)">
                                        {{ ns.label }}
                                    </el-radio>
                                </section>
                            </template>

                            <template v-else-if="itemk.itemType == 'select1' && itemk.showFlag !== '0'">
                                <el-select v-model="form[itemj.id][itemk.formName]" :placeholder="`请选择${itemk.label}`"
                                    size="small" :multiple="itemk.multiple" :collapse-tags="itemk.collapseTags"
                                    clearable
                                    :style="{ 'width': itemk.formName == 'specialCategoryCode' ? '183px' : '' }"
                                    class="list_item_width_1">
                                    <el-option v-for="items in itemk.opction" :key="items.value" :label="items.label"
                                        :value="items.value" @click.native="handleFormChange(itemj.id,itemk.formName,itemk.itemType)">
                                    </el-option>
                                </el-select>
                            </template>

                            <template v-else-if="itemk.itemType == 'textarea1'">
                                <el-input type="textarea" :placeholder="`请输入${itemk.label}`" class="item-width-textarea"
                                    maxlength="120" size="small" show-word-limit resize="none" rows="3"
                                    v-model.trim="form[itemj.id][itemk.formName]" @change.native="handleFormChange(itemj.id,itemk.formName,itemk.itemType)">
                                </el-input>
                            </template>

                            <template v-else-if="itemk.itemType == 'input1'">
                                <el-input :placeholder="`请输入${itemk.label}`" class="list_item_width_1" size="small"
                                    :style="{ 'margin-right': itemk.label == '备注' ? '50px' : '' }"
                                    v-model.trim="form[itemj.id][itemk.formName]" clearable @change.native="handleFormChange(itemj.id,itemk.formName,itemk.itemType)">
                                </el-input>
                            </template>

                            <template v-else-if="itemk.itemType == 'inputNum'">
                                <el-input :placeholder="`请输入${itemk.label}`" size="small" class="list_item_width_1-text"
                                    :style="{ 'margin-right': itemk.label == '备注' ? '50px' : '' }"
                                    v-model.trim="form[itemj.id][itemk.formName]" clearable
                                    @blur="checkNumberInput(itemj.id, itemk.formName)" @change.native="handleFormChange(itemj.id,itemk.formName,itemk.itemType)">
                                </el-input><span class="u-data-tag">元</span>
                            </template>

                            <template v-else-if="itemk.itemType == 'checkbox'">
                                <el-checkbox-group size="small" v-model="form[itemj.id][itemk.formName]">
                                    <el-checkbox v-for="items in itemk.opction" :label="items.value"
                                        :style="{ 'margin-right': items.label != itemk.label ? '' : '19px' }"
                                        :key="items.value" :value="items.value" @click.native="handleFormChange(itemj.id,itemk.formName,itemk.itemType)">{{ items.label }}</el-checkbox>
                                </el-checkbox-group>
                            </template>

                            <template v-else-if="itemk.itemType == 'datepicker1' && itemk.showFlag !== '0'">
                                <el-date-picker v-model.trim="form[itemj.id][itemk.formName]" class="list_item_width_1"
                                    type="date" size="small" clearable placeholder="选择日期" format="yyyy 年 MM 月 dd 日"
                                    value-format="yyyy-MM-dd" @change="handleFormChange(itemj.id,itemk.formName,itemk.itemType)">
                                </el-date-picker>
                            </template>

                            <template v-else-if="itemk.itemType == 'cascader1'">
                                <el-cascader v-model="form[itemj.id].partyOrgId" :props="casProps"
                                    :options="itemk.opction" class="list_item_width_1" clearable size="small"
                                    @change="handlePartyOrgCascadarChange" ></el-cascader>
                            </template>

                            <template v-else-if="itemk.itemType == 'number'">
                                <el-input-number class="list_item_width_1" size="small" :min="1" :max="10"
                                    v-model.trim="form[itemj.id][itemk.formName]"></el-input-number>
                            </template>

                        </el-form-item>
                    </section>
                </template>
            </div>

        </el-form>
    </div>
</template>

<script>
import { requestPost, requestGet } from "@/js/dai/request";
import nextTick from "dai-js/tools/nextTick";

export default {
    data() {
        return {
            formType: null,
            formList: [],
            form: {
                // 党员信息
                parymemberInfoDto: {
                    joinTime: null,
                    positiveTime: null,
                    partyOrgId: null,
                    flowFlag: null,
                    flowActNum: null,
                    partyJob: null,
                    duty: null,
                    retiredFlag: null,
                    centerFlag: null,
                    studyNotNeed: null,
                    joinBranchName: null,
                    joinCommunityTime: null
                },
                // 残疾信息
                healthDto: {
                    disabilityCategoryCode: null,
                    disabilityLevel: null,
                    disabilityNum: null,
                    disabilityDesc: null,
                    guardianFlag: null,
                    guardianName: null,
                    guardianMobile:null,
                    specialSkillFlag: null,
                    workCapacityFlag: null
                },
                // 大病信息
                seriousIllnessDto: {
                    illnessCodes: []
                },
                // 慢病信息
                chronicDiseaseDto: {
                    chronicDiseaseCodes: []
                },
                // 死亡信息
                deathDto: {
                    deathTime: null
                },
                // 老年人
                oldPeopleDto: {
                    oldPeopleCategories: [],
                    resideSituation: null,
                    oldSubsidy: null
                },
                // 低保人员
                subsistenceAllowanceDto: {
                    reasons: [],
                    category:null ,
                },
                // 退役军人
                veteranDto: {
                    joinArmyTime: null,
                    leaveArmyTime: null,
                    serviceUnit: null,
                    receiveUnit: null,
                    settlementAmount: null,
                    trainDesc: null,
                    employmentSituation: null,
                    pubWelfareJobFlag: null
                },

                // 保障房人员
                ensureHouseDto: {
                    liveCommunity: null,
                    housingNature: null
                },
                // 统战人员
                unitedFrontDto: {
                    unitedFrontType: null
                },
                //特扶人员
                specialSupportDto: {
                    specialSupportType: null,//特扶类别
                    childName: null,//子女姓名
                    childGender: null,//子女性别
                    childDeathDate: null,//子女死亡日期
                    childDisabilityCategoryCode: null,//伤残类别
                    childDisabilityLevel: null,//伤残等级
                },
                // 志愿者
                volunteerDto: {
                    volunteerCategory: []
                },
            },
            casProps: {
                value: 'id',
                label: 'partyOrgName',
                lazy: true,
                lazyLoad: (node, resolve) => {
                    this.handleNextOrgTreeClick(node, resolve)
                },
                isLeaf: (data, node) => {
                    console.log(data);
                    //根据后台返回的数据判断是否还有下级 是否显示箭头图标
                    //el-tree懒加载无子级数据时去掉下拉箭头
                    if (data.partyOrgLevel == 7 || data.childrenQty == 0) {
                        return true
                    }
                },
                checkStrictly: true,
                multiple: false,
            },
            changId:null,
            changPid:null,
            changType:null,
            partyOrgIdPath:null
        };
    },
    props: {
    },
    created() { },
    activated() {
    },
    mounted() {
    },
    methods: {
        handleFormChange(pid,id,type){
            this.changPid = pid;
            this.changId = id;
            this.changType = type;
            nextTick(1000)
            this.$emit('submitExpand', this.form,{changId:this.changId,changPid:this.changPid,changType:this.changType})
        },
        checkNumberInput(itemj, itemk) {
            if (this.form[itemj][itemk]) {
                if (isNaN(this.form[itemj][itemk])) {
                    this.$message.error("请输入数字");
                    this.form[itemj][itemk] = "";
                } else {
                    this.form[itemj][itemk] = parseFloat(
                        this.form[itemj][itemk]
                    );
                }
            }
        },
        showForm() {
            this.$nextTick(() => {
                // console.log(this.form,'拓展组件form');
                const promises = this.formList.forEach((item) => {
                    item.form.map(async (group) => {
                        return group.children.reduce(async (accPromise, item) => {
                            const acc = await accPromise;
                            acc[item.formName] = null;
                            this.form[item.pformName].id = item.id
                            if (item.itemType == 'checkbox') {
                                this.form[item.pformName][item.formName] = item.value || []
                            } else if (item.itemType == 'cascader1' && item.orgPath) {
                                this.partyOrgIdPath = item.orgPath.split(':')[0]
                                await this.getOrgTree()
                                this.form[item.pformName][item.formName] = item.value || null
                            } else{
                                this.form[item.pformName][item.formName] = item.value != null?item.value:null;
                            }
                            if (item.opctionUrl) {
                                try {
                                    item.opction = await this.getDictDataForm(item.opctionUrl, item.opctionParams);
                                } catch (error) {
                                    console.error('Error fetching options:', error);
                                }
                            }
                            return acc;
                        }, Promise.resolve({}));
                    })
                })
                Promise.all(promises).then((results) => {

                }).catch((error) => {
                    console.error('Error fetching options:', error);
                });
            })
        },
        async getDictDataForm(url, params) {
            try {
                const { data } = await this.$http.post(url, params);
                return data.data;
            } catch (error) {
                console.log(error, `获取 ${opctionParams.dictType} 字典`);
            }
        },

        handlePartyOrgCascadarChange(selectedNode) {
            this.form.parymemberInfoDto.partyOrgId = selectedNode[selectedNode.length - 1];
            this.handleFormChange('parymemberInfoDto','partyOrgId','cascader1')
        },
        async handleNextOrgTreeClick(node, resolve) {
            await this.getTreeChildenList(node, resolve)
        },
        async getTreeChildenList(node, resolve) {
            if (node.data.partyOrgLevel <= 8) {
                resolve(null);
                return;
            }
            const url = "/actual/base/party/org/listNextLevelPartyOrgTreeNodesByPid"
            let params = {
                partyOrgPid: node.data.id
            }
            const { data, code, msg } = await requestGet(url, params)
            if (code === 0) {
                data.forEach(item => {
                    item.children = null;
                    item.leaf = item.partyOrgLevel === 7 || item.childrenQty === 0
                });
                resolve(data)
            } else {
                this.$message.error(msg)
            }
        },
        async getOrgTree() {
            try {
                const { data } = await requestGet('/actual/base/party/org/listPartyOrgTreeRoot4Select', { partyOrgId:this.partyOrgIdPath,depth:8 })
                this.formList.forEach(c => {
                    if (c.formId == "parymemberInfoDto") {
                        for (let i of c.form[0].children) {
                            if (i.formName == 'partyOrgId') {
                                i.opction = [data];
                            }
                        }
                    }

                })
            } catch (error) {
                console.log(error);
            }
        },
    },
    components: {},
    computed: {},
    watch: {
        'form': {
            handler(newVal, oldVal) {
                this.$emit('submitExpand', this.form,{changId:this.changId,changPid:this.changPid,changType:this.changType})
            },
            deep: true,
            immediate: true
        }
    },

}
</script>

<style lang='scss' scoped>
@import "@/assets/scss/modules/management/list-main.scss";

h5 {
    position: relative;
    font-size: 16px;
    margin: 22px 0;

    &::after {
        content: "";
        position: absolute;
        display: inline-block;
        left: -15px;
        top: -0px;
        width: 5px;
        height: 16px;
        background-color: #0056d6;
    }
}
</style>
