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

import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { NzMessageService } from 'ng-zorro-antd/message';
import { format } from 'date-fns';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
@Component({
  selector: "app-order-management",
  templateUrl: "./order-management.component.html",
  styleUrls: ["./order-management.component.less"],
})
export class OrderManagementComponent implements OnInit {
  constructor(
    public route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private tool: ToolService,
    private message: NzMessageService,
		private fb: FormBuilder,
  ) {}
  searchTimerSubject = new Subject();
	searchParentDeptSubject = new Subject();
	debounceSubject = new Subject();
  ngOnInit() {
		this.initSearchForm();
		this.searchParentDeptSubject.pipe(debounceTime(500)).subscribe((v: any) => {
		  this.getAllParentdepart(v).subscribe((result) => {
		    this.isLoading = false;
		    if (result.status == 200) {
		      this.allParentdepart = result.list;
		    }
		  });
		});
		
		this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
		  let fun = v[0];
		  fun.call(this, v[1], v[2]);
		});
		
		this.debounceSubject.pipe(debounceTime(500)).subscribe((v:boolean) => {
		  this.getList();
		});
		
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1]);
    });
		
    this.initOrderType();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    if (this.coopBtns.deleted) {
      //是否显示已删除
      this.checkOptionsOne.push({
        label: "已删除",
        value: "3",
        checked: false,
      });
    }
    this.getAllHos();
    this.getGdStates();
  }
  loginUser: any = localStorage.getItem("user")
    ? JSON.parse(localStorage.getItem("user")).user
    : null; //登录人信息
  listOfData: any[] = []; //表格数据
  modal: boolean = false; //回复模态框
  coopId: string; //表格中执行操作的id
  hospital: string; //选中院区
  gdcode: string = ""; //工单单号
  statisticsDateType: number; //统计分类
  statisticsDateTypeList: any = []; //统计分类
  department: any; //所属科室
  alldepart: any = []; //当前院区所属科室
  worker: number; //选择执行配送人员
  tasktype: number; //选择任务类型
  allWorker: any = []; //当前院区执行配送人员列表
  allTasktype: any = []; //当前院区任务类型列表
  gdState: number; //选择工单状态
  specialCloseFlag: any; //特殊情况关闭
  workOrderRemark: string = ''; //工单备注
  dateRange: any = []; //发起时间
  gdStates: any; //工单状态列表
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

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

  btnLoading: boolean = false; //提交按钮loading状态
  checkOptionsOne: Array<any> = [
    { label: "超时工单", value: "0", checked: false },
    { label: "异常工单", value: "1", checked: false },
		{ label: "加急", value: "3", checked: false },
    // { label: "24小时未完成", value: "2", checked: false },
  ]; //工单异常状态

  // 初始化工单异常状态选中状态
  initOrderType() {
    let that = this;
    console.log(that.route);
    if (that.route.snapshot.fragment == "yc") {
      that.checkOptionsOne[1].checked = true;
    }
  }

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

  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
  // 重置
  reset() {
    this.pageIndex = 1;
    this.statisticsDateType = null;
    this.tasktype = null;
    if (!(this.coopBtns.currentDept && !this.coopBtns.allOrders)) {
      this.department = null;
    }
    if (!(this.coopBtns.currentUser && !this.coopBtns.allOrders)) {
      this.worker = null;
    }
    this.gdcode = "";
    this.gdState = null;
    // this.specialCloseFlag = null;
    // this.workOrderRemark = '';
    this.dateRange = [];
    this.changeDate();
		this.initSearchForm();
    this.getList();
  }

  // 获取院区
  getAllHos() {
    this.hospital = this.tool.getCurrentHospital().id + "";
    this.changeHos();
  }
  // 修改院区获取对应科室,工单类型，执行配送人员
  changeHos() {
    this.department = null;
    this.worker = null;
    this.tasktype = null;
    this.statisticsDateType = null;
    this.getDeparts();
    this.getAssociation();
    this.getAllWorker();
    this.getAllTasktype();
  }

  // 获取关联类型
  getAssociation() {
    let that = this;
    that.mainService
      .getDictionary("list", "statistics_date_type")
      .subscribe((data) => {
        that.statisticsDateTypeList = data;
      });
  }

  // 获取配送人员
  getAllWorker(e?, those?) {
    let that = those || this;
    let postData = {
      user: {
        name: e || "",
        hospital: { id: that.hospital },
        usertype: { id: 106 }, //配送人员
      },
      idx: 0,
      sum: 20,
    };
    that.isLoading = true;
    that.mainService
      .getFetchDataList("data", "user", postData)
      .subscribe((data) => {
        that.allWorker = data.list;
        that.isLoading = false;
      });
  }
  // 获取任务类型
  getAllTasktype(e?, those?) {
    let that = those || this;
    let postData: any = {
      idx: 0,
      sum: 10,
      taskType: {
        taskName: e || "",
        hosIds: that.hospital,
        simpleQuery: true,
      },
    };
    if (that.statisticsDateType) {
      postData.taskType.statisticsDateType = { id: that.statisticsDateType };
    }
    that.isLoading = true;
    that.mainService
      .getFetchDataList("configuration", "taskType", postData)
      .subscribe((data) => {
        that.allTasktype = data.list;
        that.isLoading = false;
      });
  }
  // 选择统计分类
  selectStatisticsDateType(e) {
    this.statisticsDateType = e;
    this.changeTasktype("");
    this.tasktype = null;
  }
  onCalendarChangeDate(dateArr){
    console.log(dateArr)
    if(dateArr.length == 2){
      let dateStart = new Date(dateArr[0]);
      let dateEnd = new Date(dateArr[1]);
      dateStart.setHours(0,0,0);
      dateEnd.setHours(23,59,59);
      this.dateRange = [dateStart,dateEnd];
    }
  }
  // 表格数据
  loading1 = false;
  getList() {
    // 有备注，无发起时间则提示
    if(this.workOrderRemark && !this.dateRange.length){
      this.message.info('请选择发起时间！');
      return;
    }
    // 三个权限都没有，则不展示
    if(!this.coopBtns.currentDept && !this.coopBtns.currentUser && !this.coopBtns.allOrders){
      this.listOfData = [];
      this.listLength = 0;
      return;
    }
    var that = this;
    let data: any = {
      idx: that.pageIndex - 1,
      sum: that.pageSize,
      workOrder: {
        worker: { id: that.worker },
        gdState: { id: that.gdState },
        gdcode: this.gdcode,
        createDept: that.department,
        hosId: that.hospital,
        abnormityType: that.checkOptionsOne[1].checked ? 1 : undefined,
        timeOut: that.checkOptionsOne[0].checked ? 1 : 0,
				specialCloseFlag: this.validateSearchForm.value.specialCloseFlag,
				workOrderRemark: this.validateSearchForm.value.workOrderRemark,
				busiParent: this.validateSearchForm.value.busiParent
      },
    };
    if (that.checkOptionsOne[2]) {
      if (that.checkOptionsOne[2].checked) {
        data.workOrder.range = 2;
      } else {
        delete data.workOrder.range;
      }
    }
    if (that.checkOptionsOne[3]) {
      if (that.checkOptionsOne[3].checked) {
        data.workOrder.deleteFlag = 1;
      } else {
        delete data.workOrder.deleteFlag;
      }
    }
    if (that.statisticsDateType) {
      data.workOrder.taskType = {
        statisticsDateType: { id: that.statisticsDateType },
      };
    }
    if (that.tasktype) {
      data.workOrder.serTaskTypes = that.tasktype;
    }
    if (!data.workOrder.worker.id) {
      delete data.workOrder.worker;
    }
    if (!data.workOrder.gdState.id) {
      delete data.workOrder.gdState;
    }
    // if (
    //   data.workOrder.specialCloseFlag === undefined ||
    //   data.workOrder.specialCloseFlag === null
    // ) {
    //   delete data.workOrder.specialCloseFlag;
    // }
    if (!data.workOrder.createDept) {
      delete data.workOrder.createDept;
    }
    delete data.workOrder.overdueTime24;
    delete data.workOrder.startTime1;
    delete data.workOrder.endTime1;
    // if (that.checkOptionsOne[2] && that.checkOptionsOne[2].checked) {
    if (false) {
      data.workOrder.overdueTime24 = true;
    } else if (that.startDate && that.endDate) {
      data.workOrder.startTime1 = that.startDate;
      data.workOrder.endTime1 = that.endDate;
      // data.workOrder.workOrderRemark = that.workOrderRemark;
    }
    that.mapOfCheckedId = {};
    that.checkedDepIds = [];
    that.isAllDisplayDataChecked = false;
    that.loading1 = true;
    that.mainService
      .getFetchDataList("data", "workOrder", data)
      .subscribe((result) => {
        that.loading1 = false;
        that.listOfData = result.list.map(v => ({...v, endDeptsName: v.endDepts ? v.endDepts.map(v => v.dept).toString() : ''}));
        that.listLength = result.totalNum;
      });
  }

  // 获取所有科室
  getDeparts(dept?) {
    let data = {
      department: {
        cascadeHosId: this.hospital,
        dept: dept,
      },
      idx: 0,
      sum: 20,
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("data", "department", data)
      .subscribe((data) => {
        this.alldepart = data.list;
        this.isLoading = false;
        if (dept === undefined && this.coopBtns.currentDept && !this.coopBtns.allOrders) {
          // 初次渲染，权限有当前科室工单,没有全部工单，则回显申请科室
          this.alldepart = [this.loginUser.dept];
          this.department = this.loginUser.dept.id;
        }
        if (dept === undefined && this.coopBtns.currentUser && !this.coopBtns.allOrders) {
          // 初次渲染，权限有当前人员工单,没有全部工单，则回显执行配送人员
          this.allWorker = [this.loginUser];
          this.worker = this.loginUser.id;
        }
        this.getList();
      });
  }

  // 获取工单状态
  getGdStates() {
    var that = this;
    that.mainService.getDictionary("list", "gdstate").subscribe((data) => {
      that.gdStates = data;
    });
  }

  // 表格筛选
  log(value: object[]): void {
    console.log(value);
    this.pageIndex = 1;
    this.getList();
  }
  // 日期选择
  startDate: string; //发起时间开始
  endDate: string; //发起时间结束
  changeDate(result?): void {
    if (!result) {
      this.startDate = this.endDate = "";
      return;
    }
    this.startDate = format(result[0], 'yyyy-MM-dd HH:mm:ss');
    this.endDate = format(result[1], 'yyyy-MM-dd HH:mm:ss');
  }

  // 展示信息提示框（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();
  }

  // 查看
  detail(e, id) {
    e.stopPropagation();
    this.router.navigateByUrl("/main/orderManagement/orderDetail/" + id);
  }
  // 批量删除
  showDelModals(e) {
    let ids = this.checkedDepIds.join(",");
    this.showDelModal(e, ids);
  }
  //删除
  loading3 = false;
  delModal: boolean = false; //删除模态框
  showDelModal(e, id) {
    e.stopPropagation();
    this.delModal = true;
    this.coopId = id + "";
  }
  hideDelModal() {
    this.delModal = false;
  }
  confirmDel() {
    this.loading3 = true;
    this.mainService[this.coopId.includes(",") ? "delOrders" : "delOrder"](
      this.coopId
    ).subscribe((data) => {
      this.loading3 = false;
      this.delModal = false;
      if (data.status == 200) {
        if (
          this.listOfData.length == 1 &&
          this.pageIndex == Math.ceil(this.listLength / this.pageSize)
        ) {
          this.listLength--;
          this.pageIndex = Math.ceil(this.listLength / this.pageSize);
        }
        this.showPromptModal("删除", true, "");
      } else {
        this.showPromptModal("删除", false, data.msg);
      }
    });
  }

  // 导出
  loading2 = false;
  export() {
    // 有备注，无发起时间则提示
    if( !this.dateRange.length){
      this.message.info('请选择发起时间！');
      return;
    }
    // 三个权限都没有，则不展示
    if(!this.coopBtns.currentDept && !this.coopBtns.currentUser && !this.coopBtns.allOrders){
      return;
    }
    let that = this;
    let postData: any = {
      idx: that.pageIndex - 1,
      sum: that.pageSize,
      workOrder: {
        worker: { id: that.worker },
        gdState: { id: that.gdState },
        gdcode: this.gdcode,
        createDept: that.department,
        hosId: that.hospital,
        abnormityType: that.checkOptionsOne[1].checked ? 1 : undefined,
        timeOut: that.checkOptionsOne[0].checked ? 1 : 0,
				specialCloseFlag: this.validateSearchForm.value.specialCloseFlag,
				workOrderRemark: this.validateSearchForm.value.workOrderRemark,
				busiParent: this.validateSearchForm.value.busiParent
      },
    };
    if (that.checkOptionsOne[2]) {
      if (that.checkOptionsOne[2].checked) {
        postData.workOrder.range = 2;
      } else {
        delete postData.workOrder.range;
      }
    }
		if (that.checkOptionsOne[3]) {
		  if (that.checkOptionsOne[3].checked) {
		    postData.workOrder.deleteFlag = 1;
		  } else {
		    delete postData.workOrder.deleteFlag;
		  }
		}
    if (that.statisticsDateType) {
      postData.workOrder.taskType = {
        statisticsDateType: { id: that.statisticsDateType },
      };
    }
    if (that.tasktype) {
      postData.workOrder.serTaskTypes = that.tasktype;
    }
    if (!postData.workOrder.worker.id) {
      delete postData.workOrder.worker;
    }
    if (!postData.workOrder.gdState.id) {
      delete postData.workOrder.gdState;
    }
    // if (
    //   postData.workOrder.specialCloseFlag === undefined ||
    //   postData.workOrder.specialCloseFlag === null
    // ) {
    //   delete postData.workOrder.specialCloseFlag;
    // }
    if (!postData.workOrder.createDept) {
      delete postData.workOrder.createDept;
    }
    delete postData.workOrder.overdueTime24;
    delete postData.workOrder.startTime1;
    delete postData.workOrder.endTime1;
    // if (that.checkOptionsOne[2] && that.checkOptionsOne[2].checked) {
    if (false) {
      postData.workOrder.overdueTime24 = true;
    } else if (that.startDate && that.endDate) {
      postData.workOrder.startTime1 = that.startDate;
      postData.workOrder.endTime1 = that.endDate;
      // postData.workOrder.workOrderRemark = that.workOrderRemark;
    }
    that.mapOfCheckedId = {};
    that.checkedDepIds = [];
    that.isAllDisplayDataChecked = false;
    this.loading2 = true;
    that.mainService.dataExport("workOrder", postData).subscribe(
      (data) => {
        this.loading2 = false;
        this.showPromptModal("导出", true, "");
        var file = new Blob([data], {
          type: "application/vnd.ms-excel",
        });
        //trick to download store a file having its URL
        var fileURL = URL.createObjectURL(file);
        var a = document.createElement("a");
        a.href = fileURL;
        a.target = "_blank";
        a.download = "工单列表.xls";
        document.body.appendChild(a);
        a.click();
      },
      (err) => {
        this.loading2 = false;
        this.showPromptModal("导出", false, "");
      }
    );
  }

  // 申请科室边输边搜节流阀
  isLoading = false;
  changeInp(e) {
    this.searchTimer(this.getDeparts, e);
  }

  // 用户输入搜索配送人员
  changeUser(e) {
    this.searchTimer(this.getAllWorker, e);
  }
  // 用户输入搜索任务类型
  changeTasktype(e) {
    this.searchTimer(this.getAllTasktype, e);
  }

  // 边输入边搜索节流阀
  searchTimer(fun, e) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e]);
  }
	
	changeDeptInp(e) {
	  this.isLoading = true;
	  this.searchParentDeptSubject.next(e);
	}
	
	//获取所有的父级科室列表
	getAllParentdepart(keyWord = "") {
	  let postData: any = {
	    idx: 0,
	    sum: 10,
	    department: {
	      hospital: { id: this.tool.getCurrentHospital().id },
	      keyWord: keyWord,
	    },
	  };
	  return this.mainService.getFetchDataList("data", "department", postData);
	}
	
	// 打开父级科室下拉框baba
	allParentdepart:any = [];
	openDeptSelect(flag) {
	  if (flag) {
	    this.isLoading = true;
	    this.getAllParentdepart().subscribe((result) => {
	      this.isLoading = false;
	      if (result.status == 200) {
	        this.allParentdepart = result.list;
	      }
	    });
	  }
	}
	
	// 详细搜索
	searchModal: boolean = false; //新增/编辑模态框
	modelName = ""; //模态框名称
	validateSearchForm: FormGroup; //新增/编辑表单
	coopData: any = {}; //当前操作列
	// 显示弹框
	showSearchModal() {
	  this.modelName = "详细搜索";
	  this.searchModal = true;
	}
	//关闭新增/编辑弹框
	hideSearchModal() {
	  this.searchModal = false;
	}
	
	// 详细搜索-提交
	submitSearchModal(){
	  this.searchModal = false;
	  this.getList();
	}
	
	// 初始化新增form表单
	initSearchForm() {
	  this.validateSearchForm = this.fb.group({
	    specialCloseFlag: [null],
	    workOrderRemark: [null],
			busiParent: [null],
	  });
	}
	
	// 详细搜索提交
	submitForm(): void {
	  for (const i in this.validateSearchForm.controls) {
	    this.validateSearchForm.controls[i].markAsDirty();
	    this.validateSearchForm.controls[i].updateValueAndValidity();
	  }
	  if (this.validateSearchForm.invalid) {
	    return;
	  }
	
	  console.log(this.validateSearchForm.value)
	  this.loading1 = true;
	  this.debounceSubject.next(true);
	}
	
  // 截取意见内容(ie内核截取)
  spliceContent(con) {
    if (con.length >= 41 && navigator.userAgent.indexOf("Trident") > -1) {
      return con.slice(0, 20) + "...";
    } else {
      return con;
    }
  }
  // 选中表格单列
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedDepIds = []; //已选中单列id
  refreshStatus(): void {
    let listOfData = this.listOfData.filter(
      (item) => item.gdState.value != 6 && item.gdState.value != 7
    );
    this.isAllDisplayDataChecked = listOfData.every(
      (item) => this.mapOfCheckedId[item.id]
    );
    let arr = [];
    for (var k in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[k]) {
        arr.push(Number(k));
      }
    }
    this.checkedDepIds = arr;
  }
  // 整行操作
  selectedListData(data) {
    if (data.gdState.value == 6 || data.gdState.value == 7) {
      return;
    }
    this.mapOfCheckedId[data.id] = !this.mapOfCheckedId[data.id];
    this.refreshStatus();
  }
  // 全选
  isAllDisplayDataChecked = false; //当前页是否全选
  checkAll(value: boolean): void {
    this.listOfData.forEach((item) => {
      if (item.gdState.value != 6 && item.gdState.value != 7) {
        this.mapOfCheckedId[item.id] = value;
      }
    });
    this.refreshStatus();
  }
}
