import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { apiConf } from '@conf/api.conf';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFUISchema } from '@delon/form';
import { DatePipe, ModalHelper, _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { UsermanageService } from '../../../../services/usercenter.service';

@Component({
  selector: 'app-supplier-components-list-view',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.less'],
  providers: [DatePipe]
})
export class FreightComponentsListDetailComponent implements OnInit {
  @ViewChild('approvedModal', { static: false })
  approvedModal!: any;
  @ViewChild('redectModal', { static: false })
  redectModal!: any;

  detailData: any = { adminUserInfo: { name: '' }, legalPersonIdentityVO: { name: '' } };
  tempalateData = { ...this.detailData };
  suppliersData: any = {};

  isEdit = false;

  uploadURl = apiConf.waterFileUpload;
  disabledUpload = false;
  enterpriseAddressCode: any = [];
  ltdId: any = [];

  approvalOpinion = '';
  networkTransporter = null;
  constructor(
    public service: UsermanageService,
    private route: ActivatedRoute,
    private nzModalService: NzModalService,
    private datePipe: DatePipe
  ) {}

  ngOnInit() {
    this.initData();
    this.loadltdId();
  }
  loadltdId() {
    this.service.getNetworkFreightForwarder().subscribe(res => {
      if (res) {
        this.ltdId = res;
        console.log(this.ltdId );
        
      }
    });
  }

  initData() {
    this.service
      .request(this.service.$api_get_freight_detail, {
        id: this.route.snapshot.params.id
      })
      .subscribe(res => {
        if (res) {
          this.detailData = res;
          this.tempalateData = { ...this.detailData };
          this.enterpriseAddressCode = [
            Number(this.detailData.fullRegionVO?.provinceCode),
            Number(this.detailData.fullRegionVO?.cityCode),
            Number(this.detailData.fullRegionVO?.areaCode)
          ];
        }
        console.log(res);
      });
  }

  goBack() {
    window.history.go(-1);
  }
  /**
   * 冻结
   */
  freezeOrResume(type: number) {
    this.service.http
      .post(this.service.$api_lock_freight, {
        id: this.route.snapshot.params.id,
        statedLocked: !!type
      })
      .subscribe(res => {
        if (res.data === true) {
          if (type === 0) {
            this.service.msgSrv.success(`启用成功！`);
          } else {
            this.service.msgSrv.success(`冻结成功！`);
          }
          this.initData();
        } else {
          this.service.msgSrv.error(res.msg || '操作失败！');
        }
      });
  }

  /**
   * 支付权限
   */
  PayOrResume(type: number) {
    this.service.http
      .post(this.service.$api_lock_freight, {
        id: this.route.snapshot.params.id,
        statedLocked: !!type
      })
      .subscribe(res => {
        if (res.data === true) {
          if (type === 1) {
            this.service.msgSrv.success(`开启成功！`);
          } else {
            this.service.msgSrv.success(`关闭成功！`);
          }
          this.initData();
        } else {
          this.service.msgSrv.error(res.msg || '操作失败！');
        }
      });
  }

  auditPass() {
    this.networkTransporter = null;
    this.nzModalService.create({
      nzTitle: '审核通过',
      nzContent: this.approvedModal,
      nzOnOk: () => {
        if (!this.networkTransporter) {
          return false;
        }
        this.auditEnterprise(20);
        return;
      }
    });
  }
  auditNo() {
    this.approvalOpinion = '';
    this.nzModalService.create({
      nzTitle: '审核驳回',
      nzContent: this.redectModal,
      nzOnOk: () => {
        if (!this.approvalOpinion) {
          return false;
        }
        this.auditEnterprise(30);
        return;
      }
    });
  }

  private auditEnterprise(status: number) {
    this.service
      .request(this.service.$api_audit_freight, {
        approvalStatus: status,
        id: this.detailData.id,
        approvalOpinion: this.approvalOpinion,
        networkTransporter: this.networkTransporter
      })
      .subscribe(res => {
        if (res) {
          this.service.msgSrv.success(status === 20 ? '审核通过' : '驳回成功');
        }
        this.initData();
      });
  }

  ratify() {
    this.isEdit = true;
  }

  deleteImg(data: any, key: string, key2: string) {
    this.nzModalService.warning({
      nzTitle: '是否确认删除该图片',
      nzOnOk: () => {
        this.disabledUpload = true;
        data[key] = '';
        data[key2] = '';
        setTimeout(() => {
          this.disabledUpload = false;
        }, 100);
      }
    });
  }
  changeUpload({ file, fileList, type }: any, data: any, key: string, key2: string) {
    if (type === 'success') {
      data[key] = file.response.data?.fullFileWatermarkPath;
      data[key2] = file.response.data?.fullFilePath;
    }
  }

  /**
   * 级联获取地区数据
   * @param node 节点
   * @param index 层级
   * @returns
   */
  loadRegionData = (node: any, index: number) => {
    return new Promise(resolve => {
      this.service.request(this.service.$api_get_region_by_code, { regionCode: node?.regionCode || '' }).subscribe(
        res => {
          node.children = res.map((item: any) => ({ ...item, isLeaf: index === 1, value: item.regionCode, label: item.name }));
        },
        _ => {},
        () => {
          resolve(node);
        }
      );
    });
  };

  reset() {
    this.detailData = { ...this.tempalateData };
    this.isEdit = false;
  }

  save() {
    const dateil = { ...this.detailData };
    Object.assign(dateil.legalPersonIdentityVO, {
      validStartTime: this.datePipe.transform(dateil.legalPersonIdentityVO.validStartTime, 'yyyy-MM-dd'),
      validEndTime: this.datePipe.transform(dateil.legalPersonIdentityVO.validEndTime, 'yyyy-MM-dd')
    });
    const params = {};
    Object.assign(params, {
      adminMobile: dateil.adminMobile,
      adminAppUserId: dateil.adminAppUserId,
      adminUserInfo: { ...dateil.adminUserInfo },
      bankAccount: dateil.bankAccount,
      businessScope: dateil.businessScope,
      createBank: dateil.createBank,
      creditPhoto: dateil.creditPhoto,
      creditPhotoWatermark: dateil.creditPhotoWatermark,
      enterpriseAddress: dateil.enterpriseAddress,
      enterpriseAddressCode: this.enterpriseAddressCode[2],
      enterpriseLogo: dateil.enterpriseLogo,
      enterpriseName: dateil.enterpriseName,
      enterpriseRegistrationTime: this.datePipe.transform(dateil.enterpriseRegistrationTime, 'yyyy-MM-dd'),
      enterpriseType: dateil.enterpriseType,
      id: dateil.id,
      legalPersonIdentityDTO: { ...dateil.legalPersonIdentityVO },
      licensePhoto: dateil.licensePhoto,
      licensePhotoWatermark: dateil.licensePhotoWatermark,
      networkTransporter: dateil.networkTransporter,
      oftenUsedServices: dateil.oftenUsedServices,
      operatingEndTime: this.datePipe.transform(dateil.operatingEndTime, 'yyyy-MM-dd'),
      operatingStartTime: this.datePipe.transform(dateil.operatingStartTime, 'yyyy-MM-dd'),
      promotersTelephone: dateil.promotersTelephone,
      registerAddress: dateil.registerAddress,
      registerPhone: dateil.registerPhone,
      registrationCapital: dateil.registrationCapital,
      taxAuthority: dateil.taxAuthority,
      unifiedSocialCreditCode: dateil.unifiedSocialCreditCode
    });
    this.service.request(this.service.$api_save_enterprise_admin, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('企业修改成功');
        this.initData();
        this.isEdit = false;
      }
    });
  }
}
