import { Component, OnInit } from '@angular/core';
import {environment} from '../../../../environments/environment';
import {FormBuilder, FormGroup} from '@angular/forms';
import {MerchantService} from '../../../services/merchant.service';
import {IconService} from '../../../services/icon.service';
import {NzMessageService} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import {CommonsService} from '../../../services/commons.service';
import {OrderService} from '../../../services/order.service';
import {CompanyService} from '../../../services/company.service';
import {ADMIN_INFO_OBJECT} from '../../../services/local-storage.namespace';
import {LocalStorageService} from '../../../services/local-storage.service';
import {MerchantStoreService} from '../../../services/merchant-store.service';
import {RechargeService} from '../../../services/recharge.service';

@Component({
  selector: 'app-pre-order',
  templateUrl: './pre-order.component.html',
  styleUrls: ['./pre-order.component.scss']
})
export class PreOrderComponent implements OnInit {

  WEB_SERVE_URL = environment.baseUrl;
  FILE_URL = environment.imageUrl;
  searchForm: FormGroup; // 搜索框
  requestData = []; // 列表数据
  companyData = []; // 列表数据
  merchantData = []; // 列表数据
  merchantStoreData = []; // 列表数据
  total: number; // 页码
  pageNum = 1; // 页码
  pageSize = 10; // 条码
  loading = true;
  id: number; // 订单ID
  isVisible = false;
  isVisibleFail = false;
  isVisibleDetail = false;
  preUserRemark: string;
  statusFailDesc: string;
  reachAddress: string;
  reachTime;
  roleType: number;
  orderDetail: any = {
    highChildOrderList: [{
      goodsName: ''
    }]
  };
  preOrderDetail: any = {};
  constructor(
      private form: FormBuilder,
      private order: OrderService,
      private iconService: IconService,
      private message: NzMessageService,
      private router: Router,
      private company: CompanyService,
      private recharge: RechargeService,
      private merchant: MerchantService,
      private store: LocalStorageService, // 数据请求
      private merchantStore: MerchantStoreService,
      private common: CommonsService
  ) {
  }

  ngOnInit(): void {
    this.init();
    this.roleType = this.store.get(ADMIN_INFO_OBJECT)['secRole']['roleType'];
    const whereObject = {};
    whereObject['pageNum'] = 1;
    whereObject['pageSize'] = 10000;
    this.company.selectCompanyList(whereObject, data => {
      if (data['return_code'] === '000000') {
        this.companyData = data['return_data'].list;
      } else {
        this.message.error(data['return_msg']);
      }
    });

    if (this.roleType === 5) {
      this.getMerchantListByCompany(this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['id']);
    } else {
      this.getMerchantListByCompany(this.searchForm.value.companyId);
    }

  }

  public init(): void {
    this.searchForm = this.form.group({
      companyId: [null],
      merchantId: [null],
      merchantStoreId: [null],
      orderNo: [null],
      preOrderNo: [null],
      userPhone: [null],
      preUserName: [null],
      goodsType: [null],
      goodsName: [null],
      status: [null],
      createTime: [null]
    });
    this.getRequest(true, this.searchForm.value);
  }

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

    if (whereObject['createTime'] != null && whereObject['createTime'].length !== 0) {
      whereObject['createTimeS'] = whereObject['createTime'][0].getTime();
      whereObject['createTimeE'] = whereObject['createTime'][1].getTime();
    }


    this.loading = false;
    if (reset) {
      this.pageNum = 1;
    }
    whereObject['pageNum'] = this.pageNum;
    whereObject['pageSize'] = this.pageSize;
    this.order.getListPreOrder(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 getMerchantListByCompany(companyId: number): void {
    this.merchant.getMerchantListByCompany(companyId, data => {
      if (data['return_code'] === '000000') {
        if (data['return_code'] === '000000') {
          this.merchantData = data['return_data'];
        } else {
          this.message.error(data['return_msg']);
        }
      } else {
        this.message.error(data['return_msg']);
      }
    });
  }


  // 查询商户
  public getMerchantStoreById(merchantIds: number): void {

    const params = {
      pageNum: 1,
      pageSize: 1000000,
      merchantId: merchantIds
    };

    this.merchantStore.getStoreListByCompany(params, data => {
      if (data['return_code'] === '000000') {
          this.merchantStoreData = data['return_data'].list;
      } else {
        this.message.error(data['return_msg']);
      }
    });
  }

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


  // 查看详情
  public getDetail(orderId: number , id: number): void {
    this.order.getOrderById(orderId , data => {
      if (data['return_code'] === '000000') {
          console.log(data);
          this.orderDetail = data['return_data'];
      } else {
        this.message.error(data['return_msg']);
      }
    });
    this.order.getPreOrderById(id , data => {
      if (data['return_code'] === '000000') {
        this.preOrderDetail = data['return_data'];
        console.log(this.preOrderDetail);
      } else {
        this.message.error(data['return_msg']);
      }
    });
    this.isVisibleDetail = true;
  }

  // 下载模板
  downloadTemplate(whereObject) {
    if (whereObject['createTime'] != null && whereObject['createTime'].length !== 0) {
      whereObject['createTimeS'] = whereObject['createTime'][0].getTime();
      whereObject['createTimeE'] = whereObject['createTime'][1].getTime();
    }
    this.order.exportListPreOrder(whereObject, data => {
      if (data['return_code'] === '000000') {
        window.location.href = this.FILE_URL + data['return_data'];
      } else {
        this.message.error(data['return_msg']);
      }
    });
  }


  getPreSuccess(id): void {
    this.id = id;
    this.isVisible = true;
  }

  getPreFail(id: number): void {
    this.id = id;
    this.isVisibleFail = true;
  }

  handleOkFail(): void {
    this.common.showConfirm('是否确认预约失败', item => {
      if (item) {
        const params = {
          id: this.id ,
          statusFailDesc: this.statusFailDesc
        };
        this.order.preOrderFail(params, data => {
          if (data['return_code'] === '000000') {
            this.getRequest(false, this.searchForm.value);
            this.isVisibleFail = false;
            this.message.success('操作成功');
          } else {
            this.message.error(data['return_msg']);
          }
        });
      }
    });
  }

  handleCancelFail() {
    this.isVisibleFail = false;
  }

  handleOk(): void {
    this.common.showConfirm('是否确认预约', item => {
      if (item) {
        const params = {
          id: this.id ,
          reachAddress: this.reachAddress,
          reachTime: this.reachTime,
          preUserRemark: this.preUserRemark,
        };
        this.order.preOrderSuccess(params, data => {
          if (data['return_code'] === '000000') {
            this.getRequest(false, this.searchForm.value);
            this.isVisible = false;
            this.message.success('预约成功');
          } else {
            this.message.error(data['return_msg']);
          }
        });
      }
    });
  }


  public postRefund(orderNo): void {
    this.common.showConfirm('确认订单申请退款', item => {
      if (item) {
        this.recharge.postRefund({
          refundSource: 2 ,
          sourceOrderNo: orderNo
        }, data => {
          if (data['return_code'] === '000000') {
            this.message.success('申请成功');
            this.getRequest(false, this.searchForm.value);
          } else {
            this.message.error(data['return_msg']);
          }
        });
      }
    });
  }


}
