// pages/searchResult/searchResult.ts
import { info, list, etcData, evaluateLaunch, labelStatistics } from "../../apis/phone";
import { list as tagList } from "../../apis/tag";
import { bindPhoneList } from "../../apis/consumer";
import { sysConfig } from "../../apis/config";
const app = getApp<IAppOption>()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dialogComment: false,
    dialogCommentRecord: false,
    dialogToLogin: false,
    dialogInvite: false,
    dialogRealName: false,
    dialogTagRecord: false,
    consumer: {},
    listQuery: {
      current: 1,
      size: 99999,
      phone: undefined
    },
    userInfo: app.globalData.userInfo,
    tagList: [],
    tagedList: [],
    tagListOrigin: [],
    commentRecordList: [],
    form: {
      evaluateLabelIds: "",
      phone: "",
      score: 0
    },
    isBind: false,
  },
  handleCommentRecord() {
    const { userInfo, checkCondition } = this.data
    if (!userInfo) {
      this.setData({
        dialogToLogin: true,
      })
    } else if (userInfo.evaluatedTimes < checkCondition) {
      this.setData({
        dialogToLogin: true,
      })
    } else {
      this.setData({
        dialogCommentRecord: true,
        popup: true
      })
      wx.setPageStyle({
        style: {
          overflow: 'hidden'
        }
      })
      this.getCommentRecords()
    }
  },

  dialogCommentRecordClose() {
    wx.setPageStyle({
      style: {
        overflow: 'auto'
      }
    })
    this.setData({
      dialogCommentRecord: false,
      popup: false
    })
  },
  handleComment() {
    let { consumer, tagListOrigin, } = this.data


    let row = consumer.evaluateLabelIds ? consumer.evaluateLabelIds.split(',') : []
    // console.log(row);

    if (!consumer.evaluateLabelIds) {
      tagListOrigin.map((item: any) => {
        item.map((itm: any) => {
          itm.checked = false
        })
      })
    }

    let tagList = <any>[]
    tagListOrigin.map((o: any) => {
      o.map((g: any) => {
        row.map((item: any) => {
          if (g.id === item) {
            // o[idx].checked = true
            g.checked = true
            tagList.push(g)
          }
        })
      })
    })

    this.setData({
      dialogComment: true,
      tagList,
      tagListOrigin: tagListOrigin,
      form: { evaluateLabelIds: consumer.evaluateLabelIds || '', phone: '', score: consumer.evaluatedScore || 0 }
    })
    wx.setPageStyle({
      style: {
        overflow: 'hidden'
      }
    })
  },
  closeInvite() {
    console.log('closeInvite');
    this.setData({
      dialogInvite: false
    })
  },
  showDialogRealName() {
    this.setData({
      dialogRealName: true
    })
  },
  dialogRealNameClose() {
    this.setData({
      dialogRealName: false
    })
  },
  dialogCommentClose() {
    this.setData({
      dialogComment: false
    })
    wx.setPageStyle({
      style: {
        overflow: 'auto'
      }
    })
  },
  showToLogin() {
    this.setData({
      dialogToLogin: true
    })
  },
  dialogToLoginClose() {
    this.setData({
      dialogToLogin: false
    })
  },
  showDialogInvite() {
    this.setData({
      dialogInvite: true
    })
  },
  hideDialogInvite() {
    this.setData({
      dialogInvite: false
    })
  },
  getSysConfig() {
    console.log('getSysConfig');

    sysConfig().then(res => {
      console.log('###');
      console.log(res);
      this.setData({
        checkCondition: res.d.checkCondition
      })
    })
  },

  deleteTag(e) {
    const { item, id } = e.currentTarget.dataset
    let { tagList, tagListOrigin } = this.data
    console.log(item, id);

    tagListOrigin.map(o => {
      o.map(g => {
        if (g.id === item.id) {
          g.checked = false
        }
      })
    })
    // tagListOrigin.find(t => t.id === id).checked = false
    tagList = tagList.filter(item => item.id !== id);

    this.setData({
      tagList,
      tagListOrigin
    })
  },
  handleSelectedTag(e) {
    console.log(e);
    let { item } = e.currentTarget.dataset
    item.checked = true
    let { tagList, tagListOrigin } = this.data
    if (tagList.findIndex(m => m.id === item.id) >= 0) {

    } else {
      tagList.push(item)
      // tagListOrigin.find(t => t.id === item.id).checked = true
      tagListOrigin.map((t, index) => {
        console.log(t);
        t.map(g => {
          console.log(g);
          if (g.id === item.id) {
            g.checked = true
          }
        })
        // console.log(t.find((g, idx) => g.id === item.id), idx);


        // console.log(o.find(g => g.id === item.id),index);

        // o.find(g => g.id === item.id).checked = true
      })
    }

    this.setData({
      tagList,
      tagListOrigin
    })
  },

  getInfo() {
    console.log('getInfo');
    console.log('Authorization', wx.getStorageSync('Authorization'));
    console.log('global', app.globalData);


    info({ phone: this.data.phone, type: 1 }).then(res => {
      console.log('###getInfo');
      console.log(res);

      this.setData({
        consumer: res.d,
      })
      if (!res.d.evaluatedScore) {
        this.setData({
          dialogComment: true
        })
      }
    })
    console.log('getInfo-end');

  },
  getCommentRecords() {
    console.log('getCommentRecords');

    let payload = {
      ...this.data.listQuery,
      phone: this.data.phone
    }
    list(payload).then(res => {
      // console.log(res);
      this.setData({
        commentRecordList: res.d.records
      })
    })
    console.log('getCommentRecords-end');
  },
  getTagList() {
    console.log('getTagList');

    let payload = {
      ...this.data.listQuery,
      phone: this.data.phone
    }
    list(payload).then(res => {
      this.setData({
        tagedList: res.d.records,
        currentComment: res.d.records.find(item => item.consumerId === app.globalData.userInfo.id)
      })
    })
  },
  // handleEvaluateLaunch() {

  // },
  setStarNum(e) {
    console.log("获得的评分为", e.detail.starNum)
    // this
  },
  submitAvgComment() {
    console.log('submitAvgComment');
    const { phone, form, tagList, userInfo, consumer } = this.data

    let evaluateLabelIds = tagList.map(m => m.id).toString();

    let payload = {
      evaluateLabelIds,
      phone,
      score: consumer.totalAverage === 0 ? 3 : 3,
      sponsorPhone: userInfo.phone || undefined
    }
    // console.log(payload);

    evaluateLaunch(payload).then(res => {
      console.log(res);
      wx.showToast({
        icon: 'none',
        title: '提交成功'
      })
      this.setData({
        dialogComment: false
      })
      wx.setPageStyle({
        style: {
          overflow: 'hidden'
        }
      })
      this.getInfo()
    })
  },
  submitComment() {
    console.log('submitComment');
    const { phone, form, tagList, userInfo } = this.data
    let evaluateLabelIds = tagList.map(m => m.id).toString();
    if (form.score === 0) {
      wx.showToast({
        icon: 'none',
        title: '请选择评分'
      })
      return
    }
    let paylod = {
      evaluateLabelIds,
      phone,
      score: form.score,
      sponsorPhone: userInfo.phone || undefined
    }
    // console.log(paylod);

    evaluateLaunch(paylod).then(res => {
      console.log(res);
      wx.showToast({
        icon: 'none',
        title: '提交成功'
      })
      this.setData({
        dialogComment: false
      })
      this.getInfo()
    })
  },
  getTagListOrigin() {
    console.log('tagListOrigi1n');
    let tagListOrigin = []


    tagList({ current: 1, size: 99999 }).then(res => {
      console.log('###2');
      console.log(res);
      tagListOrigin = res.d
      let arr = []
      Object.keys(res.d).forEach(key => {
        // console.log(key);
        res.d[key].map(item => item.checked = false)
        arr.push(res.d[key])
      })

      this.setData({
        tagListOrigin: arr
      })
    })
    console.log('tagListOrigin1n-end');
  },
  getEtcData() {
    console.log('getEtcData-start');

    etcData(this.data.phone).then(res => {
      console.log(res);

    })
    console.log('getEtcData-end');

  },
  handleScore(e) {
    const { score } = e.detail
    let { form } = this.data
    form.score = score
    this.setData({
      form
    })
  },
  goReport(e) {
    const { id } = e.currentTarget.dataset

    wx.navigateToMiniProgram({
      appId: 'wx1da91ccb94c17c99',
      path: `/pages/reportPreview/reportPreview?type=2&active=3&source=2&id=${id}`,
      success(res) {
        // 打开成功
      }
    })
  },
  // getBindPhoneList() {
  //   bindPhoneList().then(res => {
  //     console.log(res);
  //     this.setData({
  //       isBind: res.d.length > 0
  //     })
  //   })
  // },
  handleBind() {
    if (this.data.accountList.length > 0) {
      wx.navigateTo({
        url: '/pages/my/my'
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/login'
      })
    }
  },
  goMy() {
    wx.redirectTo({
      url: '/pages/login/login'
    })
  },
  handleTagRecord() {

    const { userInfo, checkCondition } = this.data

    if (!userInfo) {
      this.setData({
        dialogToLogin: true,
      })
    } else if (userInfo.evaluatedTimes < checkCondition) {
      this.setData({
        dialogToLogin: true,
      })
    } else {
      this.setData({
        dialogTagRecord: true
      })
      wx.setPageStyle({
        style: {
          overflow: 'hidden'
        }
      })

      this.getTagRecord()
      // this.getCommentRecords()
    }
  },
  dialogTagRecordClose() {
    this.setData({
      dialogTagRecord: false
    })
  },
  getTagRecord() {
    labelStatistics(this.data.phone).then(res => {
      // console.log(res);
      let total = 0;
      res.d.map(item => {
        total = total + Number(item.contentCount)
      })
      this.setData({
        tagRecordList: res.d,
        tagRecordTotal: total
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      phone: options.phone
    })
    if (app.globalData.openId) {
      this.getInfo()
      this.getSysConfig()
      this.getTagListOrigin()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

    this.setData({
      now: Math.floor(new Date().getTime() / 1000)
    })

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      // userInfo: app.globalData.userInfo,
      userInfo: wx.getStorageSync('userInfo'),
      accountList: wx.getStorageSync("accountList")
    })

    // this.getBindPhoneList()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '您对我的印象评价是什么？'
        })
      }, 100)
    })
    return {
      title: '您对我的印象评价是什么？',
      path: `/pages/searchResult/searchResult&phone=${this.data.phone}`,
      promise
    }
  },
  // onShareTimeline() {
  //   const promise = new Promise(resolve => {
  //     setTimeout(() => {
  //       resolve({
  //         title: '你的印象评价是什么？',
  //         path: `/pages/searchResult/searchResult&phone=${this.data.phone}`,
  //       })
  //     }, 100)
  //   })
  // }
})