const mixins = require('@/mixins/index.js')
const util = require('@/utils/util.js')
const Constants = require('@/utils/Constants.js');
const api = require('@/utils/api.js');

const app = getApp()

Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    // 路由
    routeObjName: 'setting',
    companyService: app.globalData['companyService'],
    curentAdItem: null,
    summaryInfo: {},
    buyBeginDate: null,
    noticeInfo: Constants.noticeInfo,
    staffCount: {
      maxNum: 1,
      webMaxNum: 0,
      wxMaxNum: 0
    },
    flgPrimary: false,
    // 是否是专业版
    proFlag: false,
    cardList: ['main'],
    contentObj: {
      main: [
        {
          code: 'gradeCode', type: 'tabs', tagList: [
            { name: mixins.$t('standardVersion'), id: Constants.gradeCode.STD },
            { name: mixins.$t('professionalVersion'), id: Constants.gradeCode.PRO }
          ], title: mixins.$t('gradeCode')
        },
        { code: 'cpName', type: 'str', required: 'true', title: mixins.$t('cpName') },
        { code: 'cpManager', type: 'str', required: 'true', title: mixins.$t('cpManager') },
        { code: 'cpPhone', type: 'phone', required: 'true', title: mixins.$t('cpPhone') },
        { code: 'cpSize', type: 'str', title: mixins.$t('cpSize') },
        { code: 'shopSize', type: 'str', title: mixins.$t('shopSize') },
        { code: 'feedback', type: 'textarea', title: mixins.$t('feedback') },
      ],
    },
  },
  /**
   * @desc : 改变产品类型
   * @author : 周兴
   * @date : 2024/4/1
   */
  changeTab(e) {
    if (e.detail.id == Constants.gradeCode.PRO) {
      this.setData({
        proFlag: true
      })
    }
  },
  /**
   * @desc : 阅读
   * @author : 周兴
   * @date : 2024/4/1
   */
  handleChangeCheckbox(e) {
    this.setData({
      flgPrimary: e.detail
    })
  },
  /**
 * @desc : 选择活动明细
 * @author : 周兴
 * @date : 2024/4/1
 */
  chooseAdItem(e) {
    let item = e.currentTarget.dataset.item;
    let summaryInfo = this.data.summaryInfo
    // 计算截止日期
    let months = item.validLong + item.extraLong
    let endDate = app.globalData.company.endDate
    console.log('buyBeginDate', this.data.buyBeginDate);
    endDate = new Date(this.data.buyBeginDate).addMonths(months)
    summaryInfo.endDate = endDate.toDateStr();
    this.setData({
      curentAdItem: item,
      summaryInfo: summaryInfo
    })
    // 计算金额
    this.countSummaryAmount(item);
  },
  /**
     * @desc : 计算金额
     * @author : 周兴
     * @date : 2024/4/1
     */
  countSummaryAmount() {
    let item = this.data.curentAdItem;
    let staffCount = this.data.staffCount;
    let summaryInfo = this.data.summaryInfo
    let amount = 0;
    // 先清空
    summaryInfo.amountInfo = '';
    // 共通用户
    if (staffCount.maxNum) {
      summaryInfo.amountInfo = item.stdPrice + '(打包价格)*' + staffCount.maxNum
      amount += item.stdPrice * staffCount.maxNum
    }
    // 手机端用户
    if (staffCount.wxMaxNum) {
      if (summaryInfo.amountInfo) {
        summaryInfo.amountInfo += ' + '
      }
      summaryInfo.amountInfo += item.wxPrice + '(手机端价格)*' + staffCount.wxMaxNum
      amount += item.wxPrice * staffCount.wxMaxNum
    }
    // 电脑端用户
    if (staffCount.webMaxNum) {
      if (summaryInfo.amountInfo) {
        summaryInfo.amountInfo += ' + '
      }
      summaryInfo.amountInfo += item.webPrice + '(电脑端价格)*' + staffCount.webMaxNum
      amount += item.webPrice * staffCount.webMaxNum
    }
    if (summaryInfo.amountInfo) {
      summaryInfo.amountInfo += ' = ' + amount + '(元)'
      summaryInfo.amount = amount;
    }
    this.setData({
      summaryInfo: summaryInfo
    })
    // 统计两端用户数
    this.countStaffInfo();
  },
  /**
   * @desc : 统计电脑端和手机端的用户数
   * @author : 周兴
   * @date : 2024/4/1
   */
  countStaffInfo() {
    let summaryInfo = this.data.summaryInfo;
    let staffCount = this.data.staffCount;
    if (!staffCount) {
      return;
    }
    let webNum = staffCount.webMaxNum + staffCount.maxNum
    let wxNum = staffCount.wxMaxNum + staffCount.maxNum
    summaryInfo.staffInfo = '可配置手机端授权' + wxNum + '个；电脑端授权' + webNum + '个（包含当前用户）'
    summaryInfo.webMaxNum = webNum
    summaryInfo.wxMaxNum = wxNum
    console.log('buyBeginDate', this.data.buyBeginDate);
    let buyBeginDate = new Date(this.data.buyBeginDate);
    summaryInfo.buyBeginDate = buyBeginDate.toDateStr();
    summaryInfo.extendDays = new Date(summaryInfo.endDate).dayDiff(buyBeginDate);
    console.log('eee', summaryInfo.amount, webNum + wxNum, summaryInfo.extendDays);
    // 计算一授权一天的单价
    let price = (summaryInfo.amount / (webNum + wxNum) / summaryInfo.extendDays).toFixed(2);
    summaryInfo.priceInfo = price

    this.setData({
      summaryInfo: summaryInfo
    })
  },
  /**
   * @desc : 修改用户数
   * @author : 周兴
   * @date : 2024/4/1
   */
  changeStaffCount(e) {
    let staffCount = this.data.staffCount
    let ds = e.currentTarget.dataset
    if (ds.type == 'wx') {
      staffCount.wxMaxNum = e.detail
    } else if (ds.type == 'web') {
      staffCount.webMaxNum = e.detail
    } else {
      staffCount.maxNum = e.detail
    }
    this.setData({
      staffCount: staffCount
    })
    // 计算金额
    this.countSummaryAmount();
  },
  /**
* @desc : 参数设置
* @date : 2024/2/1 15:49
* @author : 姜永辉
*/
  productDetail(e) {
    wx.navigateTo({
      url: this.data.route.productDetail.url,
      events: {
        // 回调后，在这里给页面赋值
        bandData: function (e) {
        }
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 TODO 测试例子url是写死的，实际中，需要从route中读取
        res.eventChannel.emit('params', {})
      }
    })
  },

  /**
   * @desc : 给表单赋值
   * @date : 2024/2/1 15:49
   * @author : 姜永辉
   */
  setValuesByEdit(data) {
    this.setData({
      formData: JSON.stringify(data)
    })
  },
  /**
   * @desc : 查询活动
   * @author : 周兴
   * @date : 2024/4/1
   */
  getActivity() {
    let params = {
      appCode: Constants.APP_CODE,
      activityTypeList: [Constants.kindCode.activityGrade, Constants.kindCode.activityMenu],
      gradeCode: app.globalData.company.gradeCode
    }
    let service = app.globalData['activityService']
    this.excute(service, service.selectActivityItems, params).then(res => {
      if (res.data.code == Constants.SUCESS_CODE) {
        if (res.data && res.data.data) {
          let activityTable = res.data.data;
          this.setData({
            activityTable: activityTable
          })
        }
      }
    });
  },


  /**
 * @desc   : 处理数据-查询后的逻辑
 * @author : 姜永辉
 * @date   : 2024/1/26 11:46
 */
  handleLoadData() {
    let data = {
      cpPhone: app.globalData.phoneNumber
    }
    this.setData({
      formData: JSON.stringify(data)
    })
    // 
  },

  /**
    * @desc : 保存的參數設置
    * @date : 2024/2/1 15:49
    * @author : 姜永辉
    */
  setParams(params) {
    params.cpId = null
    params.owner = app.globalData.user.userId // t_wx_user 表的id
    if (params.gradeCode == null) {
      params.gradeCode = Constants.gradeCode.STD
    }
    // 专业版
    if(this.data.proFlag){
      let summaryInfo = this.data.summaryInfo
      let curentAdItem = this.data.curentAdItem
      params.webMaxNum = summaryInfo.webMaxNum
      params.wxMaxNum = summaryInfo.wxMaxNum
      params.endDate = summaryInfo.endDate
      params.tradeNo = this.generateRandomNo();
      params.wxUserId = app.globalData.user.userId
      params.tradeAmount = summaryInfo.amount
      params.buyBeginDate = summaryInfo.buyBeginDate;
      params.buyEndDate = summaryInfo.endDate
      params.extendDays = summaryInfo.extendDays;
      params.buyLong = curentAdItem.activityItemName
    }
    return params
  },

  handleData(val) {
    console.log("handleData-创建商户");

    // // 调转主页
    // wx.reLaunch({
    //   url: '../../../../pages/welcome/welcome',
    // })
  },

  /**
  * @desc : 保存数据服务
  * @date : 2024/2/1 15:49
  * @author : 姜永辉
  */
  saveData() {
    // 专业版，成功后需要跳转支付
    if (this.data.proFlag) {
      return this.excute(this.data.companyService, this.data.companyService.registerCompany, this.data.params).then(res => {
        if (res.data.code == Constants.SUCESS_CODE) {
          // 成功后跳转支付
          this.toPay(res.data.data);
        }
      })
    }else{
      return this.excute(this.data.companyService, this.data.companyService.registerCompany, this.data.params)
    }
  },

  /**
  * @desc : 保存数据服务--校验
  * @date : 2024/2/1 15:49
  * @author : 姜永辉
  */
  validData() {
    if (!this.data.flgPrimary) {
      util.showToast('请勾选条款');
      return false
    }
    // 专业版必须要选择活动
    if (this.data.proFlag) {
      if (!this.data.curentAdItem) {
        util.showToast('请选择活动');
        return false
      }
      // 必须要选择一个授权
      let staffCount = this.data.staffCount
      if (!staffCount.maxNum && !staffCount.webMaxNum && !staffCount.wxMaxNum) {
        util.showToast('请选择一个授权');
        return false
      }
    }
    return true
  },
  /**
  * @desc : 初始化加载
  * @date : 2024/5/30 15:49
  * @author : 周兴
  */
  onLoad() {
    // 查询活动
    this.getActivity();
    this.setData({
      buyBeginDate: new Date().toDateStr()
    })
  },
})
