<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.username"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入用户名称"
      />
      <el-input
        v-model="listQuery.userAccount"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入用户账号"
      />
      <el-button
        v-permission="['GET /admin/builtRecovery/list','POST /admin/builtRecovery/assignTask']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="用户id" prop="id" />
      <el-table-column align="center" label="用户姓名" prop="userName" />
      <el-table-column align="center" label="用户性别" prop="gender" />
      <el-table-column align="center" label="用户账号" prop="userAccount" />
      <el-table-column align="center" label="手机号" prop="mobile" />
      <!-- <el-table-column align="center" label="身份证号" prop="idCard" /> -->
      <el-table-column align="center" label="创建时间" prop="createTime" />
      <el-table-column align="center" label="类型" prop="state">
        <template slot-scope="scope">{{ stateMap[scope.row.state] }}</template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="type">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.type==0 ? 'success' : 'error' "
          >{{ scope.row.type==0 ? '有效' : '失效' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="任务数量" prop="taskTotal" />

      <el-table-column align="center" label="操作" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.taskTotal!=0"
            v-permission="['GET /admin/builtRecovery/list','POST /admin/builtRecovery/assignTask']"
            type="primary"
            size="mini"
            @click="handleAssigned(scope.row)"
          >任务转交</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 任务转交 -->
    <el-dialog title="任务转交" :visible.sync="dialogAssignedVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        status-icon
        label-position="left"
        label-width="150px"
        style="width: 600px; margin-left:50px;"
        :model="assignForm"
      >
        <el-form-item label="分配到个人" prop="assignedUsers">
          <el-tree
            ref="tree"
            :data="sysUsers"
            :default-checked-keys="assignedUsers"
            show-checkbox
            node-key="id"
            highlight-current
            @check-change="treeChange"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ data.label }}</span>
            </span>
            
          </el-tree>
        </el-form-item>
        <el-row>分配明细如下：</el-row>
        <el-form-item :label="item.label+' 分配数量'" prop="assignedNum" v-for="(item,index) in checkList" :key="index">
          <el-input
            v-model.number="item.value"
            clearable
            style="width: 200px;"
            :placeholder="'请输入'+item.label+'分配数量'"
          />
          <!-- <el-select v-model="assignedSkillGroup" multiple style="width:500px">
            <el-option v-for="item in skillGroups" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>-->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAssignedVisible = false">取消</el-button>
        <el-button type="primary" @click="updateAssigned">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCampaign,
  createCampaign,
  updateCampaign,
  deleteCampaign,
  allSkillGroup,
  readAssigned,
  assignedCampaign
} from "@/api/campaign";
import { departUserList, getDepUser, assignTask } from "@/api/taskRecycle";

import { getToken } from "@/utils/auth";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

export default {
  name: "taskRecycle",
  components: { Pagination },
  data() {
    var validatorNum = (rule, value, callback) => {
      console.log(value);
      const reg = /^\d+$/;
      if (value == "" || value == undefined || value == null) {
        callback();
      } else {
        if (!reg.test(value) && value != "") {
          callback(new Error("只能输入数字"));
        } else {
          callback();
        }
      }
    };
    return {
      disabled: false,
checkList:[],
      list: [],
      total: 0,
      listLoading: true,
      sysUsers: [],
      // skillGroups: [],
      assignedUsers: [],
      // assignedSkillGroup: '',
      assignedCampaignId: 0, // 当前分配任务的id
      listQuery: {
        page: 1,
        limit: 20,
        username: "",
        userAccount: "",
        order: "desc"
      },
      stateMap: {
        "0": "内部账户",
        "1": "加盟商账号",
        "2": "微信游客注册"
      },
      assignForm: {
        assignedNum: ""
      },
      dataForm: {
        id: undefined,
        name: undefined,
        type: 0,
        isCsrOnline: true,
        deleted: false,
        isAutoAssigned: true,
        assignedStart: undefined,
        assignedEnd: undefined,
        isNightRun: false,
        custom_sql: undefined,
        faq: undefined,
        remark: undefined
      },
      dialogFormVisible: false,
      dialogAssignedVisible: false,
      assignedUserId :'',
      assignedTaskTotal:'',
      assignedCampaignName: "", // 当前要分配得任务名称
      dialogStatus: "",
      textMap: {
        update: "任务编辑",
        create: "任务创建"
      },
      rules: {
        name: [
          { required: true, message: "任务标题不能为空", trigger: "blur" }
        ],
        // assignedNum: [
        //   {
        //     validator: validatorNum,
        //     trigger: "blur"
        //   }
        // ]
      }
    };
  },
  computed: {
    headers() {
      return {
        "X-JZ-Admin-Token": getToken()
      };
    }
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      departUserList(this.listQuery)
        .then(response => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    filterBoolen(value) {
      if (value == 1) return "是";
      else return "否";
    },
    filterRun(value) {
      if (value == 1) return "每晚一次";
      else return "实时";
    },

    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },

    handleAssigned(row) {
      // 获取所有技能组
      // if (this.skillGroups.length == 0) {
      //   allSkillGroup().then(res => {
      //     this.skillGroups = res.data.data
      //   })
      // }
      // this.assignedCampaignName = row.name + " 分配";
      this.assignedUserId = row.id;
      this.assignedTaskTotal=row.taskTotal;
      // 获取分配信息
      getDepUser().then(res => {
        // this.assignedUsers = res.data.data.assignedUsers
        this.sysUsers = res.data.data.allUsers;
        // this.assignedSkillGroup = res.data.data.assignedGroups
      });

      this.dialogAssignedVisible = true;
      this.assignedUsers=[];
      this.checkList=[];
    },
    treeChange(){
       console.log(this.$refs.tree.getCheckedNodes());
       let checkList=((this.$refs.tree.getCheckedNodes()).filter(item=>{
         return   !item.hasOwnProperty('children');
       }));
    //  let currentCheckList=[];
    //    checkList.forEach(item=>{
    //         item.value='';
    //         currentCheckList.push(item);
    //    });
       this.checkList=checkList;
       console.log(this.checkList);
      this.assignedUsers = this.$refs.tree.getCheckedKeys(true);
      console.log(this.assignedUsers);
    },
    updateAssigned() {
      // 任务分配保存
      this.assignedUsers = this.$refs.tree.getCheckedKeys(true);
      if (this.assignedUsers.length == 0) {
        this.$message.error( "请选择需要至少一个技能组或坐席人员");
        return;
      }

      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          console.log(this.checkList);
            let builtTaskList=[];
            let total=0;
            let reg = /^\d+$/;
            let isValid=this.checkList.some(item=>{
               return  !reg.test(item.value) && item.value != ""&&item.value;
            });
            if(isValid){
              this.$message.error( "分配数量只能为数字");
                return false;
            }
            this.checkList.forEach(item=>{
              builtTaskList.push({userId:item.id,assignNumber:item.value});
              total+=item.value;
            });
          if(total>this.assignedTaskTotal){
         this.$message.error( "分配数量不能大于任务总量");
        return false;
          }
          else{
            
            let params = {
            builtTaskList: builtTaskList,
            taskTotal:this.assignedTaskTotal,
            userId: this.assignedUserId
          };
          assignTask(params)
            .then(response => {
              this.$message.success( "分配成功"
        );
          this.dialogAssignedVisible = false;
          this.getList();
            })
            .catch((err) => {
               this.$message.error( err.data.errmsg);
            });
          }
          
        } else {
          return false;
        }
      });
      console.log(this.assignedUsers, this.assignedNum);
      // 保存分配结果
      // this.$confirm('确定保存任务[' + this.assignedCampaignName + ']的分配结果？保存后立即生效', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   assignedCampaign({
      //     assignedSkillGroup: this.assignedSkillGroup,
      //     assignedUsers: this.assignedUsers,
      //     campaignId: this.assignedCampaignId
      //   }).then(res => {
      //     this.$notify.success({
      //       title: '成功',
      //       message: '任务分配成功，如果在设定时间范围，将立即生效'
      //     })
      //     this.dialogAssignedVisible = false
      //   }).catch(response => {
      //     this.$notify.error({
      //       title: '失败',
      //       message: response.data.errmsg
      //     })
      //   })
      // })
    }
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
.el-table th.gutter {
  display: table-cell !important;
}

.tableTitle {
  position: relative;
  margin: 0 auto;
  width: 600px;
  height: 1px;
  background-color: #d4d4d4;
  text-align: center;
  font-size: 16px;
  color: rgba(101, 101, 101, 1);
  margin-bottom: 20px;
}
.midText {
  position: absolute;
  left: 50%;
  background-color: #ffffff;
  padding: 0 15px;
  transform: translateX(-50%) translateY(-50%);
}
.fixed-width .el-button--mini {
  width: auto;
}
</style>
