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';
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;
  //暂存准备删除的图片
  deleteList: Array<any> = [];
  headFlag: boolean = false;
  wxFlag: boolean = false;
  
  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'];
      }
    })
  }

  // 上传图片 add表示选了新的图片(可能是新增也可能是更换)
  chooseImg(picType, rechoseIndex?: any, picId?: any, add?: any) {
    if (picType == 'lifeImgUrl') {
      if (this.settingInfo.lifeImgUrls.length >= 3) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '生活照只能有三张，请将之前的删除！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
    }
    // 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) {
            THIS.serverId = response.serverId; // 返回图片的服务器端ID
            const m = {
              mediaId: response.serverId,
              origin: 'ydLife'
            };
            THIS.myService.mediaGet(m).subscribe(async e => {
              if (e['success']) {
                if (picType == 'headImgUrl') {
                  THIS.settingInfo.headImgUrl = e['data']['imgUrl'];
                  if (add == 'add' || add == 'change') {
                    THIS.headFlag = true;
                  } else {
                    THIS.headFlag = false;
                  }
                }
                if (picType == 'wxQRImgUrl') {
                  THIS.settingInfo.wxQRImgUrl = e['data']['imgUrl'];
                  if (add == 'add' || add == 'change') {
                    THIS.wxFlag = true;
                  } else {
                    THIS.wxFlag = false;
                  }
                }
                if (picType == 'lifeImgUrl') {
                  //传需要删除的图片位置
                  if (rechoseIndex || rechoseIndex == 0) {
                    //传了生活照id就是通过接口删除否则就是自己删除
                    if (picId) {
                      //暂存更换之前的图片
                      THIS.deleteList.push({ id: picId })
                      THIS.settingInfo.lifeImgUrls.splice(rechoseIndex, 1, { id: undefined, lifeImgUrl: e['data']['imgUrl'] });
                    } else {
                      THIS.settingInfo.lifeImgUrls.splice(rechoseIndex, 1);
                      THIS.settingInfo.lifeImgUrls.push({ id: undefined, lifeImgUrl: e['data']['imgUrl'] })
                    }
                  } else {
                    THIS.settingInfo.lifeImgUrls.push({ id: undefined, lifeImgUrl: e['data']['imgUrl'] })
                  }
                }
                THIS.changeDetectorRef.markForCheck();
                THIS.changeDetectorRef.detectChanges();
              } else {
                alert(e['message'])
              }
            });
          }
        });
      }
    });
  }

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

  //删除图片
  myImgDelete(picId, index?: any, deletePic?: any) {
    if (picId) {
      const param = {
        practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],
        fileId: Number(picId)
      }
      return new Promise((resolve, reject) => {
        this.myService.myImgDelete(param).subscribe((res) => {
          if (!res['success']) {
            alert(res['message'])
          } else {
            if (deletePic == 'deletePic') {
              this.toastDialog = true;
              this.toastInfo = {
                status: 1,
                msg: '删除成功！',
                timeout: 3000,
                align: 'center'
              };
              this.mySettingQuery();
            }
            resolve(res)
          }
        })
      })
    } else {
      this.settingInfo.lifeImgUrls.splice(index, 1);
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
    }
  }

  //用户点击保存时才真删除
  async mySettingSave() {
    let param;
    if (this.uploadType == 'headUrl') {
      if (this.headFlag) {
        param = {
          settingSave: 'img',
          headImgUrl: this.settingInfo.headImgUrl,
          practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],
          lifeImgUrls: []
        }
      } else {
        param = {
          settingSave: 'img',
          headImgUrl: undefined,
          practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],
          lifeImgUrls: []
        }
      }
    }
    if (this.uploadType == 'wxUrl') {
      if (this.wxFlag) {
        param = {
          settingSave: 'img',
          wxQRImgUrl: this.settingInfo.wxQRImgUrl,
          practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],
          lifeImgUrls: []
        }
      } else {
        param = {
          settingSave: 'img',
          wxQRImgUrl: undefined,
          practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],
          lifeImgUrls: []
        }
      }
    }
    if (this.uploadType == 'lifeUrl') {
      //如果有暂存图片删除
      if (this.deleteList.length > 0) {
        for (let j = 0; j < this.deleteList.length; j++) {
          await this.myImgDelete(this.deleteList[j]['id'])
        }
      }
      let lifeImgUrlsParam = [];
      for (let i = 0; i < this.settingInfo.lifeImgUrls.length; i++) {
        if (!this.settingInfo.lifeImgUrls[i].id) {
          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'],
        bioIntroTwo: this.settingInfo.bioIntroTwo
      }
    }
    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['success']) {
        alert('保存成功！')
        this.mySettingQuery();
        setTimeout(() => {
          if (this.uploadType == 'headUrl') {
            const lifeCustomerInfo = JSON.parse(localStorage.getItem('lifeCustomerInfo')) ? JSON.parse(localStorage.getItem('lifeCustomerInfo')) : null;
            lifeCustomerInfo.practitionerBasicInfo.headImagePath = this.settingInfo.headImgUrl;
            localStorage.setItem('lifeCustomerInfo', JSON.stringify(lifeCustomerInfo))
          }
        }, 300)
      } else {
        alert(res['message']);
      }
    })
  }

  controlWord(event) {
    if (this.settingInfo.bioIntroTwo) {
      if (this.settingInfo.bioIntroTwo.length >= 200) {
        // 删除:46 退格:8 回车:13
        if (!(event.which == '46' || event.which == '8' || event.which == '13')) {
          event.returnValue = false;
        }
      }

    }

  }
}
