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

import { MainService } from "../../services/main.service";
// import { MyServiceService } from "../../services/my-service.service";
import { WebsocketIndexService } from "../../services/websocket-index.service";
import http from "../../../assets/js/http";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";

@Component({
  selector: "app-home",
  templateUrl: "./home.component.html",
  styleUrls: ["./home.component.less"],
})
export class HomeComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  constructor(
    private fb: FormBuilder,
    private router: Router,
    private mainService: MainService,
    // private myService: MyServiceService,
    private myService: WebsocketIndexService,
    private tool: ToolService
  ) {}

  ngOnInit() {
    let that = this;
    that.initForm();
    that.getAllHos();
    // that.connectWs();
    this.getWebsocketIndex();
  }

  validateForm: FormGroup; //新增/编辑表单

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  //连接ws
  groupOrders = []; //当前各小组工单执行情况
  userSituation: any = {}; //用户信息
  orderSituation: any = {}; //工单信息
  getWebsocketIndex() {
    this.myService
      .connectWs(http.homeWs, { hosIds: this.hosIds })
      .subscribe((result) => {
        console.log(result);
        if (result.groupOrders && result.groupOrders.status == 200) {
          this.groupOrders = result.groupOrders.data;
        }
        if (result.userSituation) {
          this.userSituation = result.userSituation;
        }
        if (result.orderSituation) {
          this.orderSituation = result.orderSituation;
        }
      });
  }
  ngOnDestroy() {
    clearInterval(this.moveId);
    clearInterval(this.moveId1);
    this.myService.closeWs(true);
  }
  // 小组好评
  groupInfo = [];
  loading1 = false;
  getGroupCount() {
    let that = this;
    let postData = {
      hosIds: that.hosIds,
    };
    this.loading1 = true;
    that.mainService
      .postCustom("index", "groupEvaTop", postData)
      .subscribe((data) => {
        this.loading1 = false;
        that.groupInfo = data.data || [];
        if (data.data && data.data.length) {
          data.data.forEach((e) => {
            e.value = e.percent;
          });
          this.groupChart(data.data);
        } else {
          this.groupChart([]);
        }
      });
  }
  // 好评Echarts
  groupOption;
  groupChart(datas) {
    let labels = [];
    let nums = [];
    if (datas.length) {
      datas.forEach((e) => {
        labels.push(e.name);
        nums.push(e.percent - 0);
      });
    }
    console.log(labels, nums);
    var dataShadow = [];

    for (var i = 0; i < datas.length; i++) {
      dataShadow.push(100);
    }
    this.groupOption = {
      grid: {
        left: "10",
        right: "100",
        top: "0",
        bottom: "0",
        containLabel: true,
      },
      xAxis: {
        show: "",
      },
      yAxis: {
        type: "category",
        data: labels,
        axisLabel: {
          margin: 15,
          textStyle: {
            color: "#666",
          },
        },
        axisTick: {
          lineStyle: {
            color: "#fff",
          },
        },
        axisLine: {
          lineStyle: {
            color: "#fff",
          },
        },
      },
      series: [
        {
          // For shadow
          type: "bar",
          itemStyle: {
            color: "rgba(0,0,0,0.04)",
          },
          barGap: "-100%",
          barCategoryGap: "26",
          barWidth: "26",
          data: dataShadow,
          animation: false,
        },
        {
          name: "建单总数",
          type: "bar",
          data: nums,
          label: {
            show: true,
            position: "right",
            formatter: "{c} % ",
          },
          itemStyle: {
            normal: {
              //每根柱子颜色设置
              color: "#49b856",
            },
          },
          barCategoryGap: "26",
          barWidth: "26",
        },
      ],
    };
  }

  // 近一周异常工单
  abOrders: Array<any> = [];
  loading2 = false;
  getAbnormityOrders() {
    let that = this;
    this.loading2 = true;
    that.mainService
      .postCustom("index", "abnormityOrders", { hosIds: that.hosIds })
      .subscribe((data) => {
        this.loading2 = false;
        that.abOrders = data.data || [];
      });
  }

  // 工单详情
  // 查看
  orderDetail(id) {
    this.router.navigateByUrl("/main/home/orderDetail/" + id);
  }

  // swiper 轮播图
  swiperArr = [];
  swiperTop: number = 0;
  moveId: any;
  index: number = 0;
  startSwiper(length) {
    let that = this;
    clearInterval(that.moveId);
    setInterval(() => {
      that.index++;
      clearInterval(that.moveId);
      that.moveId = setInterval(() => {
        if (that.swiperTop > -32 * that.index) {
          that.swiperTop--;
        }
        if (that.swiperTop <= length * -32) {
          that.swiperTop = 0;
          that.index = 0;
          clearInterval(that.moveId);
        }
      }, 20);
    }, 2000);
  }

  swiperArr1 = [1, 2, 3];
  swiperTop1: number = 0;
  moveId1: any;
  index1: number = 0;
  startSwiper1(length) {
    let that = this;
    clearInterval(that.moveId1);
    setInterval(() => {
      that.index1++;
      clearInterval(that.moveId1);
      that.moveId1 = setInterval(() => {
        if (that.swiperTop1 > -32 * that.index1) {
          that.swiperTop1--;
        }
        if (that.swiperTop1 <= length * -32) {
          that.swiperTop1 = 0;
          that.index1 = 0;
          clearInterval(that.moveId1);
        }
      }, 20);
    }, 2000);
  }

  // 切换工单差评/最新意见
  thisTab = 1;
  checkTab(tab) {
    this.thisTab = tab;
    this.listIdx = 1;
    this.listLength = 10;
    this.getPageList();
  }

  // 展开收起
  isOpen: boolean = false;
  coopOpenId; //当前展开/收起id
  more(id) {
    if (this.coopOpenId == id) {
      this.isOpen = !this.isOpen;
    } else {
      this.isOpen = true;
    }
    this.coopOpenId = id;
  }

  // 获取当前登录人所有院区
  hosIds: string = ""; //院区id
  hosName: string = ""; //当前院区名称
  getAllHos() {
    let hos: any = this.tool.getCurrentHospital();
    this.hosName = hos.hosName;
    this.hosIds = hos.id + "";
    this.refreshList();
    this.getGroupCount();
    this.getAbnormityOrders();
  }

  // 翻页获取当前列表
  getPageList() {
    if (this.thisTab == 1) {
      this.getBadList();
    } else if (this.thisTab == 2) {
      this.getAdviceList();
    }
  }
  // 刷新页面右侧列表
  refreshList() {
    this.getAdviceList();
    this.getBadList();
  }
  // 差评表格数据
  listIdx = 1;
  listLength = 0;
  badNum = 0; //差评数量
  badList = []; //差评列表
  Loading: boolean = true; //差评loading
  getBadList() {
    var that = this;
    that.Loading = true;
    let data = {
      idx: that.listIdx - 1,
      sum: 10,
      badEvaluationHandle: {
        hosIds: that.hosIds,
        handleStatus: { id: "286" }, //未调解
      },
    };
    that.mainService
      .getFetchDataList("adviceCollection", "badEvaluationHandle", data)
      .subscribe((data) => {
        that.badList = data.list;
        that.Loading = false;
        that.listLength = that.badNum = data.totalNum;
      });
  }

  // 意见列表
  adviceList = [];
  adviceNum = 0; //意见数量
  getAdviceList() {
    this.Loading = true;
    let data = {
      idx: this.listIdx - 1,
      sum: 10,
      advice: {
        replaceFlag: 0, //未回复
        hosIds: this.hosIds,
      },
    };

    this.mainService
      .getFetchDataList("adviceCollection", "advice", data)
      .subscribe((data) => {
        this.adviceList = data.list;
        this.Loading = false;
        this.listLength = this.adviceNum = data.totalNum;
      });
  }

  // 初始化新增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.hideDesModal();
        that.btnLoading = false;
        if (data.status == 200) {
          that.showPromptModal("指派", true, "");
          that.initForm();
          that.listIdx = 1;

          that.getBadList();
        } else {
          that.showPromptModal("指派", false, data.msg);
        }
      });
  }

  // 回复弹框
  modal: boolean = false; //回复模态框
  replyCon: any; //意见内容
  reply(data) {
    this.modal = true;
    this.replyCon = data;
  }
  hideModal() {
    this.modal = false;
  }

  // 指派人员
  allDesUser: any = []; //所有配送人员
  getAllDesUser(id) {
    let that = this;
    that.mainService
      .getHosUser("getUsersByPermission", id)
      .subscribe((data) => {
        that.allDesUser = data.data || [];
      });
  }
	
	// 查看工单
	detailModalShow = false; //弹窗开关
	coopData:any;
	viewDetail(data){ // 1:维修 2:配送陪检
		this.coopData = data;
		if(data.orderType.value==1){
			this.detailModalShow = true;
		}else{
			this.router.navigateByUrl("/main/home/orderDetail/" + data.workOrder);
		}
	}
	
	// 关闭弹窗
	closeDetailModelOrder(e) {
	  this.detailModalShow = JSON.parse(e).show;
	}
	// 弹窗确定
	confirmDetailModelOrder(e){
	  this.detailModalShow = false;
	  this.getBadList();
	}
	
  // 指派
  coopId;
  desModal: boolean = false;
  designate(id, hosId) {
    this.desModal = true;
    this.coopId = id;
    this.getAllDesUser(hosId);
  }
  hideDesModal() {
    this.desModal = false;
  }

  // 调解
  detail(id) {
    this.router.navigate(["/main/home/appraiseDetail/" + id], {
      fragment: "tj",
    });
  }

  // 回复
  adviceSubContent: string; //回复内容
  btnLoading: boolean = false;
  submitReplyForm() {
    let that = this;
    if (!that.adviceSubContent) return;
    that.btnLoading = true;
    let postData = {
      advice: {
        id: that.replyCon.id,
        replyUser: { id: that.replyCon.createUser.id },
        replyContent: that.adviceSubContent,
      },
    };
    that.mainService
      .postCustom("adviceCollection", "updData/advice", postData)
      .subscribe((data) => {
        that.btnLoading = false;
        that.adviceSubContent = "";
        if (data.status == 200) {
          that.showPromptModal("回复", true, "");
          that.hideModal();
          that.listIdx = 1;
          that.getAdviceList();
        } else {
          that.showPromptModal("回复", false, data.msg);
        }
      });
  }

  // 跳转到指定页面
  toMenu(type, title) {
    if (type == "orderManagement") {
      this.router.navigate(["/main/" + type], { fragment: "yc" });
      return;
    }
    this.router.navigateByUrl("/main/" + type);
  }

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