import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzModalService} from 'ng-zorro-antd';
import {ActivatedRoute, Router} from '@angular/router';
import {CommonsService} from '../../../services/commons.service';
import {OilPriceTaskService} from '../../../services/oil-price/oil-price-task.service';
import {LocalStorageService} from "../../../services/local-storage.service";
import {ADMIN_INFO_OBJECT} from "../../../services/local-storage.namespace";
import {OilPriceOfficialService} from '../../../services/oil-price/oil-price-official.service';
import {data} from 'jquery';

@Component({
  selector: 'app-oil-price-task-edit',
  templateUrl: './oil-price-task-edit.component.html',
  styleUrls: ['./oil-price-task-edit.component.scss']
})
export class OilPriceTaskEditComponent implements OnInit {
  dataFrom: FormGroup;
  btnLoading = false;

  oilNoArray = [];
  priceTypeArray = [];
  regionArray = [];
  gasArray = [];

  secUserObjectType: number;

  constructor(private formBuilder: FormBuilder,
              private modal: NzModalService,
              private oilPriceTaskService: OilPriceTaskService,
              private oilPriceOfficialService: OilPriceOfficialService,
              private activatedRoute: ActivatedRoute,
              private commonsService: CommonsService,
              private localStorageService: LocalStorageService , // 请求缓存
              private router: Router) {
      this.secUserObjectType = Number(this.localStorageService.get(ADMIN_INFO_OBJECT)['secUser']['objectType']);
  }

  ngOnInit(): void {

    this.dataFrom = this.formBuilder.group({
      oilNo: [null, [Validators.required]],
      priceOfficial: [{ value: 0, disabled: true}, [Validators.required]],
      gasPrice: [{ value: 0, disabled: true}, [Validators.required]],
      priceType: [null, [Validators.required]],
      price: [0, [Validators.required]],
      executionType: ['1', [Validators.required]],
      startTime: [null],
      regionId: [null],
      merStoreIdArray: [[]],
    });

    // 管理员
    if (this.secUserObjectType === 0) {
      // 价格类型  1. 国标价   2. 油站价  3. 优惠幅度
      this.priceTypeArray.push({ codeValue: 1, codeName: '国标价' });
      this.priceTypeArray.push({ codeValue: 2, codeName: '油站价' });
      this.priceTypeArray.push({ codeValue: 3, codeName: '平台优惠'});

      // 获取全部省级地区
      this.commonsService.getProvinceList(data => {
        this.regionArray = data['return_data'];
      });

      this.commonsService.getGasSelectList( data => {
        this.gasArray = data['return_data'];
      });

      // 分公司
    } else if (this.secUserObjectType === 1) {
      // 价格类型  1. 国标价   2. 油站价  3. 平台优惠  4. 油站直降
      this.priceTypeArray.push({ codeValue: 1, codeName: '国标价' });
      this.priceTypeArray.push({ codeValue: 2, codeName: '油站价' });
      this.priceTypeArray.push({ codeValue: 3, codeName: '平台优惠'});

      this.regionArray.push({ regionId: this.localStorageService.get(ADMIN_INFO_OBJECT)['bsCompany']['regionId'],
                              regionName: this.localStorageService.get(ADMIN_INFO_OBJECT)['bsCompany']['regionName'] });

      this.commonsService.getGasSelectList( data => {
        this.gasArray = data['return_data'];
      });

      // 商户
    } else if (this.secUserObjectType === 2) {
      this.priceTypeArray.push({ codeValue: 2, codeName: '油站价' });

      this.commonsService.getGasSelectList( data => {
        this.gasArray = data['return_data'];
      });

      // 加油站
    } else if (this.secUserObjectType === 3) {
      this.priceTypeArray.push({ codeValue: 2, codeName: '油站价' });
      this.priceTypeArray.push({ codeValue: 4, codeName: '油站直降' });

      this.dataFrom.patchValue({ merStoreIdArray: [ this.localStorageService.get(ADMIN_INFO_OBJECT)['merchantStore']['id'] ] });
    }

    this.commonsService.getDictionary('GAS_OIL_TYPE', data => {
      this.oilNoArray = data['return_data'];
    });

  }

  /**
   * 提交表单
   */
  submitFrom() {
    for (const i in this.dataFrom.controls) {
      this.dataFrom.controls[i].markAsDirty();
      this.dataFrom.controls[i].updateValueAndValidity();
    }
    if (this.dataFrom.status == null || this.dataFrom.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请规范填写所有的必填项信息',
      });
      return;
    }

    if (this.dataFrom.value.priceType == 1) {
      this.modal.confirm({
        nzTitle: '确定将国标价调整为'+this.dataFrom.controls.price.value +'元吗？',
        nzOkText: '确定',
        nzOnOk: () => this.submitData(),
        nzCancelText: '取消',
      });

    } else if (this.dataFrom.value.priceType == 2) {
      this.modal.confirm({
        nzTitle: '确定将油站价调整为'+this.dataFrom.controls.price.value +'元吗？',
        nzOkText: '确定',
        nzOnOk: () => this.submitData(),
        nzCancelText: '取消',
      });

    } else if (this.dataFrom.value.priceType == 3) {
      this.modal.confirm({
        nzTitle: '确定已选择的加油站，补贴'+this.dataFrom.controls.price.value +'元吗？',
        nzOkText: '确定',
        nzOnOk: () => this.submitData(),
        nzCancelText: '取消',
      });

    } else if (this.dataFrom.value.priceType == 4) {
      this.modal.confirm({
        nzTitle: '确定油站价直降'+this.dataFrom.controls.price.value +'元吗？<br>直降后的油站价'+this.dataFrom.controls.gasPrice.value+"元",
        nzOkText: '确定',
        nzOnOk: () => this.submitData(),
        nzCancelText: '取消',
      });
    }
  }

  /**
   * 提交数量
   */
  submitData() {
    const dataFromValue = this.dataFrom.value;
    const dataArray = [];

    if (dataFromValue.priceType === '1') {
      dataArray.push({
        regionId: dataFromValue.regionId,
        oilNo: dataFromValue.oilNo,
        priceType: dataFromValue.priceType,
        price: dataFromValue.price,
        executionType: dataFromValue.executionType,
        startTime: dataFromValue.startTime,
      });
    } else {
      for (const storeId of this.dataFrom.value.merStoreIdArray) {
        dataArray.push({
          merStoreId: storeId,
          oilNo: dataFromValue.oilNo,
          priceType: dataFromValue.priceType,
          price: dataFromValue.price,
          executionType: dataFromValue.executionType,
          startTime: dataFromValue.startTime,
        });
      }
    }

    this.btnLoading = true;
    this.oilPriceTaskService.batchAddTask(dataArray, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '添加成功',
          nzOnOk: () => this.router.navigateByUrl('admin/gas-oil-price/task-list')
        });
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
      this.btnLoading = false;
    });
  }

  /**
   * 价格类型
   * @param type
   */
  selectPriceType(type: number) {
    if (type == 4) {
      this.priceChange(0);
    }
  }
  /**
   * 选中油号
   * @param oilNo
   */
  selectOilNo(oilNo: number) {
    if (this.secUserObjectType === 3) {
      this.oilPriceOfficialService.getOilPriceOfficialDetail(this.localStorageService.get(ADMIN_INFO_OBJECT)['merchantStore']['regionId'], oilNo, data => {
        if (data['return_code'] === '000000') {
          if (data['return_data'] != null) {
            this.dataFrom.patchValue({ priceOfficial: data['return_data']['priceOfficial'],
                                             gasPrice: data['return_data']['priceOfficial']});
            this.priceChange(0);
          }
        }
      });
    }
  }

  /**
   * 执行价格变化
   * @param price
   */
  priceChange(price: number) {
    if (this.dataFrom.value.priceType == 4) {
       let price = parseFloat((this.dataFrom.controls.priceOfficial.value - this.dataFrom.controls.price.value).toFixed(2));
       this.dataFrom.patchValue({gasPrice: price})
    }
  }

}
