import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";

import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";

@Component({
  selector: "app-appraise-management",
  templateUrl: "./appraise-management.component.html",
  styleUrls: ["./appraise-management.component.less"],
})
export class AppraiseManagementComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private tool: ToolService
  ) {}

  listOfData: any[] = []; //表格数据

  modal: boolean = false; //新增/编辑模态框
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  department: any; //所属科室
  mediUser: number; //调解人
  taskType: number; //工单类型
	orderNo:any;
  allTaskType: any; //所有工单类型
  allHospital: any; //所有院区
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

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

  btnLoading: boolean = false; //提交按钮loading状态
  searchTimerSubject = new Subject();

  ngOnInit() {
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun(v[1], v[2]);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getAllHos();
    this.getStatus();
    this.initForm();
  }

  // 初始化增删改按钮
  coopBtns: any = {};

  // 获取院区
  hospital: string; //选中院区
  getAllHos() {
    this.hospital = this.tool.getCurrentHospital().id + "";
    this.changeHos();
    this.getList();
  }
  // 修改院区获取对应科室
  changeHos() {
    this.taskType = null;
    this.worker = null;
    this.mediUser = null;
    this.status = null;
    this.getAllWorker();
    this.getAllMediUser();
  }

  // 获取配送人员
  worker: number; //配送人员
  allWorker: any = []; //所有配送人员
  snum1 = 0;
  getAllWorker(e?, those?) {
    let that = those || this;
    let postData = {
      user: {
        name: e || "",
        hospital: { id: that.hospital },
        usertype: { id: 106 }, //配送人员
      },
      idx: 0,
      sum: 20,
    };
    that.snum1++;
    that.mainService
      .getFetchDataList("data", "user", postData)
      .subscribe((data) => {
        that.allWorker = data.list;
        that.snum1--;
        if (that.snum1 === 0) {
          that.isLoading = false;
        }
      });
  }

  // 指派人员
  allDesUser: any = []; //所有配送人员
  getAllDesUser(id) {
    this.isLoading = true;
    this.mainService
      .getHosUser("getUsersByPermission", id)
      .subscribe((data) => {
        this.isLoading = false;
        this.allDesUser = data.data || [];
      });
  }

  // 获取所有调解人
  allMediUser: any = []; //所有调解人
  snum2 = 0;
  getAllMediUser(e?, those?) {
    let that = those || this;
    let postData = {
      user: {
        name: e || "",
        hospital: { id: that.hospital },
      },
      idx: 0,
      sum: 20,
    };
    that.snum2++;
    that.mainService
      .getFetchDataList("data", "user", postData)
      .subscribe((data) => {
        that.allMediUser = data.list;
        that.snum2--;
        if (that.snum2 === 0) {
          that.isLoading = false;
        }
      });
  }

  // 用户输入搜索
  changeUser(e) {
    this.searchTimer(this.getAllWorker, e, this);
  }

  // 调解人搜索
  changeMediUser(e) {
    this.searchTimer(this.getAllMediUser, e, this);
  }

  // 边输入边搜索节流阀
  isLoading: boolean = false;
  searchTimer(fun, e, those) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e, those]);
  }

  // 获取处理状态
  status: number; //处理状态
  handleStatus: any = []; //所有处理状态
  getStatus() {
    var that = this;
    that.mainService
      .getDictionary("list", "bad_evaluation_handle_status")
      .subscribe((data) => {
        that.handleStatus = data;
      });
		that.mainService
		  .getDictionary("list", "order_type")
		  .subscribe((data) => {
		    that.allTaskType = data;
		  });
  }

  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
  // 重置
  reset() {
    this.pageIndex = 1;
    this.taskType = null;
		this.orderNo = null;
    this.worker = null;
    this.mediUser = null;
    this.status = null;
    this.getList();
  }
  // 表格数据
  loading1 = false;
  getList() {
    var that = this;
    let data = {
      idx: that.pageIndex - 1,
      sum: that.pageSize,
      badEvaluationHandle: {
				orderNo: that.orderNo || "",
        orderType: {
					id: that.taskType || "",
				},
        worker: { id: that.worker || "" },
        handleStatus: { id: that.status || "" },
        hosId: that.hospital,
        mediationUser: { id: that.mediUser },
      },
    };
    if (!data.badEvaluationHandle.orderType) {
      delete data.badEvaluationHandle.orderType;
    }
    if (!data.badEvaluationHandle.worker.id) {
      delete data.badEvaluationHandle.worker;
    }
    if (!data.badEvaluationHandle.handleStatus.id) {
      delete data.badEvaluationHandle.handleStatus;
    }
    if (!data.badEvaluationHandle.mediationUser.id) {
      delete data.badEvaluationHandle.mediationUser;
    }
    this.loading1 = true;
    that.mainService
      .getFetchDataList("adviceCollection", "badEvaluationHandle", data)
      .subscribe((data) => {
        this.loading1 = false;
        that.listOfData = data.list;
        that.listLength = data.totalNum;
      });
  }

  // 获取工单类型
  getAllTaskType() {
    let that = this;
    let postData = {
      taskType: {
        hosId: { id: that.hospital },
      },
      idx: 0,
      sum: 30,
    };
    that.mainService
      .getFetchDataList("configuration", "taskType", postData)
      .subscribe((data) => {
        that.allTaskType = data.list;
      });
  }

  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      user: [null, [Validators.required]],
    });
  }
  submitForm() {
    var that = this;
    for (const i in that.validateForm.controls) {
      that.validateForm.controls[i].markAsDirty();
      that.validateForm.controls[i].updateValueAndValidity();
    }
    if (that.validateForm.invalid) return;
    that.btnLoading = true;
    let postData = {
      badEvaluationHandle: {
        id: that.coopId,
        mediationUser: { id: that.validateForm.value.user },
      },
    };
    that.mainService
      .postCustom("adviceCollection", "updData/badEvaluationHandle", postData)
      .subscribe((data) => {
        that.hideModal();
        that.btnLoading = false;
        if (data.status == 200) {
          that.showPromptModal("指派", true, "");
          that.initForm();
          that.getList();
        } else {
          that.showPromptModal("指派", false, data.msg);
        }
      });
  }

  // 指派
  designate(id, hosId) {
    this.modal = true;
    this.coopId = id;
    this.getAllDesUser(hosId);
  }
  hideModal() {
    this.modal = false;
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    this.getList();
  }
	
	// 查看工单
	detailModalShow = false; //弹窗开关
	coopData:any;
	viewDetail(data){ // 1:维修 2:配送陪检
		this.coopData = data;
		if(data.orderType.value==1){
			this.detailModalShow = true;
		}else{
			this.router.navigateByUrl("/main/orderManagement/orderDetail/" + data.workOrder);
		}
	}
	
	// 关闭弹窗
	closeDetailModelOrder(e) {
	  this.detailModalShow = JSON.parse(e).show;
	}
	// 弹窗确定
	confirmDetailModelOrder(e){
	  this.detailModalShow = false;
	  this.getList();
	}
	
  // 查看
  detail(id, tj?) {
    if (tj) {
      this.router.navigate(["/main/appraiseManagement/appraiseDetail/" + id], {
        fragment: "tj",
      });
    } else {
      this.router.navigate(["/main/appraiseManagement/appraiseDetail/" + id],  {
        fragment: "wtj",
      });
    }
  }

  // 格式化时间戳
  timestampToTime(timestamp) {
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + "-";
    let M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "-";
    let D =
      date.getDate() < 10 ? "0" + date.getDate() + " " : date.getDate() + " ";
    let h =
      date.getHours() < 10
        ? "0" + date.getHours() + ":"
        : date.getHours() + ":";
    let m =
      date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    return Y + M + D + h + m;
  }
}
