<template>
  <div class="box-center">
    <!-- 头 -->
    <div class="app-top">
      <div class="app-titel" style="margin-top: 5px">
        <div class="label" v-if="orgType!=3" id="label1">楼盘名称：</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 maxlength="10" clearable v-model="name"></el-input>
        </div>
        <div class="label">工作状态：</div>
        <div>
          <el-select v-model="stateoptseid" clearable filterable 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" clearable filterable 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>
          <el-button type="primary"
            @click="screening()">筛选</el-button
          >
        </div>
        <div style="margin-left: 20px">
          <el-button @click="reset()">清空筛选条件</el-button>
        </div>
        <div style="margin-left: 20px">
          <el-button  v-if="sch_index_add" type="primary"
           @click="addinfo()" >添加</el-button
          >
        </div>
        <div style="margin-left: 20px">
          <el-button v-if="sch_index_del" :disabled='multipleSelection.length==0' type="primary"
           @click="alldel()" >批量删除</el-button
          >
        </div>
        <div  style="margin-left: 20px">
          <el-button v-if="sch_index_sort" :disabled='multipleSelection.length==0' type="primary"
            @click="showDailog"
            >批量排班</el-button
          >
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <div class="cen-tab">
      <el-table
        :data="tableData"
        stripe

        @selection-change="handleSelectionChange"
        style="width: 100%"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="name" label="顾问名" >
        </el-table-column>
        <el-table-column prop="name" label="状态" >
          <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="上次接待结束时间"

        >
        </el-table-column>

        <el-table-column prop="date" label="有无排班" >
          <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="操作" >
          <template slot-scope="scope">
            <el-button  type="text" @click="switchstatus(scope.row,2)" v-if="scope.row.status == 0&&sch_index_pause">暂停接待</el-button>
            <el-button  type="text" @click="switchstatus(scope.row,0)" v-if="scope.row.status == 2&&sch_index_pause">空闲</el-button>
            <el-button  type="text" v-if="sch_index_job" @click="showDailog1(scope.row)">工作安排</el-button>
            <el-button  type="text" v-if="sch_index_del" @click="del(scope.row)">删除</el-button>
          </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="Page"
          :page-sizes="[10, 30, 50]"
          :page-size="size"
          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>


    <el-dialog title="新增" :visible.sync="showVisible">
      <div>
         <div style="text-align: center;">
           <Calendar v-on:choseDay="clickDay" ref="calendar" v-on:changeMonth="changeDate" :agoDayHide='timeAcc' :markDate='arr' />
          </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showVisible = false">取 消</el-button>
        <el-button type="primary" @click="save()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Calendar from "../../components/Calendar/calendar.vue";
import { mapGetters } from "vuex";
import Sortable from 'sortablejs'
import index1Vue from '../admin/dept/index1.vue';
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,
      showVisible: false,
      arr: [],
      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: 10,
      total: 0,
      roleId:'',
      arr1:[],
      showFlag:false,
      timeAcc:''
    };
  },
    computed: {
    ...mapGetters(["permissions"]),
  },
  components: {
    Calendar,
  },
  created() {
    this.sch_index_add = this.permissions["sch_index_add"];
    this.sch_index_del = this.permissions["sch_index_del"];
    this.sch_index_sort = this.permissions["sch_index_sort"];
    this.sch_index_pause = this.permissions["sch_index_pause"];
    this.sch_index_job = this.permissions["sch_index_job"];
  },
  mounted() {
    this.getHouse();

    let newSjc=new Date().getTime()-86400000+'';
    this.timeAcc=newSjc.substr(0,10)

    console.log(this.timeAcc,'sadasdasdas')
  },
  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: '已取消修改'
              // });
        });
    },
    save(){
      if(this.showFlag){
         let arr2=[]
         let arr3=[]
        console.log(this.arr1);
        this.arr.map((item,idx)=>{
          let idx1=this.arr1.findIndex(item1=>item1==item)
          if(idx1==-1){
            // 没有重复的
            console.log(item);
            arr2.push(item)
          }
        })
        this.arr1.map((item,idx)=>{
          let idx1=this.arr.findIndex(item1=>item1==item)
          if(idx1==-1){
            // 没有重复的
            console.log(item);
            arr3.push(item)
          }
        })
        if(arr2.length==0&&arr3.length==0){
          console.log('没改变')
          this.showVisible=false
          this.AgentPoollist();
          return
        }
        // console.log(arr2,'新增的数据');
        // console.log(arr3,'修改的');
        // console.log(this.arr);
        // return

      this.$api.api.scheduling({
        chosed:arr2.join(','),
        unChosed:arr3.join(','),
        id:this.roleId
      })
      .then(res=>{
        // console.log(res);
        this.$message.success('修改成功')
        this.showVisible=false
        this.AgentPoollist();
      })
      }else{
        let arr=[]
        this.multipleSelection.map(item=>{
          arr.push(item.id)
        })
        this.$api.api.schedulings({
        chosed:this.arr.join(','),

        ids:arr.join(',')
      })
      .then(res=>{
        // console.log(res);
        this.$message.success('修改成功')
        this.showVisible=false
        this.AgentPoollist();
      })
      }
    },
    showDailog(){
      this.arr=[]
      this.showVisible=true
      this.showFlag=false
      // this.$refs.calendar.getList(new Date());
    },
    showDailog1(row){
      this.showFlag=true
      this.showVisible=true
      this.roleId=row.id
      this.arr=[]
      //获取所选择的时间
      this.$api.api.findByAgentId({
        id:row.id
      }).then(res=>{
        console.log(res);
        if(res.data.length==0)return
        res.data.map(item=>{
          this.arr.push(item.jobDate)
        })
        this.arr1=[...this.arr]
      })
    },
    clickDay(data) {
      console.log(data,'1',this.arr); //选中某天
      // 首先判断是否在已经选中的时间内如果是则对数据进行删除，如果没有则将数据放入数组
      let idx=this.arr.findIndex(item=>item==data)
      console.log(idx);
      if(idx==-1){
        this.arr.push(data)
      }else{
        this.arr.splice(idx,1)

      }
    },
    changeDate(data) {
      console.log(data,'2'); //左右点击切换月份
    },
    clickToday(data) {
      console.log(data,'3'); //跳到了本月
    },
    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: 1000px;
  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;
      min-width: 100px;
      text-align: right;
    }
    .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{
padding-bottom: 50px;
height: 400px !important;
}
/deep/.el-dialog{
  min-width: 950px;
}
// /deep/ .wh_content_all{
//   background: none;
// }
// /deep/ .wh_top_changge li {
//   color: black;
// }
// /deep/ .wh_content_item_tag,.wh_content_item{
//   color: black;
// }
</style>
