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

import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { NzMessageService } from 'ng-zorro-antd';
@Component({
  selector: "app-tripartite-company",
  templateUrl: "./tripartite-company.component.html",
  styleUrls: ["./tripartite-company.component.less"],
})
export class TripartiteCompanyComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopData: any; //当前操作列
  currentHospital; //当前院区

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

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  nextSchemeName = ""; //下一个开启的方案名称
  modelName = ""; //模态框名称

  showDropdown:boolean = false;

  ngOnInit() {
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getList(1);
    this.getCompanyType();
  }

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

  // 搜索
  search() {
    this.getList(1);
  }
  // 重置
  reset() {
    this.searchDto = {};
    this.getList(1);
  }

  // 表格数据
  searchDto: any = {};
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      company: {
        statisticalHosId: this.currentHospital.id,
        busiType: { key: 'company_busi_type', value: '2' },
        ...this.searchDto,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "company", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 新增弹框
  addModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }
	
	// 使用范围选择
	scopeValue:any;
	// 格式化使用范围
	setScopeRadio(){
		let value = this.validateForm.value.employScope
		let list = this.scopeList.find(i=>i.id == value)
		if(list.value=='-1'){
			this.scopeValue = ''
		}else if(list.value=='1'){
			if(this.currentHospital.parent){
				this.scopeValue = this.currentHospital.parent.id
			}else{
				this.scopeValue = this.currentHospital.id
			}
		}else if(list.value=='2'){
			if(this.currentHospital.parent && this.currentHospital.parentDeptId){
				this.scopeValue = this.currentHospital.id
			}
		}else{
			if(this.currentHospital.parent && this.currentHospital.parentDeptId){
				this.scopeValue = this.currentHospital.parentDeptId
			}else{
				this.scopeValue = this.currentHospital.id
			}
		}
		console.log(111,this.scopeValue)
	}
	
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
			employScope: ['', [Validators.required]],
      name: ['', [Validators.required, Validators.pattern(/\S/)]],
      nickName: ['', [Validators.required]],
      companyTypeIds: [this.companyTypeList.map(v => ({ label: v.name, value: v.id, checked: false })), [Validators.required]],
      contacts: [''],
      mphone: [''],
    });
  }

  //获取公司分类
  isLoading:boolean = false;
  companyTypeList:any[] = [];
	scopeList:any[] = [];
  getCompanyType() {
    this.isLoading = true;
    this.mainService.getDictionary("list", "company_type").subscribe((data) => {
      this.companyTypeList = data || [];
    });
		this.mainService.getDictionary("list", "select_range").subscribe((data) => {
		  this.isLoading = false;
			for(let i of data){
				i.disabled = false
			}
			for(let i of data){
				if((this.currentHospital || this.currentHospital.parent) && !this.currentHospital.parentDeptId){
					if(i.value=='2'){
						i.disabled = true
					}
				}
				if (!this.currentHospital.parent && !this.currentHospital.parentDeptId){
					if(i.value=='3'){
						i.disabled = true
					}
				}
			}
		  this.scopeList = data;
			console.log(9999,this.scopeList)
		});
  }

  // 新增/编辑表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }
		this.setScopeRadio()
    console.log(this.validateForm.value)
    let companyList = this.validateForm.value.companyTypeIds.filter(v => v.checked);
    if(!companyList.length){
      this.message.info("请选择公司分类");
      return;
    }

    this.btnLoading = true;
    let postData:any = {};

    if (this.add) {
      //增加
      postData = {
        company: {
          hosId: this.scopeValue,
					selectRange:{
						id:this.validateForm.value.employScope
					},
          name: this.validateForm.value.name,
          nickName: this.validateForm.value.nickName,
          companyTypeIds: companyList.map(v => v.value).toString(),
          contacts: this.validateForm.value.contacts,
          mphone: this.validateForm.value.mphone,
          busiType: { key: 'company_busi_type', value: '2' },
        }
      };
    } else {
      //编辑
      postData = {
        company:{
          ...this.coopData,
          ...{
            hosId: this.scopeValue,
						selectRange:{
							id:this.validateForm.value.employScope
						},
            name: this.validateForm.value.name,
            nickName: this.validateForm.value.nickName,
            companyTypeIds: this.validateForm.value.companyTypeIds.filter(v => v.checked).map(v => v.value).toString(),
            contacts: this.validateForm.value.contacts,
            mphone: this.validateForm.value.mphone,
            busiType: { key: 'company_busi_type', value: '2' },
          }
        }
      };
    }
    console.log(postData);
    this.mainService
      .coopData("addData", "company", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideAddModal();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, "");
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 编辑
  edit(e, data) {
    e.stopPropagation();
    console.log(data);
    this.initForm();
    this.modelName = "编辑";
    this.add = false;
    this.modal = true;
    this.coopData = data;
		if(data.selectRange){
			this.validateForm.controls.employScope.setValue(data.selectRange.id);
		}
    this.validateForm.controls.name.setValue(data.name);
    this.validateForm.controls.nickName.setValue(data.nickName);
    this.validateForm.controls.companyTypeIds.setValue(this.companyTypeList.map(v => ({label: v.name, value: v.id, checked: data.companyTypeIds.includes(v.id)})));
    this.validateForm.controls.contacts.setValue(data.contacts);
    this.validateForm.controls.mphone.setValue(data.mphone);
  }

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

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    e,
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    e.stopPropagation();
    this.confirmDelType = type;
    this.delModal = true;
    this.coopData = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.mainService
        .simplePost("rmvData", "company", [this.coopData.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }
}
