import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STChange } from '@delon/abc/st';
import { SFComponent, SFSchema, SFDateWidgetSchema, SFUISchema, SFSelectWidgetSchema } from '@delon/form';
import { NzModalService } from 'ng-zorro-antd/modal';
import { ContractManagementService } from '../../services/contract-management.service';
import { DatePipe } from '@angular/common';
import { ShipperBaseService } from '@shared';

@Component({
  selector: 'app-contract-management-contract-list',
  templateUrl: './contract-list.component.html',
  styleUrls: ['./contract-list.component.less'],
  providers: [DatePipe]
})
export class ContractManagementContractListComponent implements OnInit {
  url = `/rule?_allow_anonymous=true`;
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false })
  sf!: SFComponent;
  @ViewChild('auditModal', { static: false })
  auditModal!: any;
  schema: SFSchema = {};
  columns: STColumn[] = [];
  ui: SFUISchema = {};
  _$expand = false;
  isLoading: boolean = false;
  /**
   * 查询参数
   */
  get reqParams() {
    const params = {
      ...this.sf?.value
    };
    delete params.signTime;
    delete params._$expand;
    if (
      this.datePipe.transform(this.sf?.value?.signTime?.[0], 'yyyy-MM-dd HH:mm:ss') &&
      this.datePipe.transform(this.sf?.value?.signTime?.[1], 'yyyy-MM-dd HH:mm:ss')
    ) {
      params.signTime = {
        start: this.datePipe.transform(this.sf?.value?.signTime?.[0], 'yyyy-MM-dd HH:mm:ss'),
        end: this.datePipe.transform(this.sf?.value?.signTime?.[1], 'yyyy-MM-dd HH:mm:ss')
      };
    }
    return {
      ...params
    };
  }
  selectedRows: any[] = [];
  constructor(
    public service: ContractManagementService,
    private nzModalService: NzModalService,
    public shipperservice: ShipperBaseService,
    private router: Router,
    private datePipe: DatePipe
  ) {}

  ngOnInit(): void {
    this.initST();
    this.initSF();
  }
  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      {
        title: '合同编号',
        width: '130px',
        className: 'text-center',
        render: 'contractCode'
      },
      {
        title: '签约对象',
        width: '100px',
        className: 'text-center',
        index: 'signingObjectLabel'
      },
      {
        title: '合同类型',
        width: '100px',
        className: 'text-center',
        index: 'contractName'
      },
      {
        title: '业务单号',
        className: 'text-center',
        width: '120px',
        index: 'businessCode'
      },
      {
        title: '签署日期',
        className: 'text-center',
        width: '120px',
        index: 'signTime'
      },
      {
        title: '状态',
        className: 'text-center',
        width: '120px',
        type: 'badge',
        index: 'esignFlowStatus',
        badge: {
          '0': { text: '未发起', color: 'default' },
          '1': { text: '待签章', color: 'default' },
          '2': { text: '已生效', color: 'success' },
          '3': { text: '已撤销', color: 'warning' },
          '4': { text: '已作废', color: 'warning' },
          '5': { text: '已过期', color: 'warning' },
          '7': { text: '已拒签', color: 'warning' }
        }
      },
      {
        title: '操作',
        className: 'text-center',
        fixed: 'right',
        width: '80px',
        buttons: [
          {
            text: '签署',
            iif: item => item.esignFlowStatus === '0' || item.esignFlowStatus === '1' || item.esignFlowStatus === '13',
            click: item => this.service.StartTheProcessToESignById(item.id, () => this.st.load(1))
          }
        ]
      }
    ];
  }
  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        contractCode: {
          type: 'string',
          title: '合同编号'
        },
        businessCode: {
          type: 'string',
          title: '业务单号'
        },
        signingObject: {
          type: 'string',
          title: '签约对象',
          enum: [
            { label: '全部', value: '' },
            { label: '货主', value: 1 },
            { label: '司机', value: 2 }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          }
        },
        contractType: {
          title: '合同类型',
          type: 'string',
          default: '',
          ui: {
            widget: 'dict-select',
            containsAllLable: true,
            params: { dictKey: 'contract:type' },
            visibleIf: {
              _$expand: (value: boolean) => value
            },
            containAllLable: true
          } as SFSelectWidgetSchema
        },
        resourceType: {
          title: '货源类型',
          type: 'string',
          default: '',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'goodresource:type' },
            containsAllLable: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        },
        enterpriseInfoId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            },
            asyncData: () => this.shipperservice.getNetworkFreightForwarder()
          }
        },
        contractObjectName: {
          type: 'string',
          title: '合同对象',
          ui: {
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          }
        },
        signTime: {
          title: '签署日期',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
        esignFlowStatus: {
          title: '状态',
          type: 'string',
          default: '',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'esign:flow:status' },
            containsAllLable: true,
            visibleIf: {
              _$expand: (value: boolean) => value
            }
          } as SFSelectWidgetSchema
        }
      },
      type: 'object'
    };
    this.ui = { '*': { spanLabelFixed: 110, grid: { span: 8, gutter: 4 } } };
  }
  /**
   * 查询字段个数
   */
  get queryFieldCount(): number {
    return Object.keys(this.schema?.properties || {}).length;
  }
  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        break;
      case 'filter':
        this.st.load();
        break;
    }
  }
  routeTo(item: any) {
    this.router.navigate(['/ticket/invoice-requested-detail/1']);
  }

  auditAction(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '审核',
      nzContent: this.auditModal,
      nzFooter: [
        {
          label: '拒绝',
          type: 'default',
          onClick: () => {
            modal.destroy();
          }
        },
        {
          label: '通过',
          type: 'primary',
          onClick: () => {
            modal.destroy();
          }
        }
      ]
    });
    modal.afterClose.subscribe(res => {
      this.st.load();
    });
  }

  showReason(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '查看原因',
      nzContent: '运单数据异常，暂时无法开票，请联系客服400-xxxx-xxxx',
      nzFooter: [
        {
          label: '关闭',
          type: 'primary',
          onClick: () => {
            modal.destroy();
          }
        }
      ]
    });
  }
  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this._$expand = false;
    this.isLoading = true;
  }
  /**
   * 伸缩查询条件
   */
  expandToggle(): void {
    this._$expand = !this._$expand;
    this.sf?.setValue('/_$expand', this._$expand);
  }
}
