import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {IconService} from '../../../services/icon.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {CommonsService} from '../../../services/commons.service';
import {MerchantService} from '../../../services/merchant.service';
import {Router} from '@angular/router';
import {environment} from '../../../../environments/environment';
import {MerAmountService} from '../../../services/mer-amount.service';
import {MerchantTripartitePlatformService} from '../../../services/merchant-tripartite-platform.service';
import {MerAccountService} from '../../../services/mer-account.service';

@Component({
  selector: 'app-merchant-list',
  templateUrl: './merchant-list.component.html',
  styleUrls: ['./merchant-list.component.scss']
})
export class MerchantListComponent implements OnInit {
  WEB_SERVE_URL = environment.imageUrl;
  searchForm: FormGroup; // 搜索框
  requestData = []; // 列表数据
  total: number; // 页码
  pageNum = 1; // 页码
  pageSize = 10; // 条码
  loading = true;

  rechargeModal = false;
  rechargeForm: FormGroup; // 充值模态框

  tripartitePlatformModal = false;
  tripartitePlatformForm: FormGroup; // 充值模态框


  oilNoData: any = [];
  editOilNo: string;

  constructor(
      private form: FormBuilder,
      private merchant: MerchantService,
      private iconService: IconService,
      private message: NzMessageService,
      private merAccountService: MerAccountService,
      private tripartitePlatformService: MerchantTripartitePlatformService,
      private router: Router,
      private common: CommonsService,
      private modal: NzModalService,
  ) {
  }

  ngOnInit(): void {
    this.init();
  }

  public init(): void {
    this.searchForm = this.form.group({
      merchantKey: [null],
      merchantName: [null],
      telephone: [null],
      status: [null],
    });

    this.rechargeForm = this.form.group({
      merId: [null],
      merBalance: [{ value: 0, disabled: true}],
      amount: [null, [Validators.required]],
      marketingStatus: [0, [Validators.required]],
      marketingType: ['1'],
      marketingPrice: [null],
    });

    this.tripartitePlatformForm = this.form.group({
      merId: [null],
      platformType: ['1', [Validators.required]],
      platformMerName: [null, [Validators.required]],
      platformMerNumber: [null, [Validators.required]],
      profitSharingStatus: ['false', [Validators.required]],
      profitSharingRatio: [null],
      profitSharingReceiversNumber: [null],
      profitSharingReceiversName: [null],
    });

    this.common.getDictionary('GAS_OIL_TYPE', data => {
      for (let item of data['return_data']) {
        this.oilNoData.push({
          oilNo: item['codeValue'],
          oilNoName: item['codeName'],
          price: 0,
        })
      }
    });
    this.getRequest(true, this.searchForm.value);
  }

  // 查询列表
  public getRequest(reset: boolean = false, whereObject: object) {

    this.loading = false;
    if (reset) {
      this.pageNum = 1;
    }
    whereObject['pageNum'] = this.pageNum;
    whereObject['pageSize'] = this.pageSize;
    this.merchant.getMerchantList(whereObject, data => {
      if (data['return_code'] === '000000') {
        this.requestData = data['return_data'].list;
        this.total = data['return_data'].total;
      } else {
        this.message.error(data['return_msg']);
      }
    });
  }

  // 重置
  public resetForm(): void {
    this.searchForm.reset();
  }

  // 禁用商户
  public disableMerchant(id): void {
    const message =  '是否禁用商户';
    this.common.showConfirm(message, data => {
      if (data) {
        this.merchant.disableMerchant(id, dataReturn => {
          if (dataReturn['return_code'] === '000000') {
            this.message.success('操作成功');
            this.getRequest(false , this.searchForm.value);
          } else {
            this.message.warning(dataReturn['return_msg']);
          }
        });
      }
    });
  }

  // 启动商户
  public enableMerchant(id): void {
    const message =  '是否启用商户';
    this.common.showConfirm(message, data => {
      if (data) {
        this.merchant.enableMerchant(id, dataReturn => {
          if (dataReturn['return_code'] === '000000') {
            this.message.success('操作成功');
            this.getRequest(false , this.searchForm.value);
          } else {
            this.message.warning(dataReturn['return_msg']);
          }
        });
      }
    });
  }


  // 修改
  public getEdit(id: number): void {
    this.router.navigate(['/admin/merchant/merchant-edit'], {
      queryParams: {
        merchantId: id
      }
    }).then(r => console.log(r));
  }

  // 查看详情
  public getDetail(id: number): void {
    this.router.navigate(['/admin/merchant/merchant-detail'], {
      queryParams: {
        merchantId: id
      }
    }).then(r => console.log(r));
  }

  // 查看门店列表
  public getList(id: number , merchantName: string): void {
    this.router.navigate(['/admin/merchantStore/store-list'], {
      queryParams: {
        merchantId: id,
        name: merchantName,
      }
    }).then(r => console.log(r));
  }


  showRechargeModal(merId: number) {
    this.merAccountService.getMerAccount(merId, data => {
      let oilNoReliefPrice = data['return_data']['oilNoReliefPrice'];
      // 配置了加油减免
      if (oilNoReliefPrice != null) {
        this.rechargeForm.controls.marketingStatus.disable();
        this.rechargeForm.controls.marketingType.disable();
        this.rechargeForm.patchValue({ marketingStatus: 1, marketingType: '3'});
        let oilNoReliefPriceArray = JSON.parse(oilNoReliefPrice['oilNoReliefPrice']);
        for (let item of oilNoReliefPriceArray) {
          let oilNoData = this.oilNoData.find(o => o['oilNo'] == item['oilNo']);
          if (oilNoData != null) {
            oilNoData['price'] = item['price'];
          }
        }
      } else {
        this.rechargeForm.patchValue({ marketingStatus: 0, marketingType: '1'});
      }
      this.rechargeForm.patchValue({ merId: merId, merBalance: data['return_data']['amount']})
    });
    this.rechargeModal = true;
  }

  closeRechargeModal() {
    this.rechargeForm.controls.marketingStatus.enable();
    this.rechargeForm.controls.marketingType.enable();
    this.rechargeModal = false;
  }

  submitRecharge() {
    for (const i in this.rechargeForm.controls) {
      this.rechargeForm.controls[i].markAsDirty();
      this.rechargeForm.controls[i].updateValueAndValidity();
    }
    if (this.rechargeForm.status == null || this.rechargeForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请填写所有必填项',
      });
      return;
    }
    if (this.rechargeForm.value.marketingStatus == 1
      && (this.rechargeForm.value.marketingType == 1 || this.rechargeForm.value.marketingType == 2)) {
      if (this.rechargeForm.value.marketingPrice == null) {
        this.modal.warning({
          nzTitle: '提示',
          nzContent: '请填写所有必填项',
        });
        return;
      }
    }

    // 营销返点
    if (this.rechargeForm.controls.marketingType.value == 2) {
      this.rechargeForm.value.marketingPrice = this.rechargeForm.value.marketingPrice / 100;
    }

    // 加油减免
    if (this.rechargeForm.controls.marketingType.value == 3) {
      this.rechargeForm.value.marketingOilNoData = this.oilNoData;
    }

    this.rechargeForm.value.marketingStatus = this.rechargeForm.controls.marketingStatus.value;
    this.rechargeForm.value.marketingType = this.rechargeForm.controls.marketingType.value;
    this.merAccountService.recharge(this.rechargeForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '充值成功',
        });
        this.closeRechargeModal();
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });
  }


  showTripartitePlatformModal(merId: number) {
    this.tripartitePlatformService.getDetail(merId, 1, data => {
      if (data['return_data'] != null) {
        data['return_data']['platformType'] = String(data['return_data']['platformType']);
        data['return_data']['profitSharingStatus'] = String(data['return_data']['profitSharingStatus']);
        this.tripartitePlatformForm.patchValue(data['return_data']);
      } else {
        this.tripartitePlatformForm.patchValue( { merId: merId, platformType: '1', profitSharingStatus: 'false' });
      }
    });
    this.tripartitePlatformModal = true;
  }

  closeTripartitePlatformModal() {
    this.tripartitePlatformForm.reset();
    this.tripartitePlatformModal = false;
  }

  submitTripartitePlatform() {
    for (const i in this.tripartitePlatformForm.controls) {
      this.tripartitePlatformForm.controls[i].markAsDirty();
      this.tripartitePlatformForm.controls[i].updateValueAndValidity();
    }
    if (this.tripartitePlatformForm.status == null || this.tripartitePlatformForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请填写所有必填项',
      });
      return;
    }
    if (this.tripartitePlatformForm.value.profitSharingStatus === 'true'
      && (this.tripartitePlatformForm.value.profitSharingRatio == null ||
          this.tripartitePlatformForm.value.profitSharingReceiversNumber == null ||
          this.tripartitePlatformForm.value.profitSharingReceiversName == null)) {
        this.modal.warning({
          nzTitle: '提示',
          nzContent: '请填写所有必填项',
        });
        return;
    }

    this.tripartitePlatformService.editTripartitePlatform(this.tripartitePlatformForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '保存成功',
        });
        this.closeTripartitePlatformModal();
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });
  }


  // 跳转余额充值记录
  public jumpMerAccountRecord(id: number): void {
    this.router.navigate(['/admin/merchantAccount/account-record-list'], {
      queryParams: {
        merId: id
      }
    }).then(r => console.log(r));
  }

  startEdit(oilNo: string): void {
    this.editOilNo = oilNo;
  }

  stopEdit(): void {
    this.editOilNo = null;
  }


}

