import { Component, OnInit } from '@angular/core';
import { MyService } from '../my.service';
import { ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { SettingInfo } from '../../domain/settinginfo';
import { promise } from 'protractor';
declare const wx: any;
@Component({
  selector: 'ydlife-my-setting-detail',
  templateUrl: './my-setting-detail.component.html',
  styleUrls: ['./my-setting-detail.component.scss']
})
export class MySettingDetailComponent implements OnInit {
  settingInfo: SettingInfo = new SettingInfo();
  serverId: any;
  thumbnailPath: any;
  isNeedAlert: boolean;
  dialogInfo: any;
  uploadType: any;
  //控制上传数量
  uploadNumber: number;
  lifeUrlLen: number;
  //控制弹框
  toastDialog: boolean;
  toastInfo: any;
  constructor(private activateRoute: ActivatedRoute, private myService: MyService, private changeDetectorRef: ChangeDetectorRef) {

  }

  ngOnInit() {
    this.uploadType = this.activateRoute.snapshot.paramMap.get('uploadType');
    this.mySettingQuery();

  }

  //查询详情
  mySettingQuery() {
    const practitionerId = JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'];
    this.myService.mySettingQuery({ practitionerId: practitionerId }).subscribe((res) => {
      if (res['success']) {
        this.settingInfo = res['data'];
      }
    })
  }

  // 上传图片
  chooseImg(picType, rechose?: any, picId?: any) {
    // 5.1 拍照、本地选图
    const t = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        this.localId = res.localIds[0]; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
        const THIS = t;
        wx.uploadImage({
          localId: this.localId, // 需要上传的图片的本地ID，由chooseImage接口获得
          isShowProgressTips: 1, // 默认为1，显示进度提示
          success: function (response) {
            console.log(response)
            THIS.serverId = response.serverId; // 返回图片的服务器端ID
            const m = {
              mediaId: response.serverId
            };
            THIS.myService.mediaGet(m).subscribe(async e => {
              if (e['success']) {
                if (picType == 'headImgUrl') {
                  THIS.settingInfo.headImgUrl = e['data']['imgUrl'];
                }
                if (picType == 'wxQRImgUrl') {
                  THIS.settingInfo.wxQRImgUrl = e['data']['imgUrl'];
                }
                if (picType == 'lifeImgUrl') {
                  //rechose判断是重新上传
                  if (rechose) {
                    //传了生活照id就是通过接口删除否则就是自己删除
                    if (picId) {
                      THIS.myImgDelete(picId);
                    } else {

                    }
                  } else {
                    THIS.settingInfo.lifeImgUrls.push({ id: undefined, lifeImgUrl: e['data']['imgUrl'], selfAdd: THIS.settingInfo.lifeImgUrls.length })
                  }
                }
                THIS.changeDetectorRef.markForCheck();
                THIS.changeDetectorRef.detectChanges();
              } else {
                THIS.isNeedAlert = true;
                THIS.dialogInfo = {
                  title: null,
                  content: { value: e['message'], align: 'center' },
                  footer: [{ value: '我知道了', routerLink: '', className: 'weui-dialog__btn_primary' }],
                };
              }
            });
          }
        });
      }
    });
  }

  // 关闭弹窗
  getPopInfo() {
    this.isNeedAlert = false;
  }

  //删除生活照
  myImgDelete(picId) {
    if (picId) {
      const param = {
        practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],
        fileId: picId
      }
      // return new Promise((resolve, reject) => {
      this.myService.myImgDelete(param).subscribe((res) => {
        if (!res['success']) {
          this.isNeedAlert = true;
          this.dialogInfo = {
            title: null,
            content: { value: res['message'], align: 'center' },
            footer: [{ value: '我知道了', routerLink: '', className: 'weui-dialog__btn_primary' }],
          };
        } else {
          // resolve(this.mySettingQuery())
          this.mySettingQuery()
        }
      })
      // })
    }
  }

  mySettingSave() {
    let param;
    if (this.uploadType == 'headUrl') {
      param = {
        settingSave: 'img',
        headImgUrl: this.settingInfo.headImgUrl,
        practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],
      }
    }
    if (this.uploadType == 'wxUrl') {
      param = {
        settingSave: 'img',
        wxQRImgUrl: this.settingInfo.wxQRImgUrl,
        practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],

      }
    }
    if (this.uploadType == 'lifeUrl') {
      let lifeImgUrlsParam = [];
      for (let i = 0; i < this.settingInfo.lifeImgUrls.length; i++) {
        lifeImgUrlsParam.push(this.settingInfo.lifeImgUrls[i]['lifeImgUrl'])
      }
      param = {
        settingSave: 'img',
        lifeImgUrls: lifeImgUrlsParam,
        practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],
      }
    }
    if (this.uploadType == 'introduction') {
      param = {
        settingSave: 'intro',
        practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],
        bioIntro: this.settingInfo.bioIntro
      }
    }
    if (this.uploadType == 'switch') {
      param = {
        settingSave: 'isShow ',
        isNameShow: this.settingInfo.isNameShow,
        isMobileShow: this.settingInfo.isMobileShow,
        practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],

      }
    }
    alert(JSON.stringify(param))
    this.myService.mySettingSave(param).subscribe((res) => {
      if (res['data']) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '保存成功',
          timeout: 3000,
          align: 'center'
        };
        this.mySettingQuery();
      } else {
        // this.isNeedAlert = true;
        // this.dialogInfo = {
        //   title: null,
        //   content: { value: res['message'], align: 'center' },
        //   footer: [{ value: '我知道了', routerLink: '', className: 'weui-dialog__btn_primary' }],
        // };
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: res['message'],
          timeout: 3000,
          align: 'center'
        };
      }
    })
  }
}
