<template>
    <div class="main_box">
        <navbar :title="title" v-if="isShow == '1'"></navbar>
        <div class="wrapper" v-if="isShow == '1'">
            <van-form ref="form">
                <div class="title">个人信息</div>
                <van-field v-model="baseform.custName" maxlength="18" label="姓名" name="custName"
                    placeholder="请输入" class="required-field" :rules="[{ required: true, message: '姓名不能为空' }]"></van-field>
                <van-field label="性别" name="custGender">
                    <template #input>
                        <van-radio-group v-model="baseform.custGender" direction="horizontal">
                            <van-radio name="男">男</van-radio>
                            <van-radio name="女">女</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
                <van-field v-model="baseform.custAge" maxlength="3" label="年龄" name="custAge" placeholder="请输入"></van-field>
                <van-field v-model="baseform.custIdc" label="身份证号" name="custIdc" placeholder="请输入" class="required-field"
                    :rules="[{ required: true, message: '身份证号不能为空' }, { required: true, validator: validateCustIdc }]"
                    @blur="initInfoByCustIdc(baseform.custIdc)"></van-field>
                <van-field v-model="baseform.custEdu" label="学历" is-link readonly placeholder="请选择"
                    @click="showPicker = true"></van-field>
                <van-popup v-model="showPicker" position="bottom" :style="{ height: '40%' }">
                    <van-picker show-toolbar :columns="custEduList" @cancle="showPicker = false" @confirm="onConfirm"
                        @cancel="cancelStatus"></van-picker>
                </van-popup>
                <van-field v-model="baseform.birthday" is-link readonly label="出生日期" name="birthday" placeholder="请选择"
                    @click="showDatePicker = true"></van-field>
                <van-popup v-model:show="showDatePicker" position="bottom">
                    <van-datetime-picker v-model="currentDate" :min-date="minDate" :max-date="maxDate" type="date"
                        title="选择日期" @confirm="onConfirmDate" @cancel="showDatePicker = false"></van-datetime-picker>
                </van-popup>
                <van-field v-model="baseform.custPhone" label="联系方式" name="custPhone" placeholder="请输入"
                    class="required-field"
                    :rules="[{ required: true, message: '手机号不能为空' }, { required: true, validator: validatePhone, }]"
                    maxlength="11"></van-field>
                <div class="dzxzq">
                    <van-field v-model="baseform.registerLocation" label="户籍地址" is-link readonly placeholder="请选择"
                        @click="handleShowzcdz"></van-field>
                    <van-popup v-model="showzcPicker" position="bottom" :style="{ height: '40%' }">
                        <div class="btn_box">
                            <div @click="handlezcCancle">取消</div>
                            <div @click="handlezcConfim">确定</div>
                        </div>
                        <div class="picker_box">
                            <van-picker show-toolbar :columns="cityList" :value-key="'text'"
                                @change="handleChangeCity"></van-picker>
                            <van-picker show-toolbar :columns="countyList" :value-key="'text'"
                                @change="handleChangeCounty"></van-picker>
                            <van-picker show-toolbar :columns="jdList" :value-key="'text'"
                                @change="handleChangeJd"></van-picker>
                            <van-picker show-toolbar :columns="cunList" :value-key="'text'"
                                @change="handleChangeCun"></van-picker>
                        </div>
                    </van-popup>
                </div>
                <van-field v-model="registerLocationNum" label="门牌号" name="registerLocationNum"
                    placeholder="请输入门牌号"></van-field>
                <div class="dzxzq">
                    <van-field v-model="baseform.custLocation" label="住宅地址" is-link readonly placeholder="请选择"
                        @click="handleShowjydz"></van-field>
                    <van-popup v-model="showCustLocationPicker" position="bottom" :style="{ height: '40%' }">
                        <div class="btn_box">
                            <div @click="handleJydzCancle">取消</div>
                            <div @click="handleJydzConfim">确定</div>
                        </div>
                        <div class="picker_box">
                            <van-picker show-toolbar :columns="cityList" :value-key="'text'"
                                @change="handleChangeCity"></van-picker>
                            <van-picker show-toolbar :columns="countyList" :value-key="'text'"
                                @change="handleChangeCounty"></van-picker>
                            <van-picker show-toolbar :columns="jdList" :value-key="'text'"
                                @change="handleChangeJd"></van-picker>
                            <van-picker show-toolbar :columns="cunList" :value-key="'text'"
                                @change="handleChangeCun"></van-picker>
                        </div>
                    </van-popup>
                </div>
                <van-field v-model="custLocationNum" label="门牌号" name="custLocationNum" placeholder="请输入门牌号"></van-field>

                <div class="dzxzq">
                    <van-field v-model="baseform.jobLocation" label="单位地址" is-link readonly placeholder="请选择"
                        @click="handleShowdwdz"></van-field>
                    <van-popup v-model="showJobLocationPicker" position="bottom" :style="{ height: '40%' }">
                        <div class="btn_box">
                            <div @click="handleDwdzCancle">取消</div>
                            <div @click="handleDwdzConfim">确定</div>
                        </div>
                        <div class="picker_box">
                            <van-picker show-toolbar :columns="cityList" :value-key="'text'"
                                @change="handleChangeCity"></van-picker>
                            <van-picker show-toolbar :columns="countyList" :value-key="'text'"
                                @change="handleChangeCounty"></van-picker>
                            <van-picker show-toolbar :columns="jdList" :value-key="'text'"
                                @change="handleChangeJd"></van-picker>
                            <van-picker show-toolbar :columns="cunList" :value-key="'text'"
                                @change="handleChangeCun"></van-picker>
                        </div>
                    </van-popup>
                </div>
                <van-field v-model="jobLocationNum" label="门牌号" name="jobLocationNum" placeholder="请输入门牌号"></van-field>

                <van-field label="婚姻状况" name="isMarried">
                    <template #input>
                        <van-radio-group v-model="baseform.isMarried" direction="horizontal">
                            <van-radio name="未婚">未婚</van-radio>
                            <van-radio name="已婚">已婚</van-radio>
                            <van-radio name="离异">离异</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
                <van-field v-model="baseform.custSalary" label="年收入" maxlength="18" name="custSalary"
                    placeholder="请输入"></van-field>
                <van-field v-model="industryText" label="行业名称" is-link readonly placeholder="请选择"
                    @click="showPickerBelonBusi = true"></van-field>
                <van-popup v-model="showPickerBelonBusi" position="bottom" :style="{ height: '40%' }">
                    <van-picker show-toolbar :columns="belonBusiList" cancel-button-text="" confirm-button-text=""
                        @cancel="cancleBelonBusi" @confirm="changeBelonBusi" />
                </van-popup>



                <div class="title">关联信息</div>
                <van-field v-model="baseform.relateMerchant" maxlength="18" label="关联商户" name="relateMerchant"
                    placeholder="请输入"></van-field>
                <van-field v-model="baseform.relateMerchantCode" maxlength="18" label="关联商户统信码" name="relateMerchantCode"
                    placeholder="请输入"></van-field>
                <van-field v-model="baseform.relateBusiness" maxlength="18" label="关联企业" name="relateBusiness"
                    placeholder="请输入"></van-field>
                <van-field v-model="baseform.relateBusinessCode" maxlength="18" label="关联企业统信码" name="relateBusinessCode"
                    placeholder="请输入"></van-field>


                <div class="title">关联人信息</div>
                <div class="glrBox" v-for="(item, index) in list" :key="index">
                    <div class="glrBox_left">
                        <div class="left_img_box">
                            <img src="../../images/home/xkdjrw.png" alt="" style="width: 30px;height: 30px;">
                            <div class="fmyRln">{{ item.fmyRln }}</div>
                        </div>
                        <div class="left_main_box">
                            <div class="left_main_box_top">{{ item.fmyName }}</div>
                            <div class="left_main_box_card">身份号:{{ item.fmyCustIdc }}</div>
                            <div class="left_main_box_card">手机号:{{ item.tel }}</div>
                            <div class="left_main_box_card">行业:{{ item.belongBusiText }}</div>
                        </div>
                    </div>
                    <div class="glr_right">
                        <div class="glr_right_edit" @click="handleEdit(item, index)">编辑</div>
                        <div class="glr_right_delete" @click="handleDelete(index)">删除</div>
                    </div>
                </div>
                <div class="addBtn" @click="handleAdd">
                    <van-icon name="add"></van-icon>
                    <span>添加关联人</span>
                </div>

                <div class="title">其他信息</div>
                <van-field v-model="belongBranchText" label="客户经理归属机构" is-link readonly placeholder="请选择"
                    class="required-field" :rules="[{ required: true, message: '归属机构不能为空' }]"
                    @click="showBelongBranch = true"></van-field>
                <div class="gsjg">
                    <van-popup v-model="showBelongBranch" position="bottom" :style="{ height: '40%' }">
                        <van-picker show-toolbar :columns="belongBranchList" cancel-button-text="" confirm-button-text=""
                            @cancel="cancleBelongBranch" @confirm="changeBelongBranch" />
                    </van-popup>
                </div>

                <van-field v-model="belongUserText" label="客户经理" is-link readonly placeholder="请选择"
                    @click="customSelectFn"></van-field>
                <van-popup v-model="showUserPicker" position="bottom" :style="{ height: '40%' }">
                    <div class="search-input">
                        <van-search type="text" :left-icon="null" v-model="searchValue" placeholder="请输入搜索条件"
                            @clear="onCancel()" style="width:100%"/>
                        <div class="search_btn">
                            <van-icon name="search" @click="onSearch"></van-icon>
                        </div>
                    </div>
                    <van-picker show-toolbar :columns="userShowList" @cancle="showUserPicker = false" @confirm="onConfirmUser"
                        @cancel="cancelUser"></van-picker>
                </van-popup>
            </van-form>
            <div class="formBtn">
                <van-button plain color="#2372eb" @click="handleCancle" class="qx">取消</van-button>
                <van-button type="primary" @click="handleSave">保存</van-button>
            </div>
        </div>

        <div class="wrapper_two" v-if="isShow == '2'">
            <div class="navb" v-if="isShow == '2'">
                <div class="navLeft">
                    <van-icon name="arrow-left"></van-icon>
                    <span @click="handleAddCancle">返回</span>
                </div>
                <div class="navRight">添加关联人</div>
            </div>
            <van-form ref="addForm">
                <van-field v-model="addForm.fmyName" maxlength="18" label="关联人" name="fmyName"
                    placeholder="请输入"></van-field>
                <van-field v-model="addForm.fmyRln" label="与本人关系" is-link readonly placeholder="请选择"
                    @click="showfmyRlnPicker = true"></van-field>
                <van-popup v-model="showfmyRlnPicker" position="bottom" :style="{ height: '40%' }">
                    <van-picker show-toolbar :columns="FmyRlnList" @cancle="showfmyRlnPicker = false" :value-key="'label'"
                        @confirm="onConfmyNameUser" @cancel="cancelfmyName"></van-picker>
                </van-popup>
                <van-field v-model="addForm.fmyCustIdc" maxlength="18" label="身份证号" name="fmyCustIdc" class="required-field"
                    :rules="[{ required: true, message: '身份证号不能为空' }, { required: true, validator: addFormValidateCustIdc }]"
                    placeholder="请输入"></van-field>
                <van-field v-model="addForm.tel" maxlength="18" label="手机号" name="tel" placeholder="请输入"
                    class="required-field"
                    :rules="[{ required: true, message: '手机号不能为空' }, { required: true, validator: addFormValidatePhone }]"></van-field>
                <van-field v-model="addForm.belongBusiText" label="成员行业" is-link readonly placeholder="请选择"
                    @click="showPickercyBelonBusi = true"></van-field>
                <van-popup v-model="showPickercyBelonBusi" position="bottom" :style="{ height: '40%' }">
                    <van-picker show-toolbar :columns="belonBusiList" cancel-button-text="" confirm-button-text=""
                        @cancel="canclecyBelonBusi" @confirm="changecyBelonBusi" />
                </van-popup>
            </van-form>
            <div class="addFormBtn">
                <van-button plain color="#2372eb" @click="handleAddCancle" class="qx">取消</van-button>
                <van-button type="primary" @click="handleAddSave">保存</van-button>
            </div>
        </div>
    </div>
</template>
<script>
import navbar from '../../components/navbar/navbar.vue';
import {
    Button, Form, Field, RadioGroup, Radio, Popup, DatetimePicker, Picker, Area, Cascader, Icon, TreeSelect, Search
} from 'vant';
import { getRegStatus, getIndustryTree } from "@/service/api/custome";
import { addRecord, recordCustInfo } from "@/service/api/filing";
import { getIndicator, getDeptTree,getDeptTreeAll, getDeptUser,getDeptUserAll } from "@/service/api/dzTree";
import { custEduList } from '../details/custEdu'
import _ from "lodash";
export default {
    data() {
        return {
            title: '个人客户',
            isShow: '1',
            addOrEdit: '',
            editInddex: null,
            statusText: '',
            showPicker: false,
            statusList: [],
            showCustLocationPicker: false,
            showzcPicker: false,
            showJobLocationPicker: false,
            cityList: [],
            cityObj: {},
            countyList: [],
            countyObj: {},
            jdList: [],
            jdObj: {},
            cunList: [],
            custEduList,
            cunObj: {},
            showPickerBelonBusi: false,
            showPickercyBelonBusi: false,
            belonBusiList: [],
            baseform: {
                custName: '',
                custIdc: '',
                custGender: '',
                birthday: '',
                custAge: '',
                custPhone: '',
                isMarried: '',
                custSalary: '',
                relateMerchant: '',
                relateMerchantCode: '',
                relateBusiness: '',
                relateBusinessCode: '',
                status: '',
                businessScope: '',
                custLocation: '',
                jobLocation: '',
                registerLocation: '',
                custCapital: '',
                industry: '',
                belongBranchId: '',

            },
            custLocationNum: '',
            registerLocationNum: '',
            jobLocationNum: '',
            industryText: '',
            showDatePicker: false,
            currentDate: new Date(),
            minDate: new Date(1900, 0, 1),
            maxDate: new Date(),
            list: [

            ],
            belongBranchText: '',
            belongBranchId: '',
            showBelongBranch: false,
            belongBranchList: [

            ],
            activeId: '',
            activeIndex: '',
            branchPrams: {},
            belongUserText: '',
            belongUserId: '',
            showUserPicker: false,
            userList: [],
            userShowList: [],
            addForm: {
                fmyName: '',
                fmyRln: '',
                fmyCustIdc: '',
                tel: '',
                belongBusiText: '',
                belongBusi: '',
            },
            showfmyRlnPicker: false,
            FmyRlnList: [
                { label: '父亲', value: '父亲' },
                { label: '母亲', value: '母亲' },
                { label: '祖父', value: '祖父' },
                { label: '祖母', value: '祖母' },
                { label: '儿子', value: '儿子' },
                { label: '女儿', value: '女儿' },
                { label: '孙子', value: '孙子' },
                { label: '孙女', value: '孙女' },
                { label: '兄弟', value: '兄弟' },
                { label: '表兄弟', value: '表兄弟' },
                { label: '堂兄弟', value: '堂兄弟' },
                { label: '姐妹', value: '姐妹' },
                { label: '表姐妹', value: '表姐妹' },
                { label: '堂姐妹', value: '堂姐妹' },
                { label: '妻子', value: '妻子' },
                { label: '丈夫', value: '丈夫' },
            ],
            searchValue:"",
            industryList:[],
        }
    },
    components: {
        navbar: navbar,
        VanButton: Button,
        VanForm: Form,
        VanField: Field,
        VanRadioGroup: RadioGroup,
        VanRadio: Radio,
        VanPopup: Popup,
        VanDatetimePicker: DatetimePicker,
        VanPicker: Picker,
        VanArea: Area,
        VanCascadePicker: Cascader,
        VanIcon: Icon,
        VanTreeSelect: TreeSelect,
        VanSearch: Search,
    },
    created() {
        this.initRegStatus()
        this.initIndustryTree()
        this.initGetDeptTree()
    },
    methods: {
        validateCustIdc(value) {
            const regex = /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
            if (!regex.test(value)) {
                // callback(new Error('请输入正确的身份证号码'))
                this.$toast('请输入正确的身份证号码')
                this.baseform.custIdc = ''
                return
            } else {
                return
            }
        },
        validatePhone(value) {
            const regExp = /^1(3|4|5|6|7|8|9)[0-9]{9}$/
            if (!regExp.test(value)) {
                this.$toast('请输入正确的手机号码')
                this.baseform.custPhone = ''
                return
            } else {
                return
            }
        },
        addFormValidateCustIdc(value) {
            const regex = /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
            if (!regex.test(value)) {
                // callback(new Error('请输入正确的身份证号码'))
                this.$toast('请输入正确的身份证号码')
                this.addForm.fmyCustIdc = ''
                return
            } else {
                return
            }
        },
        addFormValidatePhone(value) {
            const regExp = /^1(3|4|5|6|7|8|9)[0-9]{9}$/
            if (!regExp.test(value)) {
                this.$toast('请输入正确的手机号码')
                this.addForm.tel = ''
                return
            } else {
                return
            }
        },
        onConfirmDate(value) {
            this.baseform.birthday = this.formatDate(value);
            const currentYear = new Date().getFullYear()
            const birthdayYear = Number(this.formatDate(value).slice(0, 4))
            this.baseform.custAge = currentYear - birthdayYear
            this.showDatePicker = false
        },
        formatDate(date) {
            if (date.getMonth() + 1 < 10) {
                return `${date.getYear() + 1900}-0${date.getMonth() + 1}-${date.getDate()}`;
            } else {
                return `${date.getYear() + 1900}-${date.getMonth() + 1}-${date.getDate()}`;
            }

        },
        onConfirm(value) {
            this.baseform.custEdu = value
            this.showPicker = false
        },
        cancelStatus() {
            this.showPicker = false
        },
        initRegStatus() {
            getRegStatus().then(res => {
                if (res.code == 200) {
                    this.statusList = res.data.map(item => {
                        return {
                            label: item.dictLabel,
                            value: item.dictValue
                        }
                    })

                }
            })
        },
        initStatus(data) {
            let arr = this.statusList.filter(item => item.value === data)
            if (arr && arr.length > 0) {
                return arr[0].label
            }
        },
        handleShowjydz() {
            this.showCustLocationPicker = true
            this.initGetIndicator()
        },
        initGetIndicator(data) {
            const query = {
                level: data ? data.level : '1',
                code: data ? data.value : 33
            }

            getIndicator(query).then(res => {
                if (res.code == 200) {
                    if (query.level == '1') {
                        this.cityList = res.data.map(item => {
                            return {
                                text: item.label,
                                value: item.value,
                                level: item.level
                            }
                        })
                        this.cityList.unshift({
                            text: '请选择',
                            value: '',
                            level: '1'
                        })
                    } else if (query.level == '2') {
                        this.countyList = res.data.map(item => {
                            return {
                                text: item.label,
                                value: item.value,
                                level: item.level
                            }
                        })
                        this.countyList.unshift({
                            text: '请选择',
                            value: '',
                            level: '2'
                        })
                    } else if (query.level == '3') {
                        this.jdList = res.data.map(item => {
                            return {
                                text: item.label,
                                value: item.value,
                                level: item.level
                            }
                        })
                        this.jdList.unshift({
                            text: '请选择',
                            value: '',
                            level: '3'
                        })
                    } else if (query.level == '4') {
                        this.cunList = res.data.map(item => {
                            return {
                                text: item.label,
                                value: item.value,
                                level: item.level
                            }
                        })
                        this.cunList.unshift({
                            text: '请选择',
                            value: '',
                            level: '4'
                        })
                    }

                }
            })
        },
        handleChangeCity(picker, value) {
            this.cityObj = value
            this.countyList = []
            const data = {
                level: value.level,
                value: value.value
            }
            this.initGetIndicator(data)

        },
        handleChangeCounty(picker, value) {
            this.countyObj = value
            this.jdList = []
            const data = {
                level: value.level,
                value: value.value
            }
            this.initGetIndicator(data)

        },
        handleChangeJd(picker, value) {
            this.jdObj = value
            this.cunList = []
            const data = {
                level: value.level,
                value: value.value
            }
            this.initGetIndicator(data)

        },
        handleChangeCun(picker, value) {
            this.cunObj = value
        },
        handleJydzCancle() {
            this.cityList = []
            this.countyList = []
            this.jdList = []
            this.cunList = []
            this.showCustLocationPicker = false
        },
        handleJydzConfim() {
            this.baseform.custLocation = `${this.cityObj.text}-${this.countyObj.text}-${this.jdObj.text}-${this.cunObj.text}`
            this.showCustLocationPicker = false
        },
        handleShowzcdz() {
            this.initGetIndicator()
            this.showzcPicker = true
        },
        handlezcCancle() {
            this.cityList = []
            this.countyList = []
            this.jdList = []
            this.cunList = []
            this.showzcPicker = false
        },
        handlezcConfim() {
            this.baseform.registerLocation = `${this.cityObj.text}-${this.countyObj.text}-${this.jdObj.text}-${this.cunObj.text}`
            this.showzcPicker = false
        },
        handleShowdwdz() {
            this.showJobLocationPicker = true
            this.initGetIndicator()
        },
        handleDwdzCancle() {
            this.cityList = []
            this.countyList = []
            this.jdList = []
            this.cunList = []
            this.showJobLocationPicker = false
        },
        handleDwdzConfim() {
            this.baseform.jobLocation = `${this.cityObj.text}-${this.countyObj.text}-${this.jdObj.text}-${this.cunObj.text}`
            this.showJobLocationPicker = false
        },
        initIndustryTree() {
            getIndustryTree().then(res => {
                this.industryOptions = res.data.map(item => {
                    return {
                        value: item.code,
                        label: item.name,
                        children: item.industryTrees
                    }
                })
                this.industryOptions.forEach(item => {
                    item.children.forEach(el => {
                        el.value = el.code
                        el.label = el.name
                    })
                })
                this.belonBusiList = res.data.map(item => {
                    return {
                        text: item.name,
                        id: item.code,
                        children: item.industryTrees
                    }
                })
                this.belonBusiList.forEach(item => {
                    item.children.forEach(el => {
                        el.text = el.name
                        el.id = el.code
                    })
                })
                this.belonBusiList.forEach(item => {
                    item.children.unshift({
                        text: '请选择',
                        id: ''
                    })
                })
                this.industryList=this.getIndustryTreeFn(this.belonBusiList);
            })
        },
        getIndustryTreeFn(nodes){
            return _.flatMap(nodes, (node) => [
                node, // 直接添加当前节点（保留所有属性）
                ...(node.children && node.children.length 
                ? this.getIndustryTreeFn(node.children) // 递归处理子节点
                : [])
            ]);
        },
        cancleBelonBusi() {
            this.showPickerBelonBusi = false
        },
        changeBelonBusi(value) {

            let strOne = value[0]
            let strTwo = value[1]
            if (strTwo == '请选择') {
                let obj = this.belonBusiList.find(item => item.text == strOne)
                this.baseform.industry = obj.id
                this.industryText = obj.text
            } else {
                let obj = {}
                for (let i = 0; i < this.belonBusiList.length; i++) {
                    for (let j = 0; j < this.belonBusiList[i].children.length; j++) {
                        if (strTwo == this.belonBusiList[i].children[j].text) {
                            obj = this.belonBusiList[i].children[j]
                        }
                    }
                }
                this.baseform.industry = obj.id
                this.industryText = obj.text
            }
            this.showPickerBelonBusi = false
        },
        canclecyBelonBusi() {
            this.showPickercyBelonBusi = false
        },
        changecyBelonBusi(value) {
            let strOne = value[0]
            let strTwo = value[1]
            if (strTwo == '请选择') {
                let obj = this.belonBusiList.find(item => item.text == strOne)
                this.addForm.belongBusi = obj.id
                this.industryText = obj.text
            } else {
                let obj = {}
                for (let i = 0; i < this.belonBusiList.length; i++) {
                    for (let j = 0; j < this.belonBusiList[i].children.length; j++) {
                        if (strTwo == this.belonBusiList[i].children[j].text) {
                            obj = this.belonBusiList[i].children[j]
                        }
                    }
                }
                this.addForm.belongBusi = obj.id
                this.addForm.belongBusiText = obj.text
            }
            this.showPickercyBelonBusi = false
        },
        initGetDeptTree() {
            getDeptTreeAll().then(res => {
                if (res.code == 200) {
                    this.belongBranchList = res.data.map(item => {
                        return {
                            text: item.label,
                            id: item.id,
                            children: item.children
                        }
                    })
                    this.belongBranchList[0].children.forEach(item => {
                        item.text = item.label
                    })
                    this.belongBranchList[0].children.forEach(item => {
                        if (item.children) {
                            item.children.forEach(el => {
                                el.text = el.label
                            })
                        }
                    })
                    this.belongBranchList.forEach(item => {
                        item.children.unshift({
                            id: '',
                            text: '请选择',
                            children: []
                        })
                    })
                    this.belongBranchList[0].children.forEach(item => {
                        if (item.children) {
                            item.children.unshift({
                                id: '',
                                text: '请选择'
                            })
                        }
                    })
                    console.log(this.belongBranchList, 'this.belongBranchList')
                }
            })
        },
        cancleBelongBranch() {
            this.showBelongBranch = false
        },
        changeBelongBranch(value) {
            let one = value[0]
            let two = value[1]
            let three = value[2]
            if (two == '请选择' && three == '请选择') {
                this.belongBranchText = one
                this.belongBranchId = this.belongBranchList[0].id
            } else if (two != '请选择' && three == '请选择') {
                this.belongBranchText = two
                let idArr = this.belongBranchList[0].children.find(item => item.text == two)
                this.belongBranchId = idArr.id
            } else if (two != '请选择' && three != '请选择') {
                this.belongBranchText = three
                let obj = this.findBelongBranchId(this.belongBranchList, three)
                this.belongBranchId = obj.id
            }
            this.showBelongBranch = false
            this.initGetDeptUser()
        },
        findBelongBranchId(tree, text) {
            for (const node of tree) {
                if (node.text === text) {
                    return node
                }
                if (node.children && node.children.length) {
                    const found = this.findBelongBranchId(node.children, text)
                    if (found) return found
                }
            }
            return null
        },
        initGetDeptUser() {
            const query = {
                deptid: this.belongBranchId
            }
            getDeptUserAll(query).then(res => {
                if (res.code == 200) {
                    this.userList = res.data.map(item => {
                        return {
                            id: item.userName,
                            text: `${item.nickName}-${item.userName}`,
                        }
                    })
                    this.userShowList=this.userList||[]
                }

                console.log(this.userList, 'this.userList')
            })
        },
        onConfirmUser(value) {
            if(!value){
                return
            }
            this.belongUserText = value.text
            this.belongUserId = value.id
            this.showUserPicker = false
        },
        cancelUser() { this.showUserPicker = false },
        handleAdd() {
            this.isShow = '2'
            this.addOrEdit = 'add'
            this.title = '添加关联人'
        },
        handleAddCancle() {
            this.isShow = '1'
            this.addOrEdit = ''
            this.title = '个人客户'
            this.addForm = {
                fmyName: '',
                fmyRln: '',
                fmyCustIdc: '',
                tel: '',
                belongBusiText: '',
            }
        },
        handleAddSave() {
            this.$refs.addForm.validate().then(() => {
                this.isShow = '1'
                this.title = '个人客户'
                if (this.addOrEdit == 'add') {
                    this.list.push(
                        {
                            fmyName: this.addForm.fmyName,
                            fmyRln: this.addForm.fmyRln,
                            fmyCustIdc: this.addForm.fmyCustIdc,
                            tel: this.addForm.tel,
                            belongBusiText: this.addForm.belongBusiText,
                        }
                    )
                    this.addForm = {
                        fmyName: '',
                        fmyRln: '',
                        fmyCustIdc: '',
                        tel: '',
                        belongBusiText: '',
                    }
                    this.addOrEdit = ''
                } else if (this.addOrEdit == 'edit') {
                    this.list.splice(this.editInddex, 1, {
                        fmyName: this.addForm.fmyName,
                        fmyRln: this.addForm.fmyRln,
                        fmyCustIdc: this.addForm.fmyCustIdc,
                        tel: this.addForm.tel,
                        belongBusiText: this.addForm.belongBusiText,
                    })
                }
            }).catch(() => {
                this.$toast('请输入必填项')
            })
        },
        handleEdit(item, index) {
            this.isShow = '2'
            this.editInddex = index
            this.addOrEdit = 'edit'
            this.title = '添加关联人'
            this.addForm.fmyName = item.fmyName
            this.addForm.fmyRln = item.fmyRln
            this.addForm.fmyCustIdc = item.fmyCustIdc
            this.addForm.tel = item.tel
            this.addForm.belongBusiText = item.belongBusiText
        },
        handleDelete(index) {
            this.list.splice(index, 1)
        },
        onConfmyNameUser(value) {
            this.addForm.fmyRln = value.value
            this.showfmyRlnPicker = false
        },
        cancelfmyName() {
            this.showfmyRlnPicker = false
        },
        handleCancle() {
            this.$router.go(-1);
        },
        initInfoByCustIdc(data) {

            //性别
            let sexCode = data.charAt(16)
            let gender = parseInt(sexCode, 10) % 2 === 0 ? '女' : '男'
            //年龄
            let today = new Date()
            let birthDate = new Date(data.substring(6, 10))
            let age = today.getFullYear() - birthDate.getFullYear()
            //出生日期
            let year = data.substring(6, 10)
            let mounth = data.substring(10, 12)
            let day = data.substring(12, 14)
            let csDate = `${year}-${mounth}-${day}`
            this.baseform.custGender = gender
            this.baseform.birthday = csDate
            this.baseform.custAge = age

            this.recordCustInfoFn();
        },
        recordCustInfoFn(){
            let params={
               custType: '0',
               custId: this.baseform.custIdc
            }
            recordCustInfo(params).then(res => {
                if(res.code == 200){
                    if(res?.data?.custInfoRecord?.custName){
                        this.baseform.custName=res?.data?.custInfoRecord?.custName
                    }
                    if(res?.data?.custInfoRecord?.custPhone){
                        this.baseform.custPhone=res?.data?.custInfoRecord?.custPhone
                    }
                    // if(res?.data?.custInfoRecord?.belongBranchId){
                    //     this.belongBranchId=res?.data?.custInfoRecord?.belongBranchId
                    // }
                    // if(res?.data?.custInfoRecord?.belongBranchName){
                    //     this.belongBranchText=res?.data?.custInfoRecord?.belongBranchName
                    // }
                    // if(res?.data?.custInfoRecord?.belongUserId){
                    //     this.belongUserId=res?.data?.custInfoRecord?.belongUserId
                    // }
                    // if(res?.data?.custInfoRecord?.belongUserName){
                    //     this.belongUserText=res?.data?.custInfoRecord?.belongUserName
                    // }
                    if(res?.data?.custInfoRecord?.industry){
                        this.baseform.industry=res?.data?.custInfoRecord?.industry
                        this.industryText=_.find(this.industryList, { code: res?.data?.custInfoRecord?.industry })?.text;
                    }
                    if(res?.data?.custInfoRecord?.custGender){
                        this.baseform.custGender=res?.data?.custInfoRecord?.custGender
                    }
                    if(res?.data?.custInfoRecord?.custAge){
                        this.baseform.custAge=res?.data?.custInfoRecord?.custAge
                    }
                    if(res?.data?.custInfoRecord?.isMarried){
                        this.baseform.isMarried=res?.data?.custInfoRecord?.isMarried
                    }
                    if(res?.data?.custInfoRecord?.custEdu){
                        this.baseform.custEdu=res?.data?.custInfoRecord?.custEdu
                    }
                    if(res?.data?.custInfoRecord?.custSalary){
                        this.baseform.custSalary=res?.data?.custInfoRecord?.custSalary
                    }
                    if(res?.data?.custInfoRecord?.birthday){
                        this.baseform.birthday=res?.data?.custInfoRecord?.birthday
                    }
                    if(res?.data?.custInfoRecord?.jobLocation){
                        this.baseform.jobLocation=res?.data?.custInfoRecord?.jobLocation
                    }
                    if(res?.data?.familyMembersRecords){
                        this.list=res?.data?.familyMembersRecords||[]
                        for(let i=0;i<this.list.length;i++){
                            if(this.list[i].belongBusi){
                                this.list[i].belongBusiText=_.find(this.industryList, { code: this.list[i].belongBusi })?.text;
                            }
                        }
                    }
                     if(res?.data?.recordRelates){
                        this.baseform.relateMerchant=res?.data?.recordRelates[0].relateMerchant
                        this.baseform.relateMerchantCode=res?.data?.recordRelates[0].relateMerchantCode
                        this.baseform.relateBusiness=res?.data?.recordRelates[0].relateBusiness
                        this.baseform.relateBusinessCode=res?.data?.recordRelates[0].relateBusinessCode
                    }
                }
            })
        },
        handleSave() {
            this.$refs.form.validate().then(() => {
                const infoParams = {
                    custType: '0',
                    custIdc: this.baseform.custIdc,
                    custName: this.baseform.custName,
                    custGender: this.baseform.custGender,
                    birthday: this.baseform.birthday,
                    custAge: this.baseform.custAge,
                    custPhone: this.baseform.custPhone,
                    registerLocation: `${this.baseform.registerLocation} ${this.registerLocationNum}`,
                    jobLocation: `${this.baseform.jobLocation} ${this.jobLocationNum}`,
                    custLocation: `${this.baseform.custLocation} ${this.custLocationNum}`,
                    isMarried: this.baseform.isMarried,
                    custEdu: this.baseform.custEdu,
                    custSalary: this.baseform.custSalary,
                    industry: this.baseform.industry,
                    belongBranchId: this.belongBranchId,
                    belongBranchName: this.belongBranchText,
                    belongUserId: this.belongUserId,
                    belongUserName: this.belongUserText,
                }
                console.log(infoParams)
                const params = {
                    custInfoRecord: infoParams,
                    familyMembersRecords: this.list,
                    recordRelates: [
                        {
                            relateMerchant: this.baseform.relateMerchant,
                            relateMerchantCode: this.baseform.relateMerchantCode,
                            relateBusiness: this.baseform.relateBusiness,
                            relateBusinessCode: this.baseform.relateBusinessCode,
                        }
                    ]

                }
                console.log(params)
                addRecord(params).then(res => {
                    sessionStorage.setItem("activeTab", 1);
                    this.$router.push('/filingHome');
                })
            }).catch(() => {
                this.$toast('请输入必填项')
            })

        },
        customSelectFn(){
            this.showUserPicker = true;
            this.searchValue="";
            this.userShowList=this.userList;
        },
        onCancel(){
            this.userShowList=this.userList;
        },
        onSearch(){
            this.userShowList=this.userList.filter(item => item.text.includes(this.searchValue));
        },
    }
}


</script>
<style lang="less" scoped>
.wrapper {
    padding-top: 46px;
    min-height: 100vh;
    font-size: 16px;
    padding-bottom: 60px;
}

.wrapper_two {
    min-height: 100vh;
    font-size: 16px;
    padding-bottom: 60px;
}

.title {
    color: rgb(89, 89, 89);
    font-size: 12px;
    line-height: 35px;
    padding-left: 15px;
}

.dzxzq {
    /deep/ .van-picker__toolbar {
        display: none;
    }
}

.btn_box {
    display: flex;
    padding: 20px;
    justify-content: space-between;
}

.picker_box {
    display: flex;

    /deep/ .van-picker {
        width: 40%;
    }
}

.glrBox {
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    margin-top: 3px;
    padding: 15px;
}

.glrBox_left {
    display: flex;
    align-items: center;

}

.left_img_box {
    width: 40px;
    height: 40px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
    background-color: rgb(246, 249, 255);
}

.fmyRln {
    margin-top: 5px;
}

.left_main_box {
    margin-left: 20px;
}

.left_main_box_top {
    font-size: 16px;
    font-weight: 600;
    line-height: 30px;
}

.left_main_box_card {
    font-size: 12px;
    line-height: 25px;
    color: rgb(140, 140, 140);
}

.glr_right {
    display: flex;
}

.glr_right_edit {
    background-color: rgb(233, 241, 253);
    color: rgb(35, 114, 235);
    height: 33px;
    line-height: 33px;
    width: 60px;
    text-align: center;
    border-radius: 5px;
}

.glr_right_delete {
    background-color: rgb(253, 243, 234);
    color: rgb(238, 140, 21);
    height: 33px;
    line-height: 33px;
    width: 60px;
    text-align: center;
    border-radius: 5px;
    margin-left: 5px;
}

.addBtn {
    margin-top: 5px;
    line-height: 50px;
    background-color: rgb(233, 241, 253);
    color: rgb(35, 114, 235);
    text-align: center;
    border: 1px solid rgb(35, 114, 235);
}

.addFormBtn {
    margin-top: 50px;
    display: flex;
    justify-content: space-between;
    padding: 0 10px;

    /deep/ .van-button {
        width: 48%;
    }
}

.formBtn {
    display: flex;
    justify-content: space-between;

    /deep/ .van-button {
        width: 48%;
    }
}

.navb {
    background-color: #fff;
    display: flex;
    line-height: 46px;
    padding-left: 16px;
}

.navLeft {
    color: #1989fa;
    width: 40%;
}

.gsjg {
    /deep/ .van-ellipsis {
        white-space: normal;
    }
}

.required-field {
    /deep/ .van-field__label::after {
        content: " *";
        color: red;
    }
}
.search-input {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-right: 15px;
}
.search_btn {
    background-color: rgb(24, 144, 255);
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 40px;
    height: 40px;
    color: #fff;
    font-size: 20px;
}
</style>