<template>
  <div class="box-center">
    <!-- 头 -->
    <div class="app-top">
      <div class="app-titel" style="margin-top: 5px">
        <div class="label" v-if="orgType!=3">楼盘名称：</div>
        <div style="width: 200px" v-if="orgType!=3">
          <el-select
            v-model="houseid"
            @change="houseChange"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in houseList"
              :key="item.id"
              :label="item.propertyName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
        <div class="label">顾问名：</div>
        <div>
          <el-input v-model="name"></el-input>
        </div>
        <div class="label">工作状态：</div>
        <div>
          <el-select v-model="stateoptseid" placeholder="请选择">
            <el-option
              v-for="item in stateoptse"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div class="label">排班状态：</div>
        <div>
          <el-select v-model="schedulingoptseid" placeholder="请选择">
            <el-option
              v-for="item in schedulingoptse"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="app-titel" style="margin-top: 15px">
        <!-- <div class="label" style="color: #ffffff">筛选相关：</div> -->
        <div style="margin-left: 20px">
          <el-button style="background: #2671e2; color: #ffffff"
            @click="screening()">筛选</el-button
          >
        </div>
        <div style="margin-left: 20px">
          <el-button @click="reset()">清空筛选条件</el-button>
        </div>
        <div style="margin-left: 20px">
          <el-button style="background: #2671e2; color: #ffffff"
           @click="addinfo()" >添加</el-button
          >
        </div>
        <div style="margin-left: 20px">
          <el-button style="background: #2671e2; color: #ffffff"
           @click="alldel()" >批量删除</el-button
          >
        </div>
        <div style="margin-left: 20px">
          <el-button style="background: #2671e2; color: #ffffff"
            >批量排班</el-button
          >
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <div class="cen-tab">
      <el-table
        :data="tableData"
        stripe
        height="400"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="name" label="顾问名" align="center">
        </el-table-column>
        <el-table-column prop="name" label="状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">空闲</span>
            <span v-if="scope.row.status == 1">接待中</span>
            <span v-if="scope.row.status == 2">暂停接待</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="上次接待结束时间"
          align="center"
        >
        </el-table-column>

        <el-table-column prop="date" label="有无排班" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.hasSchedule == 1">有排班</span>
            <span v-if="scope.row.hasSchedule == 0">无排班</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <span style="color: #2671e2" @click="switchstatus(scope.row,2)" v-if="scope.row.status == 0">暂停接待</span>
            <span style="color: #2671e2" @click="switchstatus(scope.row,0)" v-if="scope.row.status == 2">空闲</span>
            <span style="color: #2671e2; margin-left: 10px">工作安排</span>
            <span style="color: #2671e2; margin-left: 10px" @click="del(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage4"
          :page-sizes="[6, 12, 18, 24]"
          :page-size="6"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog title="新增" :visible.sync="dialogVisible">
      <div>
         <div style="text-align: center;">
            <el-transfer
              ref="transfer" id="transfer"
              style="text-align: left; display: inline-block;height:400px;"
              v-model="transfervalue"
              :titles="['无排班', '排班']"
              :button-texts="['删除', '添加']"
              @change="handleChange"
              :data="transferdata">
              <span slot-scope="{ option }" :draggable="!option.disabled"   @dragstart="drag($event,option)">{{ option.label }}</span>
            </el-transfer>
          </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editor()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
export default {
  data() {
    const generateData = _ => {
        const data = [];
        for (let i = 1; i <= 15; i++) {
          data.push({
            key: i,
            label: `备选项 ${ i }`
          });
        }
        return data;
    };
    return {
      transferdata: generateData(),
      draggingKey : null,
      transfervalue: [],
      multipleSelection: [],
      orgType:localStorage.getItem("orgType"),
      dialogVisible: false,
      currentPage4: 1,
      tableData: [],
      houseList: [],
      houseid: "",
      name: "",
      stateoptse: [
        { label: "空闲", value: 0 },
        { label: "接待中", value: 1 },
        { label: "暂停接待", value: 2 },
      ],
      stateoptseid: "",
      schedulingoptse: [
        { label: "无排班", value: 0 },
        { label: "有排班", value: 1 },
      ],
      schedulingoptseid: "",
      Page: 1,
      size: 6,
      total: 0,
    };
  },
  mounted() {

    this.getHouse();
  },
  methods: {
    switchstatus(row,i){
       let obj = {
        agentId: row.agentId,
        status:i
      };
        this.$confirm(i==0?'修改为空闲, 是否继续?':'修改为暂停接待, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          distinguishCancelAndClose: true,
          type: 'warning'
        }).then(() => {
            this.$api.http.agentListupdate(obj).then((res) => {
                 if(res.code==0){
                     this.$message({
                      type: 'success',
                      message: '修改成功!'
                    });
                     this.reset()
                 }else{
                    this.$message.error(res.message);
                 }
            })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消修改'
              });
        });
    },



    drag(ev,option) {
　　　　this.draggingKey = option.key;
    },
     handleChange(value, direction, movedKeys) {
        console.log(value, direction, movedKeys);
      },
    addinfo() {
       this.agentListSort()
       this.dialogVisible = true;

        const secounds = 2;
        let num = 0
        const timer = setInterval(() => {
          if(num < secounds) {
            num++
          }else {
            clearInterval(timer)
               this.inif()
          }
        }, 500)// 这里的时间不要忘记，否则没有效果
    },
    inif(){
      const transfer = this.$refs.transfer.$el
        const leftPanel = transfer.getElementsByClassName("el-transfer-panel")[0].getElementsByClassName("el-transfer-panel__body")[0];
        const rightPanel = transfer.getElementsByClassName("el-transfer-panel")[1].getElementsByClassName("el-transfer-panel__body")[0];
        const rightEl = rightPanel.getElementsByClassName("el-transfer-panel__list")[0]
        Sortable.create(rightEl, {
          animation: 100,
          onEnd: (evt) => {
            const { oldIndex, newIndex } = evt
            const temp = this.transfervalue[oldIndex]
            if (!temp || temp === 'undefined') {
              return
            }// 解决右边最后一项从右边拖左边，有undefined的问题
    　　//这里和网上的有点不一样,网上搜到的结果排序是,当前拖拽的元素和拖拽位置的元素互换位置,但是实际上在使用el-transfer有两个问题
    　　//1.右侧排序value的数组顺序来源于后台穿的数组顺序,实际如果不设置target-order="unshift"的话,展示会按照左侧的数据列顺序展示,导致拖拽排序时顺序乱七八糟
    　　//2.实际拖拽排序看到的效果是当前拖拽元素拖拽到其他地方,其他地方的元素会下移,而不是调换顺序
            // 去除空字符串
            // for (var i = 0; i < this.transfervalue.length; i++) {
            //   if (this.transfervalue[i] == '' || this.transfervalue[i] == null || typeof (this.transfervalue[i]) == 'undefined') {
            //     this.transfervalue.splice(i, 1)
            //     i = i - 1
            //   }
            // }
            const arr_temp = [].concat(this.transfervalue) // 创建一个新的临时数组，用以操作后不变更原数组
            console.log(this.transfervalue)
            arr_temp.splice(newIndex, 0, arr_temp.splice(oldIndex, 1)[0]) // 在b位置插入从a位置截取的元素
            this.transfervalue = arr_temp
            console.log(this.transfervalue)
            this.$emit('update:call-back', this.transfervalue)
          }
        })
        const leftEl = leftPanel.getElementsByClassName('el-transfer-panel__list')[0]
        Sortable.create(leftEl, {
          animation: 100,
          onEnd: (evt) => {
            const { oldIndex, newIndex } = evt
            const temp = this.transferdata[oldIndex]
            this.$set(this.transferdata, oldIndex, this.transferdata[newIndex])
            this.$set(this.transferdata, newIndex, temp)
          }
        })
        leftPanel.ondragover = (ev) => {
          ev.preventDefault()
        }
        leftPanel.ondrop = (ev) => {
          ev.preventDefault()
          const index = this.transfervalue.indexOf(this.draggingKey)
          if (index !== -1) {
            this.transfervalue.splice(index, 1)
          }
        }
        rightPanel.ondragover = (ev) => {
          ev.preventDefault()
        }
        rightPanel.ondrop = (ev) => {
          ev.preventDefault()
          if (this.transfervalue.indexOf(this.draggingKey) === -1) {
            this.transfervalue.push(this.draggingKey)
          }
        }
    },
    //查询顾问
    agentListSort(){
      let obj = {
        houseId: this.houseid,
      };
      this.$api.http.agentListSort(obj).then((res) => {
          this.transfervalue=res.data.chosedSource.map(item => {
              return item.id
          });
          let contlist=[...res.data.chosedSource,...res.data.dataSource]
          this.transferdata=contlist.map(item => {
              return {label: item.name, key: item.id}
          });
      });
    },
    // 楼盘选择
    houseChange(e) {
      this.houseid = e;
      this.Page = 1;
      this.stateoptseid = "";
      this.schedulingoptseid = "";
      this.name = "";
      this.AgentPoollist();
    },
    // 获取楼盘下拉的数据
    getHouse() {
      this.$api.api.findHouseByUser({
        orgType: localStorage.getItem("orgType"),
      }).then((res) => {
        this.houseList = res.data;
          if (localStorage.getItem("orgType") == 3) {
            this.houseid = localStorage.getItem("houseId");
          } else {
            this.houseid = res.data[0].id;
          }
        // this.houseid = this.houseList[0].id;
        this.AgentPoollist();
      });
    },
    AgentPoollist() {
      let obj = {
        current: this.Page,
        size: this.size,
        itemId: this.houseid,
        status: this.stateoptseid,
        hasSchedule: this.schedulingoptseid,
        name: this.name,
      };
      this.$api.http.AgentPoollist(obj).then((res) => {
        console.log(res);
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
    },
    screening(){
      this.Page = 1;
      this.AgentPoollist();
    },
    reset(){
      this.Page = 1;
      this.stateoptseid = "";
      this.schedulingoptseid = "";
      this.name = "";
      this.AgentPoollist();
    },
    //删除
    del(item){
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          distinguishCancelAndClose: true,
          type: 'warning'
        }).then(() => {
            this.$api.http.agentListdelete({
              id:item.id,
              houseId:this.houseid
            }).then((res) => {
                 if(res.code==0){
                     this.$message({
                      type: 'success',
                      message: '删除成功!'
                    });
                     this.Page=1;
                        this.AgentPoollist()
                 }else{
                    this.$message.error(res.message);
                 }
            })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });
        });
    },
     alldel(){
        if(this.multipleSelection.length==0){
          this.$message.error("请选择删除项！");
          return
        }else{
          console.log("11111111111",this.multipleSelection)
          let sirsto=''
          this.multipleSelection.map(item => {
              sirsto+=item.id+','
          });
            this.$confirm('此操作将永久删除, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              distinguishCancelAndClose: true,
              type: 'warning'
            }).then(() => {
                this.$api.http.agentListdelBatch({
                  ids:sirsto,
                  houseId:this.houseid
                }).then((res) => {
                     if(res.code==0){
                         this.$message({
                          type: 'success',
                          message: '删除成功!'
                        });
                         this.Page=1;
                            this.AgentPoollist()
                     }else{
                        this.$message.error(res.message);
                     }
                })
                }).catch(() => {
                  this.$message({
                    type: 'info',
                    message: '已取消删除'
                  });
            });
        }
    },
    editor() {
      console.log(this.transfervalue)
      let newlist=this.transfervalue.map((item,index) => {
        return {sort: index+1, id: item}
      });
      let obj = {
        houseId: this.houseid,
        changedArr:JSON.stringify(newlist),
      };
      this.$api.http.agentListsortUpdate(obj).then((res) => {
        this.dialogVisible = false;
        this.reset()
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
     handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.size = val;
        this.AgentPoollist()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.Page = val;
        this.AgentPoollist()
      }
  },
};
</script>

<style scoped="scoped" lang="scss" >
.box-center {
  width: 100%;
  padding: 15px;
  min-width: 1200px;
  padding-bottom: 100px;
}
.cen-tab {
  width: 100%;
  padding: 15px;
  background: #ffffff;
  margin-top: 15px;
}
.tophove {
  color: #ffffff;
  background: #2671e2;
}
.app-top {
  width: 100%;
  background: #ffffff;
  box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.04);
  border-radius: 4px;
  padding-top: 15px;
  padding-bottom: 15px;
  .app-titel {
    width: 100%;
    display: flex;
    align-items: center;
    .label {
      font-size: 14px;
      font-weight: 400;
      color: #32363d;
      line-height: 14px;
      margin-left: 15px;
    }
    .toptimeqhuan {
      height: 30px;
      background: #ffffff;
      display: flex;
      align-items: center;
    }
    .toptimeqhuan div {
      padding-left: 20px;
      padding-right: 20px;
      text-align: center;
      line-height: 30px;
      font-size: 14px;
      margin-right: 15px;
      border-radius: 4px;
      border: 1px solid #e0e0e0;
    }
  }
}
/deep/.el-transfer-panel{
  width: 300px !important;
}
/deep/.el-transfer-panel__body{
height: 400px !important;
}
/deep/.el-transfer-panel__list{
height: 400px !important;
}

</style>
