/*
 * @Description  :
 * @Version      : 1.0
 * @Author       : Shiming
 * @Date         : 2022-03-21 09:26:45
 * @LastEditors  : Shiming
 * @LastEditTime : 2022-05-07 15:38:49
 * @FilePath     : \\tms-obc-web\\src\\app\\routes\\partner\\rebate-management\\components\\rebate-setting\\add\\add.component.ts
 * Copyright (C) 2022 huzhenhong. All rights reserved.
 */
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFComponent, SFSchema } from '@delon/form';
import { ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { RebateManagementService } from '../../../services/rebate-management.service';
import { ParterRebateManageMentAddPartnerListComponent } from '../add-partnerlist/add-partnerlist.component';
@Component({
  selector: 'app-parter-channel-rebate-management-add',
  styleUrls: ['./add.component.less'],
  templateUrl: './add.component.html'
})
export class ParterRebateManageMentAddComponent implements OnInit {
  @ViewChild('table') table!: any;
  titleText: string = '新增';
  tabelData: any;
  tabelType: any;
  formData: any;
  addStatus: boolean = false;
  hiden: boolean = false;
  configName: string = '';
  partnerType: string = '';
  remark: string = '';
  accountingRate: Number = 0;
  priority: string = '';
  partnerPeopleList: any = [];
  configType = '1';
  precision = 2;
  partnerId: Array<string> = [];
  inputValue = '';
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  schema1!: SFSchema;
  constructor(
    public router: Router,
    public ar: ActivatedRoute,
    public service: RebateManagementService,
    private modal: NzModalService,
    public shipperservice: ShipperBaseService
  ) {}
  columns: STColumn[] = [];
  initSF(data?: any) {
    this.schema1 = {
      properties: {
        ruleDescription: {
          type: 'string',
          title: '',
          disabled: this.hiden,
          ui: {
            widget: 'tinymce',
            loadingTip: 'loading...',
            config: {
              height: 500
            }
          }
          // default: data?.agreementContent || ''
        }
      }
    };
    this.columns = [
      {
        title: '合伙人名称',
        index: 'enterpriseName',
        width: 180,
        format: item => (item.partnerType ? `${item.enterpriseName || item.contactName}` : '')
      },
      { title: '联系人', index: 'contactName', width: 150, format: item => (item.partnerType ? `${item.contactName}` : '') },
      { title: '手机号', index: 'contactMobile', className: 'text-center', width: 150 },
      { title: '类型', index: 'partnerType', className: 'text-center', width: 130, type: 'enum', enum: { 1: '企业', 2: '个人' } },
      {
        title: '操作',
        width: '90px',
        fixed: 'right',
        buttons: [
          {
            text: '移除',
            click: _record => this.delete(_record),
            iif: () => {
              return !this.hiden;
            },
            acl: { ability: ['AbnormalAppear-reply'] }
          }
        ]
      }
    ];
  }
  ngOnInit() {
    if (this.ar.snapshot?.queryParams?.id) {
      this.titleText = '查看';
      this.hiden = true;
      this.initSF();
      this.initData(this.ar.snapshot?.queryParams?.id);
    }
    this.addStatus = false;
    this.initSF();
  }
  goBack() {
    window.history.go(-1);
  }
  /**
   *合伙人选择
   */
  add(item?: any) {
    const modalRef = this.modal.create({
      nzTitle: '合伙人选择',
      nzWidth: 1000,
      nzContent: ParterRebateManageMentAddPartnerListComponent,
      nzComponentParams: {
        i: item
      },
      nzFooter: null
    });
    modalRef.afterClose.subscribe((res: any) => {
      this.partnerId = [];
      if (res) {
        if (Array.isArray(res)) {
          this.partnerPeopleList = this.partnerPeopleList.concat(res);
          this.partnerPeopleList = [...this.setArr(this.partnerPeopleList, 'id')];
          res.forEach((ele: any) => {
            this.partnerId.push(ele?.id);
          });
        } else {
          this.partnerPeopleList = this.partnerPeopleList.concat(res);
          this.partnerPeopleList = [...this.setArr(this.partnerPeopleList, 'id')];
          this.partnerId.push(res?.id);
        }
      }
    });
  }
  // 数组去重
  setArr(arr: any[], id: string) {
    let obj: any = {};
    const arrays = arr.reduce((setArr, item) => {
      obj[item[id]] ? '' : (obj[item[id]] = true && setArr.push(item));
      return setArr;
    }, []);
    return arrays;
  }
  delete(item: any) {
    this.partnerPeopleList = this.partnerPeopleList.filter((d: any, i: any) => {
      return item.id != d.id;
    });
  }
  save() {
    if (!this.configName) {
      this.service.msgSrv.warning('请输入配置名称！');
      return;
    }
    if (!this.accountingRate) {
      this.service.msgSrv.warning('请输入固定结算费率！');
      return;
    }
    if (!this.partnerType) {
      this.service.msgSrv.warning('请选择合伙人范围！');
      return;
    }
    if (!this.priority) {
      this.service.msgSrv.warning('请选择优先级！');
      return;
    }
    if (!this.sf?.value.ruleDescription) {
      this.service.msgSrv.warning('请输入规则说明！');
      return;
    }
    if (!this.remark) {
      this.service.msgSrv.warning('请输入备注！');
      return;
    }
    if (this.partnerType == '3' && this.partnerPeopleList?.length == 0) {
      this.service.msgSrv.warning('请选择合伙人！');
      return;
    }
    let real = false;
    if (this.configType == '2') {
      this.table.data.forEach((element: any) => {
        if (element.startAmount > element.endAmount) {
          real = true;
          return;
        }
      });
    }
    if (real) {
      this.service.msgSrv.warning('初始业务量不能超过到达业务量！');
      return;
    }

    const params = {
      accountingRate: this.accountingRate,
      configName: this.configName,
      configType: this.configType,
      rebateConfigLineDTO: this.table.data,
      priority: this.priority, // 优先级
      partnerIds: this.partnerId,
      ruleDescription: this.sf?.value.ruleDescription,
      remark: this.remark,
      partnerType: this.partnerType
    };
    console.log(params);

    this.service.request(this.service.$api_save_rebateConfig, params).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('新增成功！');
        this.router.navigate(['/partner/rebate/setting']);
      }
    });
  }
  initData(id: string) {
    this.service.request(this.service.$api_get_getPartnerRebateConfigInfo, { id: id }).subscribe((res: any) => {
      if (res) {
        this.configName = res?.configName;
        this.accountingRate = res?.accountingRate;
        this.accountingRate = res?.accountingRate;
        this.configType = res?.configType + '';
        this.tabelData = res?.partnerRebateConfigLineVOList;
        this.partnerType = res?.partnerType + '';
        this.partnerPeopleList = res?.partnerListVOs;
        this.priority = res?.priority + '';
        this.formData = { ruleDescription: res?.ruleDescription };
        this.remark = res.remark;
      }
    });
  }
  changePartner(value: any) {
    if (value == '3') {
      this.addStatus = true;
    } else {
      this.addStatus = false;
    }
  }
}
