<template>
    <div class="flex-container">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <!-- 搜索区域 -->
            <a-form layout="inline">
                <a-row :gutter="24">
                    <a-col :md="4" :sm="8">
                        <a-form-item  label="姓名">
                            <a-input  placeholder="姓名" v-model="queryParam.name"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md="4" :sm="8">
                        <a-form-item  label="账号">
                            <a-input  placeholder="账号" v-model="queryParam.account"></a-input>
                        </a-form-item>
                    </a-col>

                    <a-col :md="4" :sm="8">
                        <a-form-item label="县分">
                            <a-select v-model="queryParam.substName" @change="getSchoolNames">
                                <a-select-option key="">--全部--</a-select-option>
                                <a-select-option v-for="d in subNames" :key="d.value" :value="d.value">{{d.text}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="5" :sm="10">
                        <a-form-item label="学校">
                            <a-select v-model="queryParam.school" style="width: 13rem;">
                                <a-select-option key="">--全部--</a-select-option>
                                <a-select-option v-for="d in schoolNames" :key="d.value" :value="d.value">{{d.text}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="3" :sm="6">
                        <a-form-item :labelCol="{span: 6}"  :wrapperCol="{span: 8, offset: 1}"  label="角色">
                            <a-select placeholder="请选择" @change="changeSubst" v-model="queryParam.roleid" >
                                <a-select-option key="">请选择</a-select-option>
                                <a-select-option v-for="data in roleList" :value="data.id">{{ data.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <a-col :md="3" :sm="6">
                        <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}"  label="活跃状态">
                            <a-select showSearch placeholder="请选择"  v-model="queryParam.isActive" style="width: 6rem;">
                                <a-select-option key="">请选择</a-select-option>
                                <a-select-option key="1">活跃</a-select-option>
                                <a-select-option key="0">不活跃</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <a-col :md="3" :sm="6">
                        <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}"  label="状态">
                            <a-select showSearch placeholder="请选择"  v-model="queryParam.status" >
                                <a-select-option key="">请选择</a-select-option>
                                <a-select-option key="1">启用</a-select-option>
                                <a-select-option key="2">冻结</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <a-col :md="4" :sm="8">
                        <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}"  label="身份上传状态">
                            <a-select showSearch placeholder="请选择"  v-model="queryParam.isUpload" >
                                <a-select-option key="">请选择</a-select-option>
                                <a-select-option key="1">已上传</a-select-option>
                                <a-select-option key="0">未上传</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>


                    <span class="table-page-search-submitButtons" style="float: left; overflow: hidden;">
                        <a-col :md="6" :sm="24">
                            <a-button @click="search()" type="primary">查询</a-button>
                            <a-button @click="openAddUser()" style="margin-left: 8px" icon="plus" type="primary">新增</a-button>
                            <a-button @click="exportList()" style="margin-left: 8px" icon="export" type="primary">导出</a-button>
                        </a-col>
                    </span>
                </a-row>
            </a-form>

            <!--列表-->
            <s-table :columns="columns" :data="rowdata" bordered ref="table" size="small" class="flex-filling"  :locale="emptyText">
                <template slot="genderoperation" slot-scope="text">
                   <span v-if="text==1">男</span>
                    <span v-else>女</span>
                </template>
                <template slot="statusRender" slot-scope="text, record" v-if="record.status != 3">
                    <a-switch checkedChildren="正常" @change="changeDongjie($event,record.id)" unCheckedChildren="冻结" :defaultChecked="record.status==2?false:true" />
                </template>
                <template slot="activeRender" slot-scope="text">
                    <span v-if="text==1">活跃</span>
                    <span v-if="text==2">不活跃</span>
                    <span v-else></span>
                </template>
                <template slot="operation" slot-scope="text,record">
                    <a @click="modifyfunction(record)">编辑</a>
                    <a-divider type="vertical"/>
                    <a @click="modifyFXY(record)">
                      <a-badge :count="record.fxsCount" type="info"><span>分销员</span>
                      </a-badge>
                    </a>
                    <a-divider type="vertical"/>
                    <a-popconfirm title="是否要删除此行？" @confirm="deleteUser(record.id)">
                        <a>删除</a>
                    </a-popconfirm>
                </template>
            </s-table>

            <!--新增用户--弹框-->
            <a-modal :title="titleName" :visible="addUser"  @ok="createOk" @cancel="createCancel" html-type="submit" width="720px">
                <a-form :form="addFormtable" autocomplete="off">
                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="账号" >
                        <a-input placeholder="请输入账号" v-decorator="[ 'account', {rules: [{ required: true, message: '账号不能为空！' ,whitespace:true}]} ]"></a-input>
                    </a-form-item>
                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="电话" >
                        <a-input placeholder="请输入电话" v-decorator="[ 'phone', {rules: [{ required: true, message: '电话不能为空！' ,whitespace:true}]} ]"></a-input>
                    </a-form-item>
                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="姓名" >
                        <a-input placeholder="请输入姓名" v-decorator="[ 'name', {rules: [{ required: true, message: '姓名不能为空！' ,whitespace:true}]} ]"></a-input>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="身份证号" >
                        <a-input placeholder="请输入身份证号"   v-decorator="[ 'idCard', {rules: [{ required: true, message: '身份证号不能为空！' ,whitespace:true}]} ]"></a-input>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="性别">
                        <a-select placeholder="请选择" v-decorator="[ 'sex', {rules: [{ required: true, message: '性别不能为空！' ,whitespace:true}]} ]">
                            <a-select-option key="">请选择</a-select-option>
                            <a-select-option key="1">男</a-select-option>
                            <a-select-option key="2">女</a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="年级">
                        <a-select placeholder="请选择" v-decorator="[ 'grade', {rules: [{ required: true, message: '年级不能为空！' ,whitespace:true}]} ]">
                            <a-select-option key="">请选择</a-select-option>
                            <a-select-option key="20级">20级</a-select-option>
                            <a-select-option key="19级">19级</a-select-option>
                            <a-select-option key="18级">18级</a-select-option>
                            <a-select-option key="17级">17级</a-select-option>
                            <a-select-option key="16级">16级</a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}"  label="密码">
                        <a-input placeholder="请输入密码" type="password" v-decorator="[ 'password', {rules: [{ required: true, message: '密码不能为空！' ,whitespace:true}]} ]"></a-input>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}"  :wrapperCol="{span: 8, offset: 1}"  label="县分">
                        <a-select placeholder="请选择" @change="changeSubst(1)" v-model="addForm.subName" >
                            <a-select-option key="">请选择</a-select-option>
                          <a-select-option v-for="d in subNames" :key="d.value" :value="d.value">{{d.text}}</a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}"  label="学校名称">
                        <a-select placeholder="请选择" v-decorator="[ 'schoolId', {rules: [{ required: true, type: 'number',message: '学校不能为空！' ,whitespace:true}]} ]">
                            <a-select-option key="">请选择</a-select-option>
                            <a-select-option v-for="data in schoolList"  :value="data.id">
                                {{ data.school_name}}
                            </a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="学子公司职位">
                        <a-select placeholder="请选择" v-model="addForm.position" @change="changePosition(1)">
                            <a-select-option key="">非学子公司成员</a-select-option>
                            <a-select-option key="总经理">总经理</a-select-option>
                            <a-select-option key="楼长">楼长</a-select-option>
                            <a-select-option key="成员">成员</a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :style="leaderDisplay" :wrapperCol="{span: 8, offset: 1}" label="学子公司上级">
                        <a-select placeholder="请选择" v-decorator="[ 'parentId', {rules: [{ required: false, message: '学子公司上级不能为空！' ,whitespace:true}]} ]">
                            <a-select-option key="">请选择</a-select-option>
                            <a-select-option v-for="data in xzUserList"  :value="data.id">
                                {{ data.name}}
                            </a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 12, offset: 1}" label="通过预实名账号">
                        <a-radio-group  v-decorator="['ysm']" >
                            <a-radio :value="data.id" v-for="data in autoCompleteResult">{{data.userName}}</a-radio>
                        </a-radio-group>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="角色" >
                        <!-- <a-input placeholder="请输入部门" v-model="modelData.content" @click="handelDepartment"></a-input> -->
                        <treecheck ref="tree1" @selectcheck="contentSelectCheck1"  :treeCheckable="true" :createFun="userRoleTreeList"></treecheck>
                    </a-form-item>
                </a-form>
            </a-modal>
            <!--编辑----弹框-->
            <a-modal :title="titleName" :visible="modifyvisible"  @ok="createfunctionOk" @cancel="createfunctionCancel" html-type="submit" width="720px">
                <a-form :form="Formtable">
                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="电话号码">
                        <a-input placeholder="电话号码" v-decorator="[ 'phone', {rules: [{ required: true, message: '电话号码不能为空！' ,whitespace:true}]} ]"></a-input>
                    </a-form-item>
                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="账号">
                        <a-input placeholder="账号" v-decorator="[ 'account', {rules: [{ required: true, message: '账号不能为空！' ,whitespace:true}]} ]"></a-input>
                    </a-form-item>
                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="姓名">
                        <a-input placeholder="姓名" v-decorator="[ 'name', {rules: [{ required: true, message: '姓名不能为空！' ,whitespace:true}]} ]"></a-input>
                    </a-form-item>
                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="身份证">
                        <a-input placeholder="身份证" v-decorator="[ 'idCard', {rules: [{ required: true, message: '身份证不能为空！' ,whitespace:true}]} ]"></a-input>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}"  label="密码">
                        <a-input placeholder="密码不变时，不用填写" type="password" v-decorator="[ 'password' ]"></a-input>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="性别">
                        <a-radio-group  v-decorator="['sex', {rules: [{ required: true, message: '性别不能为空！' ,whitespace:true}]} ]" >
                            <a-radio value="1">男</a-radio>
                            <a-radio value="2">女</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="年级">
                        <a-select placeholder="请选择" v-decorator="[ 'grade', {rules: [{ required: true, message: '年级不能为空！' ,whitespace:true}]} ]">
                            <a-select-option key="">请选择</a-select-option>
                            <a-select-option key="20级">20级</a-select-option>
                            <a-select-option key="19级">19级</a-select-option>
                            <a-select-option key="18级">18级</a-select-option>
                            <a-select-option key="17级">17级</a-select-option>
                            <a-select-option key="16级">16级</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item :labelCol="{span: 6}"  :wrapperCol="{span: 8, offset: 1}"  label="县分">
                        <a-select placeholder="请选择" @change="changeSubst(2)" v-model="modifyForm.subName" >
                            <a-select-option key="">请选择</a-select-option>
                            <a-select-option key="">请选择</a-select-option>
                          <a-select-option v-for="d in subNames" :key="d.value" :value="d.value">{{d.text}}</a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}"  label="学校名称">
                        <a-select placeholder="请选择" v-model="modifyForm.schoolId">
                            <a-select-option key="">请选择</a-select-option>
                            <a-select-option v-for="data in schoolList"  :value="data.id">
                                {{ data.school_name}}
                            </a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="学子公司职位">
                        <a-select placeholder="请选择" v-model="modifyForm.position" @change="changePosition(2)">
                            <a-select-option key="">非学子公司成员</a-select-option>
                            <a-select-option key="总经理">总经理</a-select-option>
                            <a-select-option key="楼长">楼长</a-select-option>
                            <a-select-option key="成员">成员</a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="院校配置">
                        <template>
                            <a-tree-select
                                v-model="treeModelValue"
                                style="width: 100%"
                                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                :tree-data="treeData"
                                tree-checkable
                                :show-checked-strategy="SHOW_PARENT"
                                placeholder="请选择管理院校"
                            />
                          </template>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :style="leaderDisplay" :wrapperCol="{span: 8, offset: 1}" label="学子公司上级">
                        <a-select placeholder="请选择" v-model="modifyForm.parentId">
                            <a-select-option key="">请选择</a-select-option>
                            <a-select-option v-for="data in xzUserList" :key="data.id"  :value="data.id">
                                {{ data.name}}
                            </a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}" label="角色" >
                        <!-- <a-input placeholder="请输入部门" v-model="modelData.content" @click="handelDepartment"></a-input> -->
                        <treecheck ref="tree2" @selectcheck="contentSelectCheck2"  :treeCheckable="true" :createFun="userRoleTreeList"></treecheck>
                    </a-form-item>
                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 12, offset: 1}" label="通过预实名账号">
                        <a-radio-group  v-decorator="['ysm']" >
                            <a-radio :value="data.id" v-for="data in autoCompleteResult">{{data.userName}}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </a-modal>

          <!--分销员----弹框-->
            <a-modal :title="titleName" :visible="modifyvisibleFXY"  @ok="createFXYOk" @cancel="createCancel" html-type="submit" width="720px">
              <a-button @click="handleTabsAdd()" style="margin-left: 8px" icon="plus" type="primary">新增分销商</a-button>
              <a-button @click="handleTabRemove()" style="margin-left: 8px" icon="close" type="primary">删除当前分销商</a-button>
              <a-tabs name="tab" ref="tabs" @tabClick="handleTabClick">
                <a-tab-pane :key="item" :name="item" v-for="item in fxyList">
                  <span slot="tab">{{ modifyFormFXY.name+item }}</span>
                  <div :id="qrcode + item" ref="qrcode"></div>
                </a-tab-pane>
              </a-tabs>
            </a-modal>
        </div>
    </div>
</template>

<script>
    import STable from '@/components/table'
    import QRCode from 'qrcodejs2'
    import {
        findByList,modify,getlistysm,getRoleList,
        addPartner,getSubstList,getSchoolList,getXzUserList,
        exportUserList,deleteUser, lockUser, unlockUser,pushFxyList
    } from "../../../api/school-center/PartnerManagementAPI"
    import {cloneObject,exportFile} from '@/utils/util'
    import treecheck from '@/components/sysmanage/treeCheck'
    import treeList from '@/components/sysmanage/treeList'
    import {
        tabList,
        userRoleTreeList,
    } from '@/api/system';
    import {getSchoolNames, initSubstName} from "../../../api/school-center/userManager/newUserAPI";
    import {notification, TreeSelect} from 'ant-design-vue';
    const SHOW_PARENT = TreeSelect.SHOW_PARENT;

    export default {
        name: "PartnerManagement",
        components: {
            STable,
            treeList,
            treecheck,
            QRCode,
        },
        data: function () {
            return {
                emptyText: {emptyText: '暂无数据'},
                Formtable: this.$form.createForm(this, {name: 'Formtable'}),
                addFormtable: this.$form.createForm(this, {name: 'addFormtable'}),
                titleName : "新增",
                treeModelValue: [],
                treeData: [],
                SHOW_PARENT,
                queryParam: {
                    name: '',
                    account: '',
                    roleid: '',
                    isUpload: '',
                    status: '',
                    isActive: '',
                    substName:'',
                    school:'',
                },
                addForm: {
                    account: '',
                    phone:'',
                    name:'',
                    idCard: '',
                    sex: '',
                    grade: '',
                    password: '',
                    subName: '',
                    substName: '',
                    schoolId: '',
                    roleId: '',
                    position:'',
                    parentId:'',
                    parentIds:'',
                    ysm:'',
                },
                leaderDisplay:'display:none',
                modifyvisible:false,
                allowStatus: true,
                schoolSelect: '',
                modifyForm: {
                    id:"",
                    phone: '',
                    school:'',
                    name: '',
                    account: '',
                    idCard: '',
                    password: '',
                    sex: '',
                    grade: '',
                    substName: '',
                    ysm: '',
                    schoolId: '',
                    roleId: '',
                    position:'',
                    parentId:'',
                },
                modifyvisibleFXY:false,
                FXYFormtable: this.$form.createForm(this, {name: 'FXYFormtable'}),
                modifyFormFXY:{
                  id:"",
                  name:"",
                  fxs:"",
                },
                fxyList:[],
                qrcode:"qrcode",
                qrcodeLink:"https://dx.dianyuanjiangli.com/mobile/#/hhr/home?id=",
                autoCompleteResult:[],
                subNameList: [],
                substList: [],
                schoolNames: [],
                subNames: [],
                roleList: [],
                schoolList:[],
                schoolListParam: [],
                xzUserList:[],
                addSubName:'',
                columns: [
                    {dataIndex: 'id', width:100, title: '合伙人id', align: 'center'},
                    {dataIndex: 'name', width: 100, title: '姓名', align: "center"},
                    {dataIndex: 'phone', width: 200, title: '电话', align: "center"},
                    {dataIndex: 'school', width: 200, title: '学校', align: "center"},
                    {dataIndex: 'idCard', width: 200, title: '身份证', align: "center"},
                    {dataIndex: 'account', width: 200, title: '账号', align: "center"},
                    {dataIndex: 'substName', width: 100, title: '县分', align: "center"},
                    {dataIndex: 'roleName', width: 200, title: '角色', align: "center"},
                    {dataIndex: 'sex', width: 100, title: '性别', align: "center",scopedSlots: {customRender: 'genderoperation'},},
                    {dataIndex: 'isActive', width: 200, title: '活跃状态', align: "center",scopedSlots: {customRender: 'activeRender'},},
                    {dataIndex: 'status',width:100,fixed: 'right', sort: true, title: '状态',  scopedSlots: { customRender: 'statusRender' },},
                    {
                        dataIndex: 'operation',
                        width: 150,
                        title: '操作',
                        align: "center",
                        scopedSlots: {customRender: 'operation'},
                        fixed: "right"
                    }]
                ,
                rowdata: parameter => {
                    let params = {
                        pageNo: parameter.pageNo,
                        pageSize: parameter.pageSize
                    }

                    //表示
                    let obj = cloneObject(this.queryParam)

                    // 获取角色下拉清单
                    this.roleList = [];
                    getRoleList().then(res => {
                        if (res.state == 'success') {
                            res.data.forEach((key)=>{
                                this.roleList.push(key)
                            })
                        }
                    })

                    return findByList(Object.assign(params,obj)).then(res => {
                        let data = {}
                        if (res.state !== 'success') {
                            this.$message.error("查询失败！", 5);
                            this.emptyText.emptyText = '查询失败！'
                            data = {
                                data: [],
                                pageSize: parameter.pageSize,
                                pageNo: 1,
                                totalCount: 0
                            }
                        } else {
                            data = {
                                data: res.data.records,
                                pageSize: parameter.pageSize,
                                pageNo: parameter.pageNo,
                                totalCount: res.data.total
                            }
                        }
                        return data
                    })
                },
                keyRecord: '',
                recordId: '',
                addUser: false,
                userRoleTreeList:userRoleTreeList,
            }
        },
        watch : {
          treeModelValue(data) {
          }
        },
        methods:{
            search() {
                this.$refs.table.refresh({search: true})
            },
            modifyfunction(data) {
                this.modifyForm.id = data.id
                this.titleName = "编辑"
                this.modifyvisible = true
                setTimeout(() => {
                    this.Formtable.setFieldsValue({
                        phone: data.phone,
                        schoolId: data.schoolId,
                        name: data.name,
                        account: data.account,
                        idCard: data.idCard,
                        sex: data.sex,
                        grade: data.grade,
                        ysm: data.ysm,
                    })
                    if (data.schools == undefined) {
                      this.treeModelValue = [];
                    }else{
                      this.treeModelValue = data.schools.split(",");
                    }
                    this.modifyForm.subName = data.substName;
                    this.modifyForm.roleId = data.roleid;
                    this.modifyForm.position = data.position;
                    this.modifyForm.parentId = "";
                    this.modifyForm.parentIds = "";
                    this.recordId = data.parentId;
                    this.changeSchool(data.schoolId);
                    this.changePosition(2);
                    this.$refs.tree2.setValue2(data.roleid);
                }, 500)
                getlistysm().then(res => {
                    if (res.state == "success") {
                        this.autoCompleteResult = res.data
                    }
                })
            },
            //提交表单
            createfunctionOk(){
                this.Formtable.validateFields(["account",'phone','name',"idCard", 'password', 'parentId', 'sex','schoolId', 'roleid','ysm'], {force: true}, (err, values)=>{
                    if (!err){
                        this.modifyForm.account=values.account
                        this.modifyForm.phone=values.phone
                        this.modifyForm.name=values.name
                        this.modifyForm.idCard=values.idCard
                        this.modifyForm.sex=values.sex
                        this.modifyForm.ysm=values.ysm
                        this.modifyForm.password = values.password
                        const subNames = [];
                        const schools = [];
                        out : for(let i = 0; i < this.treeModelValue.length; ++i) {
                          for(let j = 0; j < this.subNames.length; ++j) {
                              if (this.treeModelValue[i] == this.subNames[j].value) {
                                subNames.push(this.subNames[j].value);
                                continue out;
                              }
                          }
                          schools.push(this.treeModelValue[i]);
                        }
                        if(this.modifyForm.parentId == undefined){
                          this.modifyForm.parentId = ''
                          this.modifyForm.parentIds = ''
                        }else{
                          this.xzUserList.forEach((key) => {
                            if(this.modifyForm.parentId == key.id){
                              if(this.modifyForm.position == '楼长'){
                                this.modifyForm.parentIds = key.id + ',';
                              }else{
                                this.modifyForm.parentIds = key.parentIds + key.id + ',';
                              }
                            }
                          })
                        }

                        this.modifyForm.subNames = subNames;
                        this.modifyForm.schools = schools;
                        if(this.modifyForm.idCard.length != 18){
                            this.$message.error( '身份证不合法', 5);
                            return null;
                        }
                        if(this.modifyForm.roleId == null || this.modifyForm.roleId == ''){
                            this.$message.error( '角色不能为空', 5);
                            return null;
                        }

                        if(this.modifyForm.roleId.substring(0,2) == '0,'){
                            // 剔除 '0,'
                            this.modifyForm.roleId = this.modifyForm.roleId.substring(2);
                        }

                        //修改数据
                        modify(this.modifyForm).then(res=>{
                            if (res.state=="success") {
                                this.$message.success(res.data ? res.data : '修改成功！', 5);
                                this.search();
                                this.modifyvisible = false;
                                return null;
                            }
                            this.$message.error(res.data ? res.data : '修改失败！', 5);
                        })
                    }

                })
            },
            createfunctionCancel(){
                this.modifyvisible=false
                this.autoCompleteResult=[]
                this.Formtable.setFieldsValue({
                    account: '',
                    phone: '',
                    name: '',
                    idCard: '',
                    sex: '',
                    grade: '',
                    password: '',
                    repassword: '',
                    schoolId: '',
                    parentId: '',
                    ysm: '',
                })
                this.treeModelValue = [];
                this.addForm.subName = '';
                this.addForm.position = '';
                this.addForm.parentIds = '';

            },
            openAddUser() {
                this.titleName = "新增"
                this.addUser = true;
                setTimeout(()=>{
                    this.addFormtable.setFieldsValue({
                        account: '',
                        phone: '',
                        name: '',
                        idCard: '',
                        sex: '',
                        grade: '',
                        password: '',
                        schoolId: '',
                        parentId: '',
                        ysm: '',
                    })

                    this.addForm.subName = '';
                    this.addForm.position = '';
                    this.addForm.parentIds = '';
                    getlistysm().then(res => {
                        if (res.state == "success") {
                            this.autoCompleteResult = res.data
                        }
                    })
                },0)
            },
            createOk(){
                this.addFormtable.validateFields(["account", 'phone', "name", "idCard", "sex", 'grade',"password",'schoolId','role','position','parentId','ysm'], {force: true}, (err, values)=>{
                    if (!err){
                        this.addForm.account=values.account
                        this.addForm.phone=values.phone
                        this.addForm.name=values.name
                        this.addForm.idCard=values.idCard
                        this.addForm.sex=values.sex
                        this.addForm.grade=values.grade
                        this.addForm.password=values.password
                        this.addForm.schoolId=values.schoolId
                        this.addForm.postion=values.position
                        this.addForm.parentId=values.parentId
                        this.addForm.ysm=values.ysm

                        this.addForm.substName=""

                        const subNames = [];
                        const schools = [];
                        out : for(let i = 0; i < this.treeModelValue.length; ++i) {
                          for(let j = 0; j < this.subNames.length; ++j) {
                            if (this.treeModelValue[i] == this.subNames[j].value) {
                              subNames.push(this.subNames[j].value);
                              continue out;
                            }
                          }
                          schools.push(this.treeModelValue);
                        }

                        this.modifyForm.subNames = subNames;
                        this.modifyForm.schools = schools;
                        if(this.addForm.idCard.length != 18){
                            this.$message.error( '身份证不合法', 5);
                            return null;
                        }
                        if(this.addForm.password.length <= 8){
                            this.$message.error( '密码长度必须大于8', 5);
                            return null;
                        }

                        if(this.addForm.roleId == null || this.addForm.roleId == ''){
                            this.$message.error( '角色不能为空', 5);
                            return null;
                        }

                        if(this.addForm.parentId == undefined){
                            this.addForm.parentId = ''
                            this.addForm.parentIds = ''
                        }else{
                            this.xzUserList.forEach((key) => {
                                if(this.addForm.parentId == key.id){
                                    if(this.addForm.position == '楼长'){
                                        this.addForm.parentIds = key.id + ',';
                                    }else{
                                        this.addForm.parentIds = key.parentIds + key.id + ',';
                                    }
                                }
                            })
                        }

                        if(this.addForm.roleId.substring(0,2) == '0,'){
                            // 剔除 '0,'
                            this.addForm.roleId = this.addForm.roleId.substring(2);
                        }
                        //修改数据
                        addPartner(this.addForm).then(res=>{
                            if (res.state=="success") {
                                this.$message.success(res.data ? res.data : '修改成功！', 5);
                                this.search();
                                this.addUser = false;
                                return null;
                            }
                            this.$message.error(res.msg ? res.msg : '修改失败！', 5);
                        })
                    }
                })
            },
            // TODO 生成二维码
            qrcodeImg(qWidth, qHeight, qText, id) {
              let qrcode = new QRCode(id, {
                width: qWidth,
                height: qHeight,
                text: qText,
              });
            },
            newQrcodeImg(data){
              let link = this.qrcodeLink + this.modifyFormFXY.id + "&sell=" + data;
              let id = this.qrcode + data;
              let that = this;
              that.$nextTick(function() {
                  setTimeout(() => {
                    that.qrcodeImg(124, 124, link,id);
                  });
              });
            },
            removeInnerHTML(){
              let qrcodeLen = this.$refs.qrcode.length
              if(qrcodeLen>0){
                let i=0;
                for (i=0;i<qrcodeLen;i++){
                  this.$refs.qrcode[i].innerHTML = "";
                }
              }
            },
            // TODO 调整分销员
            modifyFXY(data) {
              this.titleName = "分销员配置";
              this.modifyFormFXY.id = data.id;
              this.modifyFormFXY.name = data.name;
              this.modifyFormFXY.fxs = data.fxs
              this.fxyList = data.fxs==""?[]:data.fxs.split(",");
              if(this.fxyList.length != ""){
                this.newQrcodeImg(this.fxyList[0]);
              }
              this.modifyvisibleFXY = true;
            },
            handleTabsAdd(){
              if(this.fxyList.length>=5){
                  this.$message.info("分销商不得超过5个",2);
                  return;
              }
              let i=1;
              for (i=1;i<=5;i++){
                let srt = this.fxyList.toString();
                if(srt.indexOf(i.toString()) == -1){
                  this.fxyList.push(i);
                  this.removeInnerHTML();
                  this.newQrcodeImg(i);
                  break;
                }
              }
              this.$refs.tabs.activeKey = i;
              this.setFxyList()
            },
            handleTabClick(name){
              this.$refs.tabs.activeKey = name;
              this.removeInnerHTML();
              this.newQrcodeImg(name);
            },

            handleTabRemove(){
              let index = this.fxyList.indexOf(this.$refs.tabs.activeKey);
              this.fxyList.splice(index,1);
              this.$refs.tabs.activeKey = this.fxyList[0];
              this.setFxyList()
            },
            setFxyList(){
              pushFxyList({id:this.modifyFormFXY.id,fxy:this.fxyList.sort().toString()}).then(res =>{
                if (res.state == 'success') {
                  this.$message.success("分销商更新成功",2);
                }
              });
            },
            createFXYOk(){
              this.modifyvisibleFXY = false;
              this.search();
              this.removeInnerHTML();
            },
            createCancel(){
                this.removeInnerHTML();
                this.addUser=false;
                this.addFormtable.setFieldsValue({
                    account: '',
                    phone: '',
                    name: '',
                    idCard: '',
                    sex: '',
                    grade: '',
                    password: '',
                    repassword: '',
                    schoolId: '',
                    parentId: '',
                    ysm: '',
                })
                this.treeModelValue = [];
                this.addForm.subName = '';
                this.addForm.position = '';
                this.addForm.parentIds = '';
                this.titleName = '';
                this.modifyvisibleFXY = false;
                this.modifyFormFXY.id = "";
                this.modifyFormFXY.name = "";
                this.modifyFormFXY.fxs = "";
            },
            contentSelectCheck1(data){
                let list = data.list;
                let textlist = new Array();
                let pObj = {};
                list.forEach(element => {

                    if(element !== undefined){
                        if(!pObj[element.pId]){
                            pObj[element.pId] = {len:element.plen,list:[element.id]}
                        }else{
                            pObj[element.pId].list.push(element.id)
                        }
                    }
                });
                for (let name in pObj) {
                    if(pObj[name].len === pObj[name].list.length){
                        textlist.push(name)
                        textlist = [...textlist,...pObj[name].list];
                    }else{
                        textlist = [...textlist,...pObj[name].list];
                    }
                }
                this.addForm.roleId = textlist.join(",");
            },
            contentSelectCheck2(data){
                let list = data.list;
                let textlist = new Array();
                let pObj = {};
                list.forEach(element => {
                    /*if(element.plist){
                      element.plist.forEach(item2 =>{
                        textlist.push(item2);
                      })
                    }*/
                    if(!pObj[element.pId]){
                        pObj[element.pId] = {len:element.plen,list:[element.id]}
                    }else{
                        pObj[element.pId].list.push(element.id)
                    }
                    //textlist.push(element.id);
                });
                for (let name in pObj) {
                    if(pObj[name].len === pObj[name].list.length){
                        textlist.push(name)
                        textlist = [...textlist,...pObj[name].list];
                    }else{
                        textlist = [...textlist,...pObj[name].list];
                    }
                }
                this.modifyForm.roleId = textlist.join(",");
            },
            changeSubst(type){
                let schoolParams = {};
                if(type == 1){
                    schoolParams.substName = this.addForm.subName;
                    this.schoolList = [];
                }else if(type == 3){
                    schoolParams.substName = this.queryParam.substName;
                    this.schoolListParam = [];
                }else{
                    schoolParams.substName = this.modifyForm.subName;
                    this.schoolList = [];
                }


                getSchoolList(schoolParams).then(res => {
                    if (res.state == 'success') {
                        res.data.forEach((key) => {
                            if(type == 3){
                                this.schoolListParam.push(key)
                            }else{
                                this.schoolList.push(key)
                            }

                        })
                    }
                })
            },
            changeSchool(schoolId){
                let schoolParams = {};
                schoolParams.substName = this.modifyForm.subName;
                this.schoolList = [];

                getSchoolList(schoolParams).then(res => {
                    if (res.state == 'success') {
                        res.data.forEach((key) => {
                            this.schoolList.push(key)
                        })

                        this.modifyForm.schoolId = schoolId;
                    }
                })
            },
            changePosition(type){
                let params = {};
                if(type == 1){
                    params.position = this.addForm.position;
                }else{
                    params.position = this.modifyForm.position;
                }

                this.addForm.parentIds = '';
                if(params.position != '' && params.position != '总经理'){
                    this.leaderDisplay = '';
                    if(params.position == '楼长'){
                        params.position = '总经理'
                    }else{
                        params.position = '楼长'
                    }

                    this.xzUserList = [];
                    getXzUserList(params).then(res => {
                        if (res.state == 'success') {
                            this.keyRecord = ''
                            res.data.forEach((key) => {
                                this.xzUserList.push(key)
                            })

                            if(type == 1){
                                this.addForm.parentId = '';
                            }else{
                                if(this.recordId != ''){
                                    this.modifyForm.parentId = this.recordId;
                                }
                            }

                        }
                    })
                }else {
                    this.leaderDisplay = 'display:none';
                    this.addForm.parentId = '';
                    this.modifyForm.parentId = '';
                }
            },
            changeDongjie(event,id){
              if(event){
                unlockUser({userId:id}).then(res =>{
                  if(res.state == 'success'){
                    notification.success({ message: '系统提示', description: '解冻成功'})
                  }else{
                    notification.error({ message: '系统提示', description: '解冻失败'})
                  }
                });
              }else{
                lockUser({userId:id}).then(res =>{
                  if(res.state == 'success'){
                    notification.success({ message: '系统提示', description: '冻结成功'})
                  }else{
                    notification.error({ message: '系统提示', description: '冻结失败'})
                  }
                });
              }

            },
            exportList() {
                exportFile(exportUserList(this.queryParam),'用户清单.xlsx');
            },
            deleteUser(id){
                let params = {};
                params.id = id;
                deleteUser(params).then(res => {
                    if(res.state == 'success'){
                        this.$message.info("删除成功",2);
                    }else{
                        this.$message.info("删除失败",2);
                    }
                })
            },
            getSchoolNames() {
                this.queryParam.school = ''
                this.schoolNames = []
                getSchoolNames({"substName": this.queryParam.substName}).then((res) => {
                    if (res.state == "success") {
                        const result = res.data
                        result.forEach((r) => {
                            if (r.schoolName === 'null')
                                return;
                            this.schoolNames.push({
                                value: r.id,
                                text: r.schoolName
                            })
                        })
                    }
                })
            },
            initSubstName() {
                initSubstName().then((res) => {
                    if (res.state == "success") {
                        const result = res.data
                        result.forEach((r) => {
                            if (r.subName === 'null')
                                return;
                            this.subNames.push({
                                value: r.subName,
                                text: r.subName
                            })
                            this.treeData.push({
                              title: r.subName,
                              value: r.subName,
                              key: r.subName
                            });
                        })

                      for (let i = 0;i < this.treeData.length; ++i) {
                        getSchoolNames({"substName": this.treeData[i].value}).then((res) => {
                          if (res.state == "success") {
                            const temp = [];
                            const result = res.data
                            result.forEach((r) => {
                              if (r.schoolName === 'null')
                                return;
                              temp.push({
                                key: r.id,
                                value: r.id,
                                title: r.schoolName
                              });
                            })
                            this.treeData[i].children = temp;
                          }
                        })
                      }
                    }
                })
            },
          /*
          newImage : function() {
            // 生成图片
            var imageBox = document.getElementById("imageBox")
            var canvas = document.getElementById("canvas")
            var cxt = canvas.getContext("2d")
            canvas.width = document.getElementById("imageBox").clientWidth;
            canvas.height = document.getElementById("imageBox").clientHeight;

            //背景图
            var img = new Image()
            img.src = require('../../../assets/picture/hhr/qrcode.png');
            img.setAttribute("crossOrigin", 'Anonymous')
            img.onload = () => {
              // 图片加载完成，才可处理
              // 画图(这里画布与图片等宽高)
              cxt.drawImage(img, 0, 0, canvas.width, canvas.height);

              cxt.drawImage(this.img2,  canvas.width*0.23, canvas.height*0.64);

              //绘制完成,转为图片
              setTimeout(function() { //在ios上无法在画完之后取到整个画布内容，加了个settimeout
                let images = new Image();
                images.src = canvas.toDataURL("image/png");
                images.setAttribute("crossOrigin", 'Anonymous')
                $('.canimg').attr('src', canvas.toDataURL("image/png"))
                this.showBox = false;
              }, 0)
            }

          },
          convertCanvasToImage: function () {
            let qrcode = document.getElementsByTagName("canvas")[0];
            let img2 = new Image();
            img2.src = qrcode.toDataURL("image/png");
            this.img2 = img2;
          }
          */
        },
        mounted() {
            this.initSubstName();
            this.getSchoolNames();
        }
    }
</script>

<style scoped>
.demo-badge-alone{
  background: #5cb85c !important;
  size: 10px;
}
</style>
