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, SFUISchema } from '@delon/form';
import { DynamicSettingModalComponent, SinglepageSettingModalComponent } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { takeLast } from 'rxjs/operators';
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;
  ui: SFUISchema = {};
  ui2: SFUISchema = {};
  ui3: SFUISchema = {};
  ui4: SFUISchema = {};
  schema: SFSchema = {};
  addSchema: SFSchema = {};
  ticketSchema: SFSchema = {};
  TaxSchema: SFSchema = {};
  _$expand = false;
  taxStatus = false;
  formData: any;
  ticketId: any;
  ticketItem: any;
  formDataTicket: any
  formDataTax: any
  isVisible = false;
  isVisibleTicket = false;
  edit = false;
  editId = false;
  tabs: any[] = [
    {name: '开票设置'},
    {name: '税务设置'},
  ];

  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: '150px',
      render: 'pinganAccountEnable'
     },
    { 
      title: '浦发电子账户',
      width: '150px',
      render: 'pufaAccountEnable'
     },
    { 
      title: '开票开关',
      width: '150px',
      render: 'invoiceEnable'
     },
    {
      title: '操作',
      width: '110px',
      fixed: 'right',
      className: 'text-left',
      buttons: [
        {
          text: '基础设置',
          click: item => this.ticket(item)
        },
        {
          text: '财务设置',
          click: item => this.ticket(item)
        },
        {
          text: '充值账户',
          click: item => this.settingPay(item)
        },
        {
          text: '应用设置',
          click: item => this.settingApp(item)
        },
        {
          text: '系统配置',
          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: '请输入' }
        },
        registerPhone2: {
          type: 'string',
          title: '税收分类版本号',
          ui: { placeholder: '请输入' }
        },
        registerPhone3: {
          type: 'string',
          title: '税收分类编码',
          ui: { placeholder: '请输入' }
        },
        registerPhone4: {
          type: 'string',
          title: '发票税率',
          ui: { placeholder: '请输入' }
        },
        registerPhone5: {
          type: 'string',
          title: '发票面额上限',
          ui: { placeholder: '请输入' }
        },
        registerPhone6: {
          type: 'string',
          title: '收款人',
          ui: { placeholder: '请输入' }
        },
        registerPhone7: {
          type: 'string',
          title: '复核人',
          ui: { placeholder: '请输入' }
        },
        registerPhone8: {
          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']
    };
    this.ui3 = { '*': { spanLabelFixed: 120, 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 } } };
  }
  initSFFre() {
    this.addSchema = {
      properties: {
        enterpriseName: {
          type: 'string',
          title: '公司名称',
          ui: { placeholder: '请输入' }
        },
        taxCode: {
          type: 'string',
          title: '纳税人识别号',
          ui: { placeholder: '请输入' }
        },
        customerCode: {
          type: 'string',
          title: '税收分类编码',
          ui: { placeholder: '请输入' }
        },
        invoiceTaxRate: {
          type: 'string',
          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.formDataTax = [];
    this.ticketItem  = value;
      this.initSFTax();
      this.initSFTicket();
    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;
      }
    });
    this.isVisibleTicket = true;
  }
  getProvinceData(value: any) {
    this.service.http.post(this.service.$api_getRegionDetailByCode, { regionCode: value}).subscribe(res => {
      console.log(res.data)
      console.log(this.formDataTicket)
      let enterpriseAddressCode : any= [];
      let regioin = res?.data?.regionFullCodes.split(',');
      console.log(regioin)
      regioin?.forEach((element: any) => {
           enterpriseAddressCode.push(Number(element))
      });
      console.log(enterpriseAddressCode)
      this.sfTicket.setValue('/senderRegionCode', enterpriseAddressCode);
     return enterpriseAddressCode;
    });
  }
  deleteAction(item?: any) {
    this.nzModalService.error({
      nzTitle: '确认删除？',
      nzClosable: false,
      nzCancelText: '取消',
      nzOnOk: () => {}
    });
  }
// 基础设置
  settingAction(item?: any) {
    this.nzModalService.create({
      nzTitle: '基础设置',
      nzContent: DynamicSettingModalComponent,
      nzWidth: 900,
      nzComponentParams: {
        extendType: '1',
        businessId: item.id,
      },
      nzFooter: null
    });
  }
  // 应用设置
  settingApp(item?: any) {
    this.nzModalService.create({
      nzTitle: '基础设置',
      nzContent: DynamicSettingModalComponent,
      nzWidth: 900,
      nzComponentParams: {
        extendType: '1',
        businessId: item.id,
        configvalue: 'app'
      },
      nzFooter: null
    });
  }
  // 重置账户
  settingPay(item?: any) {
    this.nzModalService.create({
      nzTitle: '基础设置',
      nzContent: DynamicSettingModalComponent,
      nzWidth: 900,
      nzComponentParams: {
        extendType: '1',
        businessId: item.id,
        configvalue: 'bankcard'
      },
      nzFooter: null
    });
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
  }
  handleCancel() {
    this.isVisible = false;
  }
  handleCancelTicket() {
    this.isVisibleTicket = false;
  }
  handleOKTicket() {
    console.log(this.sfTicket.valid)
    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);
      }
    });
  }

  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) {
  console.log(value);
   if(value.name === '税务设置') {
      this.taxStatus = true
   } else {
    this.taxStatus = false
   }
  } 
  // 新增
  creat() {
    this.router.navigate(['./new'], { relativeTo: this.ar });
  }
}
