<template>
    <div class="flex-container">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <!-- 搜索区域 -->
            <a-form layout="inline">
                <a-row :gutter="24">
                    <a-col :md="6" :sm="12">
                        <a-form-item  label="配置名称">
                            <a-input  placeholder="配置名称"  v-model="queryParam.name" ></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="12">
                        <a-form-item  label="合伙人">
                            <a-input  placeholder="合伙人"  v-model="queryParam.hhrNames" ></a-input>
                        </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-divider type="vertical"/>
                            <a-button @click="modifyfunction()" type="primary">添加</a-button>
                        </a-col>
                    </span>
                </a-row>
            </a-form>
        </div>

        <!--列表-->
        <s-table :columns="columns" :data="rowdata" bordered ref="table" size="small" class="flex-filling"  :locale="emptyText">
            <!--拦截器-->
            <!--<template slot="hhrIds" slot-scope="text">
                <span v-for="id in text.split(',')">
                    <span v-for="item in userNames">
                        <span v-if="item.id == id">
                            <a>{{ item.name }}</a>,
                        </span>
                    </span>
                </span>
            </template>-->
            <template slot="operation" slot-scope="text,record">
                <span>
                  <a @click="modifyfunction(record)">编辑</a>
                  <a-divider type="vertical"/>
                  <a @click="remove(record.id)">删除</a>
                  <a-divider type="vertical"/>
                  <a @click="creatQrCode(record.id)">生成二维码</a>
                </span>
            </template>
        </s-table>
        <!----弹框-->
        <div class="qrcode"  ref="qrCodeUrl"></div>
        <a-modal title="" v-show="showCode" @ok="cancel" @cancel="cancel" width="324px">
        </a-modal>
        <!----弹框-->
        <a-modal :title="add ?'添加配置': '编辑配置'" :visible="modifyvisible"  @ok="createfunctionOk" @cancel="createfunctionCancel" html-type="submit" width="1024px">
            <a-form :form="Formtable">
                <a-form-item :labelCol="{span: 5}" :wrapperCol="{span: 9, offset: 1}" label="配置名称">
                    <a-input placeholder="配置名称" v-decorator="[ 'name', {rules: [{ required: true, message: 'name' ,validator: 'click'}]} ]"></a-input>
                </a-form-item>
                <a-form-item :labelCol="{span: 5}" :wrapperCol="{span: 9, offset: 1}" label="县分：">
                    <a-select v-decorator="['subName',{ validateTrigger: ['change', 'blur'] }]"
                              :maxTagCount="Number(1)"
                              :showArrow="true"
                              allowClear
                              placeholder="请选择县分"
                              style="width: 100%"
                              @change="handleChangeSite1">
                        <a-select-option :title="item.value" v-for="(item, index) in subNameList" :value="item.value" :key="item.value">{{item.value}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item :labelCol="{span: 5}" :wrapperCol="{span: 9, offset: 1}" label="学校：">
                    <a-select allowClear
                              :showArrow="true"
                              v-decorator="['schoolName']"
                              placeholder="请选择学校"
                              style="width: 100%"
                              @change="handleChangeSite2">

                        <a-select-option :title="item.schoolName" v-for="(item,index) in schoolList" :key="item.id" :value="item.schoolName">{{item.schoolName}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item :labelCol="{span: 5}" :wrapperCol="{span: 9, offset: 1}" label="学校：">
                    <a-select allowClear
                              :showArrow="true"
                              v-decorator="['hhrName']"
                              placeholder="请选择合伙人"
                              style="width: 100%"
                              @change="handleChangeSite3">

                        <a-select-option :title="item.userName" v-for="(item,index) in userList" :key="item.id" :value="item.userName">{{item.userName}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item :labelCol="{span: 5}" :wrapperCol="{span: 9, offset: 1}" label="已选预览：">
                    <div v-for="(item,index) in resultList" style="line-height: 1.2rem;">
                        {{item.name}}----{{item.subName}}----{{item.schoolName}}--{{item.hhrName}}
                    </div>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
    import STable from '@/components/table';
    import {deployList,getSchools,delDeploy,addOrUpdate,getHhrs} from "../../../api/school-center/other/userDeployApi"
    import {cloneObject} from '@/utils/util';
    import {initSubstName} from "../../../api/school-center/louZhang/louZhangManagerAPI";
    import QRCode from 'qrcodejs2'

    export default {
        name: "userDeploy",
        components: {
            STable,
        },
        data(){
            return {
                params:{
                    id:'',
                    name:'',
                    hhrIds:'',
                    hhrNames:'',
                    subNames:'',
                    schoolNames:'',
                },
                emptyText: {emptyText: '暂无数据'},
                Formtable: this.$form.createForm(this, { name: 'search_form' }),
                subNameList: [],
                schoolList:[],
                userList: [],
                resultList : [],

                modifyvisible: false,
                showCode: false,
                add: true,
                clicks: 0,
                queryParam: {
                    name :'',
                    hhrNames:''
                },
                modelData:{
                    id: '',
                    name:'',
                    hhrId:'',
                    hhrName:'',
                    subName:'',
                    schoolName:'',
                },
                columns: [
                    {dataIndex: 'name', width:60, title: '配置名称'},
                    {dataIndex: 'hhrNames', width: 200, title: '合伙人'},
                    {
                        dataIndex: 'operation',
                        width: 100,
                        title: '操作',
                        scopedSlots: {customRender: 'operation'},
                        fixed: "right"
                    }]
                ,
                rowdata: parameter => {
                    let params = {
                        pageNo: parameter.pageNo,
                        pageSize: parameter.pageSize
                    }
                    let obj = cloneObject(this.queryParam)
                    //表示
                    return deployList(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
                    })
                }
            }
        },
        methods:{
            handleChangeSite1(value) {
                this.modelData.subName = value;
                this.$nextTick(() => {
                    //this.getUser(e,'')
                    this.getSub(value, true)
                })
            },
            getSub(params) {
                this.schoolList = [];
                getSchools({"subName": params}).then((res) => {
                    if (res.state == "success") {
                        const result = res.data
                        result.forEach((r) => {
                            if (r.schoolName === 'null')
                                return;
                            this.schoolList.push({
                                id: r.id,
                                schoolName: r.schoolName
                            })
                        })
                    }
                })

            },
            handleChangeSite2(value,str) {
                this.modelData.schoolName = value;
                this.$nextTick(() => {
                    //this.getUser(e,'')
                    this.getSchool(str.key)
                })
            },
            getSchool(params) {
                this.userList = [];
                getHhrs({"schoolId": params}).then((res) => {
                    if (res.state == "success") {
                        const result = res.data
                        if(result != null){
                            result.forEach((r) => {
                                if (r.name === 'null')
                                    return;
                                this.userList.push({
                                    id: r.id,
                                    userName: r.name,
                                })
                            })
                        }
                    }
                })
            },
            handleChangeSite3(value,str) {
                var name = this.params.name;
                var subName = this.modelData.subName;
                var schoolName = this.modelData.schoolName;
                var hhrId = str.key;
                var hhrName = value;
                var count = true;
                var count2 = true;
                if(name == this.params.name){
                    for (const i in this.resultList){
                        if(this.resultList[i].schoolName == schoolName){
                            this.resultList[i].hhrName = hhrName;
                            this.resultList[i].subName = subName;
                            this.resultList[i].schoolName = schoolName;
                            this.resultList[i].hhrId = hhrId;
                            count = false;
                            count2 = false;
                            break
                        }
                    }
                    if(count){
                        for (const i in this.resultList){
                            if(this.resultList[i].hhrId == hhrId) {
                                this.removeAaary(this.resultList,this.resultList[i])
                                count = false;
                                count = false;
                                count2 = false;
                                break;
                            }
                        }
                    }
                    if(count2){
                        this.resultList.push({
                            name:name,
                            subName:subName,
                            hhrId: hhrId+"",
                            hhrName:hhrName,
                            schoolName:schoolName,
                        })
                    }
                }else{
                    this.params.name = name;
                    this.resultList = [];
                    this.resultList.push({
                        name:name,
                        subName:subName,
                        hhrId: hhrId+"",
                        hhrName:hhrName,
                        schoolName:schoolName,
                    })
                }
                this.params.hhrIds = '';
                this.params.hhrNames = '';
                this.params.subNames = '';
                this.params.schoolNames = '';
                for (const i in this.resultList){
                    const item = this.resultList[i];
                    this.params.hhrIds += item.hhrId+",";
                    this.params.hhrNames += item.hhrName+",";
                    this.params.subNames += item.subName+",";
                    this.params.schoolNames += item.schoolName+",";
                }
            },
            initSubstName() {
                initSubstName().then((res) => {
                    if (res.state == "success") {
                        const result = res.data
                        result.forEach((r) => {
                            if (r.subName === 'null')
                                return;
                            this.subNameList.push({
                                value: r.subName,
                                text: r.subName
                            })
                        })
                    }
                })
            },
            handleChange(value) {
                console.log(`selected ${value}`);
            },
            search() {
                this.$refs.table.refresh({search: true})
            },
            remove(id) {
                delDeploy({'id':id}).then((res) => {
                    if(res.state=="success"){
                        this.$notification.success({message: res.data, description: '', duration: 4})
                    }
                    this.$refs.table.refresh({search: true})
                })
            },
            creatQrCode(id) {
                if(this.$refs.qrCodeUrl != undefined){
                    this.$refs.qrCodeUrl.innerHTML = ''
                }
                new QRCode(this.$refs.qrCodeUrl, {
                    text: 'http://192.168.3.4:2999/#/hhStu/chooseArea?partner='+id, // 需要转换为二维码的内容
                    width: 160,
                    height: 160,
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
                })
            },
            cancel(){
                this.showCode= false
            },
            modifyfunction(data){
                if(data != undefined ){
                    this.params.id=data.id
                    this.params.name = data.name
                    var objids = data.hhrIds.substring(0,data.hhrIds.length-1)
                    var uIds = objids.split(",");
                    var uNames = data.hhrNames.split(",");
                    var subs = data.subNames.split(",");
                    var schs = data.schoolNames.split(",");
                    setTimeout(()=>{
                        this.Formtable.setFieldsValue({
                            "name":data.name
                        })
                    },0)
                    this.add=false;
                    let htmlttt = "";
                    var userIdttt = "";
                    var hhrNamettt="";
                    var subNamettt="";
                    var schoolNamettt="";
                    for (const i in uIds){
                        this.resultList.push({
                            name: data.name,
                            subName: subs[i],
                            hhrId: uIds[i]+"",
                            hhrName: uNames[i],
                            schoolName: schs[i],
                        })
                        userIdttt += uIds[i]+",";
                        hhrNamettt += uNames[i]+",";
                        subNamettt += subs[i]+",";
                        schoolNamettt += schs[i]+",";
                    }
                    this.params.hhrIds = userIdttt;
                    this.params.hhrNames = hhrNamettt;
                    this.params.subNames = subNamettt;
                    this.params.schoolNames = schoolNamettt;
                }
                this.modifyvisible=true;
            },
            createfunctionOk(){
                let that = this;
                that.Formtable.validateFields(['name','subName','schoolName','hhrName'], {force: true}, (err, values) => {
                    if (err ) {
                        return;
                    }
                    if (values.name==undefined) {
                        this.$message.error("配置名称不能为空！！！", 10);
                        return;
                    }
                    if (values.subName==undefined) {
                        this.$message.error("请选择县分！！！", 10);
                        return;
                    }if (values.schoolName==undefined) {
                        this.$message.error("请选择学校！！！", 10);
                        return;
                    }if (values.hhrName==undefined) {
                        this.$message.error("请选择合伙人！！！", 10);
                        return;
                    }
                    let obj = this.params;
                    if(this.add){
                        delete obj.id
                        let  userDeploy= JSON.stringify(obj);
                        addOrUpdate({userDeploy}).then((res) => {
                            this.modifyvisible=false;
                            this.clearmodel()
                            if(res.state=="success"){
                                this.$notification.success({message: res.data, description: '', duration: 4})
                            }
                            this.search()
                        })
                    }else {
                        let  userDeploy= JSON.stringify(obj);
                        addOrUpdate({userDeploy}).then((res) => {
                            this.modifyvisible=false;
                            this.clearmodel()
                            if(res.state=="success"){
                                this.$notification.success({message: res.data, description: '', duration: 4})
                            }
                            this.search()
                        })
                    }

                })
            },
            createfunctionCancel(){
                this.modifyvisible=false;
                this.clearmodel()
                this.add=true;
            },
            //清除弹窗信息
            clearmodel() {
                this.resultList = []
                this.schoolList = [];
                this.userList = [];
                this.add=true
                this.params.id=''
            },
            removeAaary(_arr, _obj) {
                var length = _arr.length;
                for (var i = 0; i < length; i++) {
                    if (_arr[i] == _obj) {
                        if (i == 0) {
                            _arr.shift(); //删除并返回数组的第一个元素
                            return _arr;
                        }
                        else if (i == length - 1) {
                            _arr.pop();  //删除并返回数组的最后一个元素
                            return _arr;
                        }
                        else {
                            _arr.splice(i, 1); //删除下标为i的元素
                            return _arr;
                        }
                    }
                }
            }
        },
        mounted() {
            this.initSubstName();
        },

    }
</script>

<style scoped>
    .qrcode{
        display: inline-block;
        img {
            width: 180px;
            height: 180px;
            background-color: #fff; /*设置白色背景色*/
            padding: 16px;  /*利用padding的特性，挤出白边*/
            box-sizing: border-box;
        }
    }

</style>