<template>
    <div>
        <div class="dialog-h-content scroll-h" :class="{ 'visiual-form': source === 'visiual' }">
            <el-form ref="ref_add_form" :inline="true" :model="formData" :rules="dataRule" class="div_form">
                <el-row>
                    <el-col :span="24">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">所属组织: </span>
                            <span>{{ formData.agencyName || "--" }}</span>
                        </div>
                        <el-form-item label="所属组织" prop="agencyId" label-width="100px" v-else>
                            <el-cascader class="u-item-width-normal" ref="myCascader" v-model="agencyIdTemp"
                                :options="orgOptions" :props="orgOptionProps" :show-all-levels="false"
                                @change="handleChangeAgency" clearable>
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">姓名: </span>
                            <span>{{ formData.name || "--" }}</span>
                        </div>
                        <el-form-item label-width="100px" label="姓名" prop="name" v-else>
                            <el-input v-model="formData.name" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">性别: </span>
                            <span>{{
                                formData.gender
                                ? formData.gender == "1"
                                    ? "男"
                                    : formData.gender == "2"
                                        ? "女"
                                        : "--"
                                : "--"
                            }}</span>
                        </div>
                        <el-form-item label-width="100px" label="性别" v-else>
                            <el-select v-model="formData.gender" clearable>
                                <el-option v-for="item in genderList" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">出生日期: </span>
                            <span>{{ formData.birthday || '--' }}</span>
                        </div>
                        <el-form-item label-width="100px" label="出生日期" v-else>
                            <el-date-picker v-model="formData.birthday" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                                placeholder="选择日期" style="width: 202px" clearable>
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">民族: </span>
                            <span>{{ formData.nationName || "--" }}</span>
                        </div>
                        <el-form-item label-width="100px" label="民族" v-else>
                            <el-select v-model="formData.nation" clearable>
                                <el-option v-for="item in dicts.nationList" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row>
                    <el-col :span="12">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">证件号: </span>
                            <span>{{ formData.idNum || "--" }}</span>
                        </div>
                        <el-form-item label-width="100px" label="证件号" prop="idNum" v-else>
                            <el-input v-model="formData.idNum" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">联系电话: </span>
                            <span>{{ formData.mobile || "--" }}</span>
                        </div>
                        <el-form-item label-width="100px" label="联系电话" v-else>
                            <el-input v-model="formData.mobile" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">证件类型: </span>
                            <span>{{ formData.idTypeName || "--" }}</span>
                        </div>
                        <el-form-item label-width="100px" label="证件类型" prop="idType" v-else>
                            <el-select v-model="formData.idType" clearable>
                                <el-option v-for="item in dicts.idCard_type" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">文化程度: </span>
                            <span>{{ cultureLevelName(formData.cultureLevel) }}</span>
                        </div>
                        <el-form-item label-width="100px" label="文化程度" v-else>
                            <el-select v-model="formData.cultureLevel" clearable>
                                <el-option v-for="item in dicts.educationList" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">是否党员: </span>
                            <span>{{
                                formData.isParty != null
                                ? formData.isParty == 1
                                    ? "是"
                                    : formData.gender == 2
                                        ? "否"
                                        : "--"
                                : "--"
                            }}</span>
                        </div>
                        <el-form-item label-width="100px" label="是否党员" v-else>
                            <el-select v-model="formData.isParty" clearable>
                                <el-option v-for="item in binaryOptionList" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">岗位类型: </span>
                            <span>{{ formData.postTypes }}</span>
                        </div>
                        <el-form-item label-width="100px" label="岗位类型" prop="postTypes" v-else>
                            <el-select v-model="formData.postTypes" clearable>
                                <el-option v-for="item in dicts.public_welfare_post_type" :key="item.value"
                                    :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">入职时间: </span>
                            <span>{{ formData.hireDate || '--' }}</span>
                        </div>
                        <el-form-item label-width="100px" label="入职时间" v-else>
                            <el-date-picker v-model="formData.hireDate" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                                placeholder="选择日期" style="width: 202px" clearable>
                            </el-date-picker>
                        </el-form-item>
                    </el-col>

                </el-row>


                <el-row>
                    <el-col :span="24">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">现居地址: </span>
                            <span>{{ formData.currentResidence || "--" }}</span>
                        </div>
                        <el-form-item label-width="100px" label="现居地址" class="wd-wr" v-else>
                            <el-input v-model="formData.currentResidence" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">兴趣特长: </span>
                            <span>{{ formData.hobbyCodes || "--" }}</span>
                        </div>

                        <el-form-item label-width="100px" label="兴趣特长" v-else class="wd-wr">
                            <el-checkbox-group size="small" v-model="formData.hobbyCodes">
                                <el-checkbox v-for="items in dicts.SPECIAL_SKILL" :label="items.value" :key="items.value"
                                    :value="items.value">{{ items.label }}</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>


                </el-row>

                <el-row>
                    <el-col :span="12">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">兴趣描述: </span>
                            <span>{{ formData.interestDesc || "--" }}</span>
                        </div>
                        <el-form-item label-width="100px" label="兴趣描述" v-else>
                            <el-input v-model="formData.interestDesc" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">备注: </span>
                            <span>{{ formData.remark || "--" }}</span>
                        </div>
                        <el-form-item label-width="100px" label="备注" class="wd-wr" v-else>
                            <el-input v-model="formData.remark" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <div class="info-prop" v-if="formType == 'detail'">
                            <span class="info-title-2">管理范围: </span>
                            <span>{{ formData.manageScopes || "--" }}</span>
                        </div>
                        <el-form-item label="管理范围" prop="agencyId" label-width="100px" v-else>
                            <el-cascader class="u-item-width-normal" ref="myCascader" v-model="formData.manageScopes"
                                :options="orgOptions" :props="orgOptionProps" :show-all-levels="false" clearable>
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="div_btn">
            <el-button size="small" @click="handleCancle">取 消</el-button>
            <el-button size="small" type="primary" :disabled="btnDisable" @click="handleComfirm">确 定</el-button>
        </div>
    </div>
</template>
      
<script>
import { Loading } from "element-ui"; // 引入Loading服务
import { requestPost, requestGet } from "@/js/dai/request";
import nextTick from "dai-js/tools/nextTick";
import { genderList, binaryOptionList } from "@/js/columns/constants";

let loading; // 加载动画

export default {
    props: {
        source: {
            //展示来源：manage  管理平台    visiual  可视化平台
            type: String,
            default: "manage",
        },
    },

    data() {
        let orgOptionProps = {
            multiple: false,
            value: 'agencyId',
            label: 'agencyName',
            children: 'subAgencyList',
            checkStrictly: true
        }
        return {
            formType: '',
            btnDisable: false,
            // 不要证件类型 把本地户籍改成是否党员是否党员
            formData: {
                hobbyCodes: [],
                agencyId: "",
                name: "",
                mobile: "",
                gender: "",
                idType: "",
                idType: '',
                idNum: "",
                birthday: "",
                nation: "",
                placeOfDomicile: "",
                cultureLevel: "",
                marriage: "",
                interestDesc: "",
                remark: "",
                postTypes: [],
                manageScopes: [],
                hireDate: '',
                isParty: null
            },
            agencyIdTemp: [],
            orgOptionProps,
            orgOptions: [],
            genderList,
            binaryOptionList,
            dataRule: {
                name: [{ required: true, message: "姓名不能为空", trigger: "bulr" }],
                idNum: [{ required: true, message: "证件号不能为空", trigger: "bulr" }],

                idType: [
                    { required: true, message: "证件类型不能为空", trigger: "bulr" },
                ],
                postTypes: [
                    { required: true, message: "岗位类型不能为空", trigger: "bulr" },
                ],
                agencyId: [
                    { required: true, message: "所属组织不能为空", trigger: "bulr" },
                ],
                manageScopes: [
                    { required: true, message: "管理范围不能为空", trigger: "bulr" },
                ]
            },
            scopeId: "",

            dicts: {
                nationList: [],
                educationList: [],
                public_welfare_post_type: [],
                SPECIAL_SKILL: [],
                idCard_type: []
            },
        };
    },

    watch: {},

    components: {},
    created() {
        this.getDicts();
        this.getOrgTreeList()
    },
    async mounted() {
        this.startLoading();
        await this.endLoading();
    },

    methods: {
        async initForm(type, row) {
            this.formType = type;
            this.scopeId = row.categorizedResiId;
            await this.getDetail(this.scopeId);
        },
        async getDetail(categorizedResiId) {
            const url = `/actual/base/publicWelfarePost/detail/${categorizedResiId}`;
            const { data, code, msg } = await requestGet(url);
            if (code === 0) {
                this.formData = { ...data };
                await this.setAgencyIdFromLastLayerId(data.agencyId)
                console.log(this.agencyIdTemp);
            } else {
                this.$message.error(msg);
            }
        },
        async handleComfirm() {
            this.$refs["ref_add_form"].validate(async (valid) => {
                if (!valid) {
                    return false;
                }
                const url =
                    this.formType === "edit"
                        ? "/actual/base/resiCategorized/publicWelfarePost/update"
                        : "/actual/base/resiCategorized/publicWelfarePost/create";

                const { data, code, msg } = await requestPost(url, this.formData);
                if (code === 0) {
                    this.$message.success(this.formType == 'add' ? "添加成功" : '修改成功');
                    this.resetData();
                    this.$emit("handleComfirm");
                } else if (code >= 8000) {
                    this.$message.error(msg);
                }
            });
        },
        async getDicts() {
            try {
                const requests = [
                    this.$http.post("sys/dict/data/nation", {
                        formCode: "resi_base_info",
                    }),
                    this.$http.post("sys/dict/data/education", {
                        formCode: "resi_base_info",
                    }),
                    this.$http.post("sys/dict/data/dictlist", {
                        dictType: "public_welfare_post_type",
                    }),
                    this.$http.post("sys/dict/data/dictlist", {
                        dictType: "SPECIAL_SKILL",
                    }),
                    this.$http.post("sys/dict/data/dictlist", {
                        dictType: "idCard_type",
                    }),

                ];
                const dictKeys = [
                    "nationList",
                    "educationList",
                    "public_welfare_post_type",
                    'SPECIAL_SKILL',
                    'idCard_type'
                ]; // 对应的键名

                const results = await Promise.all(requests);
                results.forEach((result, index) => {
                    if (result.data.code === 0) {
                        this.dicts[dictKeys[index]].push(...result.data.data);
                    } else {
                        console.log(`获取${dictKeys[index]}失败: ${result.data.msg}`);
                    }
                });
            } catch (error) {
                console.log("获取字典失败: ", error);
            }
        },
        cultureLevelName(val) {
            let filtered = this.dicts.educationList.filter(
                (item) => item.value == val
            );
            let str = filtered.length > 0 ? filtered[0].label : null;
            return str ? str : "--";
        },
        handleCancle() {
            this.resetData();
            this.$emit("handleClose");
        },

        resetData() {
            this.formData = {};
        },
        getOrgTreeList() {
            this.$http
                .post('/gov/org/customeragency/agencygridtree', {})
                .then(({ data: res }) => {
                    if (res.code !== 0) {
                        return this.$message.error(res.msg)
                    } else {
                        console.log('获取组织树成功', res.data)
                        this.orgOptions = []
                        this.orgOptions.push(res.data)
                    }
                })
                .catch(() => {
                    return this.$message.error('网络错误')
                })
        },
        findPathInOptions(agencyId, options) {
            console.log(agencyId, options);
            for (let i = 0; i < options.length; i++) {
                console.log(options[i]);
                if (options[i].agencyId === agencyId) {
                    console.log(agencyId);
                    return [agencyId];
                } else if (options[i].subAgencyList) {
                    const pathFromChild = this.findPathInOptions(agencyId, options[i].subAgencyList
                    );
                    if (pathFromChild.length) {
                        return [options[i].agencyId].concat(pathFromChild);
                    }
                }
            }
            return [];
        },

        async setAgencyIdFromLastLayerId(lastLayerId) {
            console.log(lastLayerId, '事件');
            this.agencyIdTemp = await this.findPathInOptions(lastLayerId, this.orgOptions);
        },
        handleChangeAgency(val) {
            this.formData.agencyId = val[val.length - 1]
            console.log(this.formData.agencyId);
        },
        // 开启加载动画
        startLoading() {
            loading = Loading.service({
                lock: true, // 是否锁定
                text: "正在加载……", // 加载中需要显示的文字
                background: "rgba(0,0,0,.7)", // 背景颜色
            });
        },
        // 结束加载动画
        endLoading() {
            if (loading) {
                loading.close();
            }
        },
    },
};
</script>
      
<style lang="scss" scoped>
@import "@/assets/scss/modules/management/form-main.scss";
@import "@/assets/scss/modules/visual/a_customize.scss";
@import "@/assets/scss/modules/management/detail-main.scss";

.form-item::v-deep .el-form-item__label {
    color: #fff;
}

.form-item {
    .el-radio {
        color: #fff;
    }

    .el-checkbox {
        color: #fff;
    }
}

.wd-wr {
    width: 100%;

    /deep/ .el-form-item__content {
        width: calc(100% - 148px);
    }
}

.info-prop {
    margin-top: 29px;

    .info-title-2 {
        width: 100px;
        text-align: right;
        display: inline-block;
        padding-right: 10px;
    }
}
</style>
      
    
    