import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { MainService } from "../../services/main.service";

@Component({
  selector: "app-allocation-worker",
  templateUrl: "./allocation-worker.component.html",
  styleUrls: ["./allocation-worker.component.less"],
})
export class AllocationWorkerComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private mainService: MainService
  ) {}

  ngOnInit() {
    this.groupList = JSON.parse(localStorage.getItem("user")).user.scope ? JSON.parse(localStorage.getItem("user")).user.scope.groupIds : [];
    this.getWorkerList();
  }
  // 配送人员数据
  workerList = [];

  id; //工单id
  stateId; //工单状态id
  listOfDisplayData: any[] = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  searchName: string = ""; //搜索框内容
  checkedGroup; //选中人员分组
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //是否展示提示框

  btnLoading: boolean = false; //提交按钮loading状态

  // 配送人员数据
  groupList: Array<{ groupName: string; id: string }> = []; //分组下拉框
  snum = 0;
  loading1 = false;
  nameMask = false; //是否禁用
  groupMask = false; //是否禁用
  workerDispatchUserList = '';
  getWorkerList(pageIndex?) {
    this.id = this.route.snapshot.paramMap.get("id");
    this.stateId = this.route.snapshot.paramMap.get("stateId");
    this.pageIndex = pageIndex ? pageIndex : this.pageIndex;

    let groupsId = [];
    JSON.parse(localStorage.getItem("user")).infoPermission.groups.forEach(
      (e) => {
        groupsId.push(e.id);
      }
    );

    let postData: any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      groupIds: "",
      hosId: this.route.snapshot.paramMap.get("hosId"),
    };
    if (this.searchName) {
      postData.name = this.searchName;
    } else {
      delete postData.name;
    }
    if (this.checkedGroup) {
      postData.groupId = this.checkedGroup;
    } else {
      delete postData.groupId;
    }
    this.snum++;
    this.loading1 = true;
    this.mainService
      .getSerInfo("getOnlineWorker", postData)
      .subscribe((data) => {
        this.snum--;
        if (this.snum == 0) {
          this.loading1 = false;
        }
        console.log(data);
        this.workerDispatchUserList = data.type;
        this.workerList = data.data;
        this.listLength = data.totalNum;
      });
  }

  // 输入用户信息搜索节流阀
  time: any;
  searchInp(type) {
    this.getWorkerList(1);
    console.log(type);
    if (type == "worker") {
      this.groupMask = Boolean(this.searchName);
    } else if (type == "group") {
      this.nameMask = Boolean(this.checkedGroup);
    }
  }

  // 选择分配配送人员
  worderId = 0; //配送人员id
  checkAllotWorker(id, flag?): void {
    this.mapOfCheckedId = {
      [id]: flag ? !this.mapOfCheckedId[id] : this.mapOfCheckedId[id],
    };
    this.worderId = id;
  }

  // 分配
  submit() {
    let that = this;
    that.btnLoading = true;
    let flag: any = that.route.snapshot.paramMap.get("flag");

    let postData: any = {};
    let flags = "";
    if (that.id.includes("_")) {
      flags = "batchExcuteWorkOrder";
      let ids_types = that.id.split("-");
      let stateIds = that.stateId.split("-");
      postData.workOrders = [];
      stateIds.forEach((item, i) => {
        postData.workOrders.push({
          id: ids_types[i].split("_")[0],
          type: ids_types[i].split("_")[1],
          worker: { id: that.worderId },
          gdState: { id: item },
        });
      });
    } else {
      flags = flag == 1 ? "excuteWorkOrder/reassign" : "excuteWorkOrder/assign";
      postData = {
        workOrder: {
          id: that.id,
          worker: { id: that.worderId },
          gdState: { id: that.stateId },
        },
      };
    }
    that.mainService.assignWorker(postData, flags).subscribe((data) => {
      that.btnLoading = false;
      if (data.status == 200) {
        that.showPromptModal("分配", true, "");
      } else {
        that.showPromptModal("分配", false, data.msg);
      }
    });
  }

  // 关闭弹框
  close() {
    history.go(-1);
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
  }
}
