<template>
  <a-modal v-model="visible"  title="选择编辑"  width="1200px" class="edit-dialog" >
    <template slot="footer">
      <a-button key="back" @click="handleCancel">
        取消
      </a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="handleOk">
        确认
      </a-button>
    </template>
    <div class="dialog-content">
      <div class="left">
        <div class="header">
          <div class="select">
            <Select style="margin: 0 10px"
                    v-model="majorId"
                    @change="handleMajor"
                    :hideClear='true'
                    :selectdata="majorList"
                    :placeholder="'请选择'"
                    class="search-select"
                    width="236"
            />
          </div>
          <div class="search">
            <Select
                v-model="floorId"
                caption="所属楼层："
                @change="chageFloor"
                :hideClear='false'
                :selectdata="dataFloor"
                :placeholder="'请选择'"
                class="search-select"
                width="236"
            />
            <a-input-search placeholder="搜索" class="press-enter" @search="onSearch" v-model="keyword"/>

          </div>
        </div>
        <div class="tree">
          <searchTree  @getTreeId="getTreeId" :treeData="treeData"/>
        </div>
        <div class="checkbox">
          <a-table :pagination="false" :row-key='typeEdit=="Zone"?"location":"assetnum"' :columns="typeEdit=='Image'?columnsSys:columnsLocal" :data-source="tableData"  :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange,onSelect:onSelect }" :scroll="{ y: 340 }"  :loading="loading"/>
          <a-pagination v-if="total>0" v-model="page" :total="total" show-less-items style="margin-left: auto;"  @change="handleTableChange"/>
        </div>
      </div>
      <div class="right">
        <div class="header">
          <span class="select-number">已选择 <b>{{arrList.length}}</b>/{{sysNum}}</span>
          <a-button type="link" class="link" @click="clearArrList">清空</a-button>
        </div>

        <div class="list-box">
          <p v-for="(item,index) in arrList" :key="index" class="list">{{item.sbjc||item.wzjc}}
            <a-icon type="close" class="icon" @click="deleteItem(item,index)"/>
          </p>
        </div>

      </div>
    </div>
  </a-modal>
</template>

<script>
    import searchTree from "@/components/edit/search_tree";
    import {queryGlsmsasset ,getQuerySmsxt,getPlazaFloor,getQuerySmsxtBy,queryWzfldl,queryWzflByDl,queryGlsmsLocation} from "@/api/editer";
    import bus from "@/bus";
    import {getUrlMsg}  from '@/components/urlMsg.js'

    export default {
        name: "edit-dialog",
        components: {searchTree},
      props:{
        typeEdit:String , //用于区分是设备 还是  位置
        getmajorId:String, //专业Id
        sysNum:Number ,//设备总数
        attrCards:Array
      },
        data() {
            return {
                loading: false,
                visible: false,
                model: 'test1',
                searchName: '',
                floorId:"",//所属楼层
                dataFloor: [],
                plainOptions: ['福建三明万达-供电系统-6楼-工程信息化中的区域编码ND182472e83742', '福建三明万达-供电系统-6楼-工程信息化中的区域编码ND18247283742'],
                majorList: [],
                checkedList: [],
              keyword:'',
              classstructureid:'',
              locfl:'',
              columnsSys : [
                {
                  title: '设备名称',
                  dataIndex: 'sbjc',
                  key: 'sbjc',
                  width: '75%',
                  scopedSlots: { customRender: 'sbjc' },
                },
                {
                  title: '设备内码',
                  dataIndex: 'sbjbm',
                  key: 'sbjbm',
                  width: '25%',
                },
              ],
              columnsLocal : [
                {
                  title: '位置名称',
                  dataIndex: 'wzjc',
                  key: 'wzjc',
                  width: '75%',
                  scopedSlots: { customRender: 'wzjc' },
                },
                {
                  title: '位置内码',
                  dataIndex: 'location',
                  key: 'location',
                  width: '25%',
                },
              ],
              tableData:[],
              loading:false,
              page:1,
              size:10,
              treeData:[],
              total:0,
              selectedRowKeys :[],
              arrList:[]
            }
        },
        computed:{
          majorId(){
            return this.typeEdit=='Zone'?'位置区域': this.getmajorId
          },
        },
      watch:{
        floorId(val){
          if(val==''){
            this.queryGlsmsasset();
          }
        }
      },
        methods: {
            showModal() {
                this.visible = true;
            },
            handleOk(e) {
                this.loading = true;
                setTimeout(() => {
                    this.visible = false;
                    this.loading = false;
                    const lists = [];
                    let arr = [];
                    arr = JSON.parse(JSON.stringify( this.arrList))
                  arr.map(item =>{
                      lists.push({id:item.location||item.assetnum,name:item.wzjc||item.sbjc})
                    })
                    bus.$emit('changeAttachObjectIds',lists)
                    bus.$emit('updateAttachMsg',lists)
                }, 3000);
            },
            handleCancel(e) {
                this.visible = false;
            },
            onSearch(value) {
                this.queryGlsmsasset()
            },
            ChangeCheckbox(val) {
                console.log(val)
            },
            handleMajor(val) {
              this.tableData = [];
              this.getQuerySmsxtBy(val.id)
            },
            chageFloor(data) {
              this.queryGlsmsasset();
            },
            pressEnter(e) {
                console.log(e)
            },
            //获取treeId --classstructureid
            getTreeId(id) {
              if(this.typeEdit=='Image'){
                this.classstructureid = id;
              }else if(this.typeEdit=='Zone'){
                this.locfl = id;
              }

             this.queryGlsmsasset();
            },
          //获取表格数据
          queryGlsmsasset(){
            const data = {
              plazaId: getUrlMsg().projectId,//广场id 必填
              page: this.page,//页数
              size: this.size,//条数
            }
            if( this.keyword){
              data.keyword = this.typeEdit=='Image'? `${this.keyword}:brand`:`${this.keyword}:wzjc`
            }
            const paramData =  {classstructureid: this.classstructureid,gname:this.floorId};
            const paramDataLocal =  {locfl: this.locfl,gname:this.floorId};
            this.loading = true;
            if(this.typeEdit=='Image'){
              queryGlsmsasset(data,paramData).then(res => {
                this.loading = false;
                if(res.data.result == 'success'){
                  this.total = res.data.count;
                  if(res.data.data){
                    const data = res.data.data;
                    data.map(item=>{
                      item.id = item.sbjbm
                    })
                    this.tableData = data;

                  }else if(res.data.count == 0){
                    this.tableData = [];
                  }
                }else{
                  this.$message.error('数据请求失败')
                }
              })
            }else if(this.typeEdit=='Zone'){
              queryGlsmsLocation(data,paramDataLocal).then(res => {
                this.loading = false;
                if(res.data.result == 'success'){
                  this.total = res.data.count;
                  if(res.data.data){
                    this.tableData = res.data.data;
                  }else if(res.data.count == 0){
                    this.tableData = [];
                  }
                }else{
                  this.$message.error('数据请求失败')
                }
              })
            }

          },
          //分页切换点击
          handleTableChange(page, pageSize) {
            this.page = page;
            this.queryGlsmsasset();
          },
          onSelect(record, selected, selectedRows, nativeEvent){
            if(!selected  && this.arrList.length>0){
              this.arrList.map((item,index)=>{
                if(this.typeEdit=='Zone'&& item.location == record.location ){
                  this.arrList.splice(index,1);
                }else if(this.typeEdit=='Image'&& item.assetnum == record.assetnum ){
                  this.arrList.splice(index,1);
                }
              })
            }
          },
          // 中间表格勾选
          onSelectChange(selectedRowKeys,selectedRows) {
            this.selectedRowKeys = selectedRowKeys;
              if(this.selectedRowKeys.length>this.sysNum){
                this.selectedRowKeys.pop();
                this.$message.error('不能超过设备数')
                return false;
              }
            this.arrList = [...this.arrList,...selectedRows]
            const obj = {}
            if(this.typeEdit=='Zone'){
              this.arrList = this.arrList.reduce (function(item,next){
                obj[next.location] ? ' ' : obj[next.location]  = true && item.push(next)

                return item;

              },[])
            }else{
              this.arrList = this.arrList.reduce (function(item,next){
                obj[next.assetnum] ? ' ' : obj[next.assetnum]  = true && item.push(next)

                return item;

              },[])
            }

          },
          //右侧删除
          deleteItem(item,index){
            this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(item.location||item.assetnum),1);
            this.arrList.splice(index,1);
          },
          //右侧清空
          clearArrList(){
            this.selectedRowKeys = [];
            this.arrList = [];
          },
          //获取楼层
          getPlazaFloor(){
              const data = {
                plazaId:getUrlMsg().projectId
              }
            getPlazaFloor(data).then(res =>{
              if(res.result == 'success'){
                const data = res.data;
                data.map(item=>{
                  item.id = item.gname;
                })
                this.dataFloor  = data;
              }
            })
          },
          //获取设备大类和位置大类
          getQuerySmsxt(){
              if (this.typeEdit=='Image'){
                getQuerySmsxt({}).then(res =>{
                  if(res.result == 'success'){
                    if(res.data){
                      const data = res.data;
                      data.map(item=>{
                        item.id = item.code;
                        item.name = item.name;
                      })
                      this.majorList  = data;
                    }
                  }
                })
              }else if(this.typeEdit =='Zone'){

                queryWzfldl({}).then(res =>{
                if(res.result == 'success'){
                  if(res.data){
                    const data = res.data;
                    data.map(item=>{
                      item.id = item.dl;
                      item.name = item.dl;
                    })
                    this.majorList  = data;
                  }
                }
              })
            }

          },
         // 获取设备大类下的分类和位置大类下的分类
          getQuerySmsxtBy(smsxt){
              if(this.typeEdit=='Image'){
              const data = {
                smsxt:smsxt
              }
              getQuerySmsxtBy(data,{}).then(res =>{
                if(res.result == 'success') {
                  if(res.data){
                    const data = res.data;
                    (function recursion(newObj) {
                      newObj.map(item=>{
                        item.label = item.gcxxhxtname || item.classqc;
                        item.id = item.gcxxhxtnum || item.id;
                        item.children = item.data;
                        if(item.children){
                          recursion(item.children);
                        }
                      })
                    })(data)

                    this.treeData = data;
                  }
                }else{
                  this.$message.error('获取失败');
                }
              })
            }else if(this.typeEdit=='Zone'){
                const data = {
                  dl:smsxt
                }
                queryWzflByDl(data,{}).then(res =>{
                  if(res.result == 'success') {
                    if(res.data){
                      const data = res.data;
                      (function recursion(newObj) {
                        newObj.map(item=>{
                          item.label = item.name;
                          if(item.children){
                            recursion(item.children);
                          }
                        })
                      })(data)

                      this.treeData = data;
                    }
                  }else{
                    this.$message.error('获取失败');
                  }
                })
              }

          }
        },
        created() {
          if(this.attrCards.length){
            this.attrCards.map(item=>{
              this.selectedRowKeys.push(item.location||item.assetnum)
            })
            this.arrList = JSON.parse(JSON.stringify(this.attrCards));
          } else{
            this.selectedRowKeys = [];
          }
          this.getQuerySmsxt();
          //如果有专业就带过来
          this.getQuerySmsxtBy(this.majorId)
          this.getPlazaFloor();

        }
    }
</script>

<style scoped lang="less">
  .edit-dialog {
    .dialog-content {
      width: 1136px;
      height: 499px;
      background: rgba(255, 255, 255, 1);
      border-radius: 3px;
      border: 1px solid rgba(239, 240, 241, 1);
      display: flex;
      /*overflow: auto;*/

      .left {
        width: 785px;
        border-right: 1px solid #EFF0F1;

        .header {
          width: 785px;

          .select {
            width: 260px;
            border-right: 1px solid #EFF0F1;
            display: inline-block;
          }

          .search {
            width: 524px;
            display: inline-block;

            .search-select {
              margin-left: 10px;
              position: relative;
              top: -2px;
            }

            .press-enter {
              margin-left: 10px;
              width: 236px;
            }
          }


        }


        .tree {
          width: 259px;
          height: 441px;
          border-right: 1px solid #EFF0F1;
          display: inline-block;
          float: left;
          overflow-y: scroll;
          overflow:overlay;

        }

        .checkbox {
          /*margin-top: 17px;*/
          /*margin-left: 13px;*/
          width: 500px;
          height: 441px;
          display: inline-block;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          /deep/ .ant-table-selection-column {
            .ant-table-header-column{
              display: none;
            }
          }
        }
      }

      .right {
        flex-grow: 1;

        .list-box{
          height: 440px;
          overflow-y: scroll;
          .list {
            background: rgba(239, 240, 241, 1);
            border-radius: 2px;
            margin: 8px 12px;
            position: relative;
            padding: 5px;

            .icon {
              position: absolute;
              bottom: 5px;
              right: 5px;
              cursor: pointer;
            }
          }
        }



        .select-number {
          margin-left: 12px;

        }

        .link {
          float: right;
          line-height: 57px;
        }
      }

      .header {
        height: 57px;
        line-height: 57px;
        border-bottom: 1px solid #EFF0F1;
      }
    }

    /deep/ .ant-input-affix-wrapper .ant-input-suffix {
      /*left: 12px;*/
      /*padding-right: 12px;*/
    }

    /deep/ .ant-modal-footer {
      border: 0;
    }

    /deep/ .ant-checkbox-wrapper + .ant-checkbox-wrapper {
      margin: 0;
    }
  }
</style>