import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STComponent, STColumn, STChange } from '@delon/abc/st';
import {
  SFCascaderWidgetSchema,
  SFComponent,
  SFRadioWidgetSchema,
  SFSchema,
  SFSchemaEnum,
  SFSelectWidgetSchema,
  SFUISchema
} from '@delon/form';
import { DynamicSettingModalComponent, SinglepageSettingModalComponent } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { of } from 'rxjs';
import { map, takeLast } from 'rxjs/operators';
import { AccountDetailComponent } from 'src/app/shared/components/account-detail/account-detail.component';
import { SystemService } from '../../services/system.service';

@Component({
  selector: 'app-network-freight-component',
  templateUrl: './network-freight.component.html',
  styleUrls: ['./network-freight.component.less']
})
export class NetworkFreightComponent implements OnInit {
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sfFre', { static: false }) sfFre!: SFComponent;
  @ViewChild('sfTicket', { static: false }) sfTicket!: SFComponent;
  @ViewChild('sfTax', { static: false }) sfTax!: SFComponent;
  @ViewChild('sfNC', { static: false }) sfNC!: SFComponent;
  ui: SFUISchema = {};
  ui2: SFUISchema = {};
  ui3: SFUISchema = {};
  ui4: SFUISchema = {};
  ui5: SFUISchema = {};
  schema: SFSchema = {};
  addSchema: SFSchema = {};
  ticketSchema: SFSchema = {};
  TaxSchema: SFSchema = {};
  NCSchema: SFSchema = {};
  _$expand: boolean = false;
  taxStatus: boolean = false;
  TicketStatus: boolean = true;
  NCStatus: boolean = false;
  formData: any;
  ticketId: any;
  ticketItem: any;
  formDataTicket: any;
  formDataNC: any;
  formDataTax: any;
  NCID: string = '';
  isVisible = false;
  isVisibleTicket = false;
  edit = false;
  editId = false;
  isLoading: boolean = false;
  tabs: any[] = [{ name: '开票设置' }, { name: '税务设置' }, { name: 'NC设置' }];

  columns: STColumn[] = [
    {
      title: '公司名称',
      width: '180px',
      index: 'enterpriseName'
    },
    {
      title: '纳税人识别号',
      width: '180px',

      index: 'taxCode'
    },
    {
      title: '成立日期',
      width: '150px',
      index: 'enterpriseRegistrationTime'
    },
    {
      title: '成本费率',
      width: '150px',
      render: 'costRate'
    },
    {
      title: '附加费率',
      width: '150px',
      render: 'goodsSurchargeRatio'
    },
    {
      title: '云开票',
      width: '150px',
      render: 'ticketEnable'
    },
    {
      title: '保险',
      width: '150px',
      render: 'insuranceEnable'
    },
    {
      title: '平安银行',
      width: '150px',
      render: 'pinganEnable'
    },
    {
      title: '浦发银行',
      width: '150px',
      render: 'pufaEnable'
    },
    {
      title: '平安电子账户',
      width: '170px',
      render: 'pinganAccountEnable'
    },
    {
      title: '浦发电子账户',
      width: '170px',
      render: 'pufaAccountEnable'
    },
    {
      title: '开票开关',
      width: '150px',
      render: 'invoiceEnable'
    },
    {
      title: '操作',
      width: '110px',
      fixed: 'right',
      className: 'text-center',
      buttons: [
        { type: 'divider' },
        {
          text: '基础设置<br>',
          click: item => this.creat(item)
        },
        {
          text: '财务设置<br>',
          click: item => this.ticket(item)
        },
        {
          text: '充值账户<br>',
          click: item => this.settingPay(item)
        },
        {
          text: '应用设置<br>',
          click: item => this.settingApp(item)
        },

        {
          text: '系统配置<br>',
          click: item => this.settingAction(item)
        },
        // {
        //   text: '合同设置',
        //   click: item => this.roleAction(item, 2)
        // },
      ]
    }
  ];

  selectedRows: any[] = [];

  get reqParams() {
    return {
      ...this.sf?.value
    };
  }

  constructor(public service: SystemService, private nzModalService: NzModalService, private router: Router, private ar: ActivatedRoute) {}

  ngOnInit(): void {
    this.initSF();
    this.initSFFre();
    // this.initSFTicket();
  }

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        break;
      case 'filter':
        this.st.load();
        break;
    }
  }
  /**
   * 伸缩查询条件
   */
  expandToggle(): void {
    this._$expand = !this._$expand;
    this.sf?.setValue('/_$expand', this._$expand);
  }
  /**
   * 查询字段个数
   */
  get queryFieldCount(): number {
    return Object.keys(this.schema?.properties || {}).length;
  }
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        enterpriseName: {
          type: 'string',
          title: '公司名称',
          ui: { placeholder: '请输入' }
        },
        taxCode: {
          type: 'string',
          title: '纳税人识别号',
          ui: { placeholder: '请输入' }
        }
      }
    };
    this.ui = { '*': { spanLabelFixed: 110, grid: { span: 8, gutter: 4 } } };
  }
  initSFTicket() {
    this.ticketSchema = {
      properties: {
        enterpriseName1: {
          type: 'string',
          title: '公司名称',
          ui: {
            widget: 'text'
          },
          default: this.ticketItem?.enterpriseName
        },
        taxCode2: {
          type: 'string',
          title: '纳税人识别号',
          ui: {
            widget: 'text'
          },
          default: this.ticketItem?.taxCode
        },
        bankName: {
          type: 'string',
          title: '开户银行',
          ui: { placeholder: '请输入' }
        },
        bankAccount: {
          type: 'string',
          title: '银行账号',
          ui: { placeholder: '请输入' }
        },
        registerAddress: {
          type: 'string',
          title: '注册地址',
          ui: { placeholder: '请输入' }
        },
        registerPhone: {
          type: 'string',
          title: '注册电话',
          ui: { placeholder: '请输入' }
        },
        taxClassificationVersion: {
          type: 'string',
          title: '税收分类版本号',
          ui: { placeholder: '请输入' }
        },
        taxClassificationCode: {
          type: 'string',
          title: '税收分类编码',
          ui: { placeholder: '请输入' }
        },
        invoiceTaxRate: {
          type: 'number',
          title: '发票税率',
          ui: { placeholder: '请输入' }
        },
        invoiceMaxAmount: {
          type: 'number',
          title: '发票面额上限',
          ui: { placeholder: '请输入' }
        },
        payee: {
          type: 'string',
          title: '收款人',
          ui: { placeholder: '请输入' }
        },
        reviewer: {
          type: 'string',
          title: '复核人',
          ui: { placeholder: '请输入' }
        },
        drawer: {
          type: 'string',
          title: '开票人',
          ui: { placeholder: '请输入' }
        },
        senderName: {
          type: 'string',
          title: '寄件人姓名',
          ui: { placeholder: '请输入' }
        },
        senderPhone: {
          type: 'string',
          title: '寄件人电话',
          ui: { placeholder: '请输入' }
        },
        senderRegionCode: {
          type: 'number',
          title: '寄件地区',
          ui: {
            widget: 'cascader',
            valueProperty: 'regionCode',
            labelProperty: 'name',
            asyncData: (node: any, index: any) => {
              return new Promise(resolve => {
                this.getRegionDetailByCode(node?.regionCode || '').subscribe(
                  res => {
                    node.children = res.map((item: any) => ({ ...item, isLeaf: index === 1 }));
                  },
                  _ => {},
                  () => {
                    resolve();
                  }
                );
              });
            }
          } as SFCascaderWidgetSchema
        },
        senderAddress: {
          type: 'string',
          title: '详细地址',
          ui: { placeholder: '请输入' }
        }
      },
      required: [
        'enterpriseName',
        'taxCode',
        'bankName',
        'bankAccount',
        'registerAddress',
        'registerPhone',
        'senderName',
        'senderRegionCode',
        'senderPhone',
        'senderAddress',
        'taxClassificationVersion',
        'taxClassificationCode',
        'invoiceTaxRate',
        'invoiceMaxAmount',
        'payee',
        'reviewer',
        'drawer'
      ]
    };
    this.ui3 = {
      '*': { spanLabelFixed: 150, grid: { span: 24 } },
      $taxClassificationVersion: { spanLabelFixed: 150, grid: { span: 24 } }
    };
  }
  initSFTax() {
    this.TaxSchema = {
      properties: {
        enterpriseName1: {
          type: 'string',
          title: '公司名称',
          ui: {
            widget: 'text'
          },
          default: this.ticketItem?.enterpriseName
        }
      },
      required: ['enterpriseName']
    };
    this.ui4 = { '*': { spanLabelFixed: 120, grid: { span: 24 } } };
  }
  initSFNC() {
    this.NCSchema = {
      properties: {
        crmCustomerId: {
          type: 'string',
          title: 'CRM客户编码',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            visibleIf: {
              _$expand: (value: boolean) => value
            },
            allowClear: true,
            onSearch: (q: any) => {
              let str = q.replace(/^\s+|\s+$/g, '');
              if (str) {
                console.log(str);

                return this.service
                  .request(this.service.$api_get_crmCustomer_page, { customerName: str })
                  .pipe(map((res: any) => (res.records as any[]).map(i => ({ label: i.customerName, value: i.id } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            }
          } as SFSelectWidgetSchema
        }
      },
      required: ['crmCustomerId']
    };
    this.ui5 = { '*': { spanLabelFixed: 120, grid: { span: 24 } } };
  }
  initSFFre() {
    this.addSchema = {
      properties: {
        enterpriseName: {
          type: 'string',
          title: '公司名称',
          ui: { placeholder: '请输入' }
        },
        taxCode: {
          type: 'string',
          title: '纳税人识别号',
          ui: { placeholder: '请输入' }
        },
        customerCode: {
          type: 'string',
          title: '税收分类编码',
          ui: { placeholder: '请输入' }
        },
        invoiceTaxRate: {
          type: 'number',
          title: '发票税率',
          ui: { placeholder: '请输入' }
        },
        surchargeRate: {
          type: 'string',
          title: '附加费比例',
          ui: { placeholder: '请输入' }
        }
      },
      required: ['enterpriseName', 'taxCode', 'customerType', 'invoiceTaxRate', 'surchargeRate']
    };
    this.ui2 = { '*': { spanLabelFixed: 120, grid: { span: 24 } } };
  }
  roleAction(value: any, item?: any) {
    this.service.request(this.service.$api_get_crmCustomer, { id: value.id }).subscribe((res: any) => {
      console.log(res);
      if (res) {
        this.formData = res;
      }
    });
    this.edit = true;
    this.editId = value.id;
    this.isVisible = true;
  }
  // 财务设置
  ticket(value: any) {
    this.formDataTicket = [];
    this.formDataNC = [];
    this.formDataTax = [];
    this.ticketItem = value;
    this.taxStatus = false;
    this.TicketStatus = true;
    this.NCStatus = false;
    this.initSFTax();
    this.initSFNC();
    this.initSFTicket();
    this.NCID = value.id;
    if (this.TicketStatus) {
      console.log('9999999');

      this.service.request(this.service.$api_getTicketByNetworkTransporterId, { id: value.id }).subscribe((res: any) => {
        console.log(res);
        if (res) {
          let List = {
            ...res
          };
          delete List.senderRegionCode;
          (List.senderRegionCode = this.getProvinceData(res?.senderRegionCode)), (this.formDataTicket = List);
          this.ticketId = res.id;
        }
      });
    }
    if (this.NCStatus) {
      this.getNcSetData();
    }
    this.isVisibleTicket = true;
  }
  getNcSetData() {
    const List: any = [];
    console.log(99999);
    this.service.request(this.service.$api_get_crmCustomer, { id: this.ticketItem.crmCustomerId }).subscribe((res: any) => {
      console.log(res);
      if (res) {
        List.push({ label: res.customerName, value: res.id });
        console.log(List);

        this.sfNC.getProperty('/crmCustomerId')!.schema.enum = List;
        this.sfNC.getProperty('/crmCustomerId')!.widget.reset(List);
        this.sfNC.setValue('/crmCustomerId', res?.id);
      }
    });
  }
  getProvinceData(value: any) {
    this.service.http.post(this.service.$api_getRegionDetailByCode, { regionCode: value }).subscribe(res => {
      let enterpriseAddressCode: any = [];
      let regioin = res?.data?.regionFullCodes.split(',');
      regioin?.forEach((element: any) => {
        enterpriseAddressCode.push(Number(element));
      });
      if (this.TicketStatus) {
        this.sfTicket.setValue('/senderRegionCode', enterpriseAddressCode);
        return enterpriseAddressCode;
      }
    });
  }
  deleteAction(item?: any) {
    this.nzModalService.error({
      nzTitle: '确认删除？',
      nzClosable: false,
      nzCancelText: '取消',
      nzOnOk: () => {}
    });
  }
  // 基础设置
  settingAction(item?: any) {
    const modalRef = this.nzModalService.create({
      nzTitle: '系统配置',
      nzContent: DynamicSettingModalComponent,
      nzWidth: 900,
      nzComponentParams: {
        extendType: '1',
        businessId: item.id
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: boolean) => {
      if (res) {
        this.resetSF;
        this.st.load();
      }
    })
  }
  // 应用设置
  settingApp(item?: any) {
    const modalRef = this.nzModalService.create({
      nzTitle: '应用设置',
      nzContent: DynamicSettingModalComponent,
      nzWidth: 900,
      nzComponentParams: {
        extendType: '1',
        businessId: item.id,
        configvalue: 'app'
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: boolean) => {
      if (res) {
        this.resetSF;
        this.st.load();
      }
    })
  }
  // 重置账户
  settingPay(item?: any) {
    this.nzModalService.create({
      nzTitle: '充值账户',
      nzContent: DynamicSettingModalComponent,
      nzWidth: 900,
      nzComponentParams: {
        extendType: '1',
        businessId: item.id,
        configvalue: 'bankcard'
      },
      nzFooter: null
    });
  }

  createAccount(item: any, bankType: string, key: string) {
    if (item[key]) {
      return;
    }
    const params = {
      accountType: 3,
      bankType,
      clientName: item.enterpriseName,
      ctfId: item.taxCode,
      ltdId: item.id,
      roleId: item.id,
      roleName: item.enterpriseName
    };
    this.service
      .request('/api/fcc/accountBalance/saveByLtd', {
        ...params
      })
      .subscribe(res => {
        if (res) {
          this.st.load(1);
          this.service.msgSrv.success(bankType === '1' ? res?.paMsg : res?.pfMsg);
        }
      });
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this.isLoading = false
  }
  handleCancel() {
    this.isVisible = false;
  }
  handleCancelTicket() {
    this.isVisibleTicket = false;
  }
  handleOKTicket() {
    console.log(this.taxStatus, this.TicketStatus, this.NCStatus);
    if (this.TicketStatus) {
      console.log(this.sfTicket);
      console.log(this.sfTicket.value);

      if (!this.sfTicket.valid) {
        this.service.msgSrv.warning('请正确填写完整！');
        return;
      }
      const params = {
        ...this.sfTicket.value
      };
      if (this.ticketId) {
        params.id = this.ticketId;
      }
      params.senderRegionCode = this.sfTicket.value.senderRegionCode[2];
      console.log(params);
      this.service.request(this.service.$api_networkTransporterTicket_save, params).subscribe((res: any) => {
        if (res) {
          this.service.msgSrv.success('保存成功！');
          this.isVisibleTicket = false;
          this.st.reload(1);
        }
      });
    } else if (this.NCStatus) {
      console.log(this.sfNC);
      console.log(this.formDataNC);
      console.log(this.sfNC?.value);

      if (!this.sfNC.valid) {
        this.service.msgSrv.warning('请正确填写完整！');
        return;
      }
      const params = {
        ...this.sfNC.value
      };
      if (this.NCID) {
        params.id = this.NCID;
      }
      console.log(params);
      this.service.request(this.service.$api_setCrmCustomer, params).subscribe((res: any) => {
        if (res) {
          this.service.msgSrv.success('保存成功！');
          this.isVisibleTicket = false;
          this.st.reload(1);
        }
      });
      // api_setCrmCustomer
    }
  }

  handleOK() {
    console.log(this.sfFre.value);
    if (!this.sfFre.valid) {
      this.service.msgSrv.warning('请正确填写完整！');
      return;
    }
    const params = {
      ...this.sfFre.value
    };
    if (this.editId) {
      params.id = this.editId;
    }
    this.service.request(this.service.$api_save_crmCustomer, params).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('保存成功！');
        this.isVisible = false;
        this.st.reload();
      } else {
        this.service.msgSrv.warning(res?.msg);
      }
    });
  }
  // 云开票
  setMakeInvoice() {}
  /*
   * 根据地区code查询地区列表
   */
  getRegionDetailByCode(regionCode: any) {
    return this.service.request(this.service.$api_get_region_by_code, { regionCode });
  }
  changeType(value: any) {
    if (value.name === '税务设置') {
      this.taxStatus = true;
      this.TicketStatus = false;
      this.NCStatus = false;
    } else if (value.name === '开票设置') {
      this.TicketStatus = true;
      this.NCStatus = false;
      this.taxStatus = false;
    } else if (value.name === 'NC设置') {
      this.getNcSetData();
      this.NCStatus = true;
      this.TicketStatus = false;
      this.taxStatus = false;
    }
  }
  // 新增
  creat(value?: any) {
    console.log(value);
    this.router.navigate(['./new/' + value?.id], { relativeTo: this.ar });
  }
}
