import { Component, OnInit } from '@angular/core';
import {environment} from '../../../../../environments/environment';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {LocalStorageService} from '../../../../services/local-storage.service';
import {TyAgentOilStationService} from '../../../../services/ty-agent-oil-station.service';
import {TyAgentService} from '../../../../services/ty-agent.service';
import {TySalesmanService} from '../../../../services/ty-salesman.service';
import {OrganizationService} from '../../../../services/organization.service';
import {ADMIN_INFO_OBJECT} from '../../../../services/local-storage.namespace';
import {CommonsService} from '../../../../services/commons.service';
import {CompanyService} from '../../../../services/company.service';
import {MerchantService} from '../../../../services/merchant.service';
import {OrderOilService} from '../../../../services/order/order-oil.service';
import {OrderManageService} from '../../../../services/order/order-manage.service';

@Component({
  selector: 'app-order-oil-list',
  templateUrl: './order-oil-list.component.html',
  styleUrls: ['./order-oil-list.component.scss']
})
export class OrderOilListComponent implements OnInit {
  FILE_URL = environment.imageUrl;
  roleType;
  adminFlag;

  loadingObject = {
    title: "加载中...",
    status: false,
  };
  dataObject: any = {};
  tableLoading = true;
  searchForm: FormGroup;
  pageNum = 1;
  pageSize =  10;
  whereObject: any = {};
  isCollapse = false;

  refundModal = false;
  refundForm: FormGroup;

  orderDetailModal = false;
  orderDetailModalLoading = false;
  orderDetailObject: any = {
    tradeOrder: {},
    gasOrder: {},
  };

  orderStatusArray = [];
  companyArray = [];
  merArray = [];
  oilArray = [];
  orgIdArray = [];
  tyAgentArray = [];
  tySalesmanArray = [];

  constructor(private modal: NzModalService,
              private message: NzMessageService,
              private commonsService: CommonsService,
              private companyService: CompanyService,
              private merchantService: MerchantService,
              private store: LocalStorageService,
              private orderManageService: OrderManageService,
              private orderOilService: OrderOilService,
              private tyAgentService: TyAgentService,
              private tySalesmanService: TySalesmanService,
              private organizationService: OrganizationService,
              private form: FormBuilder) {
    this.roleType = Number(this.store.get(ADMIN_INFO_OBJECT)['secRole'].roleType);
    this.adminFlag = Number(this.store.get(ADMIN_INFO_OBJECT)['secUser'].adminFlag);
  }

  ngOnInit(): void {
    this.refundForm = this.form.group({
      orderNo: [{ value: null, disabled: true}, [Validators.required]],
      remarks: [null],
    });

    this.searchForm = this.form.group({
      orderNo: [null],
      gasOrgId: [null],
      gasAgentId: [null],
      gasSalesmanId: [null],
      salesmanName: [null],
      salesmanId: [null],
      gasStaffName: [null],
      gasOilNo: [null],
      storeName: [null],
      memPhone: [null],
      status: [null],
      createTimeArray: [null],
      payTimeArray: [null],
      refundTimeArray: [null],
      companyId: [null],
      merId: [null],
    });
    this.requestOrderData(1);

    this.commonsService.getDictionary("GAS_OIL_TYPE", data => {
      this.oilArray = data['return_data'];
    });
    this.commonsService.getDictionary("ORDER_OIL_STATUS", data => {
      this.orderStatusArray = data['return_data'];
    });

    if (this.roleType === 0 || this.roleType === 1) {
        this.companyService.selectCompanyList({ pageNum: 1,pageSize: 999 }, data => {
            this.companyArray = data['return_data']['list'];
        });
    }

    if (this.roleType === 5) {
      this.requestMerList(this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['id'])
    }

    if (this.roleType === 5 && this.adminFlag === 1) {
      this.requestOrgId(this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['id']);
    }

    if (this.roleType === 5 && this.adminFlag === 0) {
      this.requestAgent(this.store.get(ADMIN_INFO_OBJECT)['secUser'].organizationId);
    }

    if (this.roleType === 8) {
      this.requestSalesman(this.store.get(ADMIN_INFO_OBJECT)['highTyAgent'].id);
    }
  }

  /**
   * 请求订单数据
   */
  requestOrderData(pageNum: number) {
    this.tableLoading = true;
    this.whereObject['pageNum'] = pageNum;
    this.whereObject['pageSize'] = this.pageSize;
    this.orderOilService.getGasOrderList(this.whereObject, data => {
      if (data['return_code'] === '000000') {
        this.dataObject = data['return_data'];
      } else {
        this.modal.error(data['return_msg']);
      }
      this.tableLoading = false;
    });
  }

  /**
   * 请求数据
   */
  requestMerList(companyId: number) {
    if (companyId != null) {
      this.searchForm.controls['merId'].setValue(null);
      this.merchantService.getMerchantListByCompany(companyId, data => {
        if (data['return_code'] === '000000') {
          this.merArray = data['return_data'];
        } else {
          this.modal.error(data['return_msg']);
        }
        this.tableLoading = false;
      });

      this.requestOrgId(companyId);
    }
  }

  /**
   * 请求数据
   */
  requestOrgId(companyId: number) {
    this.organizationService.getOrganizationList(companyId, data => {
      if (data['return_code'] === '000000') {
        this.orgIdArray = data['return_data'];
      } else {
        this.modal.error(data['return_msg']);
      }
      this.tableLoading = false;
    });
  }

  /**
   * 请求数据
   */
  requestAgent(orgId: number) {
    if (orgId != null) {
      this.searchForm.controls['gasAgentId'].setValue(null);
      this.searchForm.controls['gasSalesmanId'].setValue(null);

      this.tyAgentService.getAgentList({ orgId: orgId, pageNum: 1, pageSize: 9999}, data => {
        if (data['return_code'] === '000000') {
          this.tyAgentArray = data['return_data']['list'];
        } else {
          this.modal.error(data['return_msg']);
        }
        this.tableLoading = false;
      });
    }
  }

  /**
   * 请求数据
   */
  requestSalesman(tyAgentId: number) {
    if (tyAgentId != null) {
      this.searchForm.controls['gasSalesmanId'].setValue(null);

      this.tySalesmanService.getSalesmanList({ tyAgentId: tyAgentId, pageNum: 1, pageSize: 9999}, data => {
        if (data['return_code'] === '000000') {
          this.tySalesmanArray = data['return_data']['list'];
        } else {
          this.modal.error(data['return_msg']);
        }
        this.tableLoading = false;
      });
    }
  }

  /**
   * 搜索
   * @param whereObject 条件
   */
  search(whereObject: object) {
    if (whereObject['createTimeArray'] != null) {
      whereObject['createTimeS'] = new Date(whereObject['createTimeArray'][0]).getTime();
      whereObject['createTimeE'] = new Date(whereObject['createTimeArray'][1]).getTime();
    } else {
      whereObject['createTimeS'] = null;
      whereObject['createTimeE'] = null;
    }

    if (whereObject['payTimeArray'] != null) {
      whereObject['payTimeS'] = new Date(whereObject['payTimeArray'][0]).getTime();
      whereObject['payTimeE'] = new Date(whereObject['payTimeArray'][1]).getTime();
    } else {
      whereObject['payTimeS'] = null;
      whereObject['payTimeE'] = null;
    }

    if (whereObject['refundTimeArray'] != null) {
      whereObject['refundTimeS'] = new Date(whereObject['refundTimeArray'][0]).getTime();
      whereObject['refundTimeE'] = new Date(whereObject['refundTimeArray'][1]).getTime();
    } else {
      whereObject['refundTimeS'] = null;
      whereObject['refundTimeE'] = null;
    }
    this.whereObject = whereObject;
    this.requestOrderData(1);
  }

  /**
   * 分页
   * @param pageSize
   */
  pageSizeChang(pageSize: number) {
    this.pageSize = pageSize;
    this.requestOrderData(1)
  }

  /**
   * 重置
   */
  resetSearchForm(): void {
    this.searchForm.reset();
  }

  /**
   * 搜索条件折叠
   */
  toggleCollapse(): void {
    this.isCollapse = !this.isCollapse;
  }

  /**
   * 导出订单
   */
  excelOrder() {
    this.loadingObject.status = true;
    this.loadingObject.title = '数据导出中...';

    this.orderOilService.exportGasOrderList(this.whereObject, data => {
      if (data['return_code'] === '000000') {
        window.location.href = this.FILE_URL + 'temporary/' + data['return_data'];
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
      this.loadingObject.status = false;
    });
  }

  /**
   * 打开订单详情
   */
  showOrderDetail(orderNo: string) {
    this.orderDetailModal = true;
    this.orderDetailModalLoading = true;

    this.orderOilService.getGasOrderDetail(orderNo, data => {
      if (data['return_code'] === '000000') {
        this.orderDetailObject = data['return_data'];
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
      this.orderDetailModalLoading = false;
    });
  }

  /**
   * 关闭订单详情
   */
  closeOrderDetail() {
    this.orderDetailModal = false;
  }

  /**
   * 打开退款模态框
   * @param orderNo
   */
  showRefund(orderNo: string) {
    this.refundForm.patchValue({ orderNo: orderNo})
    this.refundModal = true;
  }

  /**
   * 提交退款确认框
   */
  submitRefundConfirm() {
    for (const i in this.refundForm.controls) {
      this.refundForm.controls[i].markAsDirty();
      this.refundForm.controls[i].updateValueAndValidity();
    }
    if (this.refundForm.status == null || this.refundForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请填写所有必填项',
      });
      return;
    }
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确定对交易订号（'+this.refundForm.controls.orderNo.value+'）进行退款吗？',
      nzOnOk: () => this.submitRefund()
    });
  }

  /**
   * 提交退款
   * @param orderNo
   */
  submitRefund() {
    this.loadingObject.status = true;
    this.loadingObject.title = '处理中...';
    this.orderManageService.refundOrder(this.refundForm.controls.orderNo.value,this.refundForm.controls.remarks.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '操作成功',
        });
        this.requestOrderData(this.whereObject.pageNum);
        this.closeRefund();
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
      this.loadingObject.status = false;
    });
    this.refundModal = true;
  }

  /**
   * 关闭退款模态框
   * @param orderNo
   */
  closeRefund() {
    this.refundModal = false;
  }
}
