/*******************************************************************************
 * Copyright(c) 2024 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述：表单-（基础数据）
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		周兴		  	2024-1-30    1.00		   	  新建
 *******************************************************************************/
const common = require('@/utils/common');
const Constants = require('@/utils/Constants');
const util = require('@/utils/util.js')
const chooseLocation = requirePlugin('chooseLocation');
const config = require('@/config/config.js')
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 区域
    cardList: {
      type: Array,
      value: []
    },
    // 表名，用于上传附件
    table: {
      type: String,
    },
    // 内容
    contentObj: {
      type: Object,
    },
    // 结果集
    value: {
      type: String,
      observer: function (newVal) {
        if (newVal) {
          this.setData({
            form: JSON.parse(newVal) || {}
          })
        } else {
          this.setData({
            form: {}
          })
        }
      }
    },
    routeObjName: {
      type: String,
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    // 是否显示pop
    show: false,
    mutishow: false,
    showDate: false,
    showDateTime: false,
    currentDate: new Date().getTime(),
    $t: app.globalData.lang,
    routeUrl: app.globalData['routeUrl'],
    item: null,
    index: null,
    card: null,
    // 下拉类型
    dropType: null,
    dropCode: null,
    dropName: null,
    // 根据值控制组件的显示隐藏
    changeObj: null,
    form: {},
    maxSize: Constants.uploadFileConfig.maxSize,
    checked: false
  },
  lifetimes: {
    attached: function () {},
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  pageLifetimes: {
    /**
     * @desc :  生命周期函数--监听页面显示
     * @author : 周兴
     * @date : 2024/2/19 12:16
     */
    show: function () {
      const location = chooseLocation.getLocation();
      let form = this.data.form
      if (location) {
        form['address'] = location;
        form['addressName'] = location.name;
        form['addressFull'] = form['addressFull'] ? form['addressFull'] : location.address + location.name;
        form['addressGcj02'] = {
          latitude: location.latitude,
          longitude: location.longitude
        };
        form['addressArea'] = {
          province: location.province,
          city: location.city,
          district: location.district == undefined || !location.district ? location.city : location.district
        }
        // 如果有校验信息就清除掉
        let card = this.data.card;
        let index = this.data.index;
        let contentObj = this.data.contentObj;
        if (card && contentObj[card][index]?.errMsg) {
          contentObj[card][index].errMsg = undefined;
          this.setData({
            contentObj: contentObj
          })
        }
      }
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * @desc   : 打开下拉
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    open(e) { 
      let item = e.currentTarget.dataset;
      this.setData({
        dropCode: item.key,
        dropName: item.name,
        dropType: item.type,
        index: item.index,
        card: item.card
      })
      console.log('ee', e);
      // 单选
      if (item.item.type == 'drop') {
        this.setData({
          show: true,
          changeObj: item.item.changeObj,
        })
        // 多选
      } else if (item.item.type == 'mutidrop') {
        this.setData({
          mutishow: true
        })
      } else if (item.item.type == 'choose') {
        let that = this
        console.log(item, this.data.routeObjName, this.data.routeUrl);
        that.setData({
          changeObj: item.item.changeObj,
        })
        // 跳转链接
        if (item.item.urlKey) {
          let route = this.data.routeUrl[this.data.routeObjName][item.item.urlKey]
          let url = route.url
          // TODO
          // url = '/package-base-select/pages/select-customers/select-customers'
          if (url) {
            wx.navigateTo({
              url: url,
              events: {
                // 回调后
                bindData: function (data) {  
                  let contentObj = that.data.contentObj
                  // 是否根据值进行控制其他组件显示、隐藏
                  let changeObj = that.data.changeObj
                  let key =  data.data.id;
                  let card = that.data.card;
                  if (changeObj && changeObj[key]) {
                    // 显示
                    if (changeObj[key]['visible']) {
                      changeObj[key]['visible'].forEach(it => {
                        let index = contentObj[card].findIndex(t => t.code == it)
                        console.log('index', index);
                        if (contentObj[card][index]) {
                          contentObj[card][index].hide = false
                        }
                      })
                    }
                    // 隐藏
                    if (changeObj[key]['hide']) {
                      changeObj[key]['hide'].forEach(it => {
                        let index = contentObj[card].findIndex(t => t.code == it)
                        console.log('index', index);
                        if (contentObj[card][index]) {
                          contentObj[card][index].hide = true
                        }
                      })
                    }
                  }

                  that.setData({
                    contentObj: contentObj
                  })
 

                  that.triggerEvent("chooseData", {
                    code: item.key,
                    data: data
                  })
                }
              },
              success: function (res) {
                console.log('item', that.data.form)
                let data = {
                  route: route,
                  formMode: item.item.formMode,
                  id: that.data.form[item.item.idKey],
                  chooseType: item.item.chooseType
                }
                if (that.data.form[item.item.code]) {
                  data[item.item.code] = that.data.form[item.item.code]
                }
                // 通过eventChannel向被打开页面传送数据
                // that.data.form.formMode = item.item.formMode
                // that.data.form.id = that.data.form[item.item.idKey]
                // that.data.form.chooseType = item.item.chooseType
                res.eventChannel.emit('params', data)
              }
            })
          }
        }
      }
    },
    /**
     * @desc   : 非空校验
     * @author : 周兴
     * @date   : 2024/2/20 11:46
     */
    validData() {
      let flag = true;
      let cardList = this.data.cardList;
      if (!cardList || cardList.length == 0) {
        return flag;
      }
      let form = this.data.form;
      let contentObj = this.data.contentObj;
      cardList.forEach(card => {
        if (contentObj[card]) {
          contentObj[card].forEach(item => {
            let title = this.$t(item.title ? item.title : item.code)
            // 如果必须输入，就要进行判断
            if (item.required && !form[item.code]) {
              item.errMsg = title + '不为空'
              flag = false;
            }
          })
        }
      })
      this.setData({
        contentObj: contentObj
      })
      return flag;
    },
    /**
     * @desc   : 选择数据
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    chooseData(e) {
      let contentObj = this.data.contentObj;
      let form = this.data.form
      if (e.detail.ids) {
        form[this.data.dropCode + 's'] = e.detail.ids;
        form[this.data.dropName + 's'] = e.detail.names;
      } else {
        form[this.data.dropCode] = e.detail.value;
        form[this.data.dropName] = e.detail.text;
      }
      let card = this.data.card;
      // 选择后清空校验提示信息
      if (card && contentObj[card][this.data.index]?.errMsg && e.detail) {
        contentObj[card][this.data.index].errMsg = undefined;
      }
      this.setData({
        value: JSON.stringify(form),
        form: form,
        contentObj: contentObj
      })
      // 是否根据值进行控制其他组件显示、隐藏
      let changeObj = this.data.changeObj
      let key = util.getKeyByValue(Constants.kindCode, e.detail.value);
      if (changeObj && changeObj[key]) {
        // 显示
        if (changeObj[key]['visible']) {
          changeObj[key]['visible'].forEach(it => {
            let index = contentObj[card].findIndex(t => t.code == it)
            console.log('index', index);
            if (contentObj[card][index]) {
              contentObj[card][index].hide = false
            }
          })
        }
        // 隐藏
        if (changeObj[key]['hide']) {
          changeObj[key]['hide'].forEach(it => {
            let index = contentObj[card].findIndex(t => t.code == it)
            console.log('index', index);
            if (contentObj[card][index]) {
              contentObj[card][index].hide = true
            }
          })
        }
      }

      this.setData({
        contentObj: contentObj
      })
      // 如果处理id，name还需要赋值其他，需要在页面事件中自行处理
      this.triggerEvent("chooseData", {
        code: this.data.dropCode,
        list: e.detail.list
      })
    },
    /**
     * @desc   : 打开日期pop
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    openDatePop(e) {
      let item = e.currentTarget.dataset;
      this.setData({
        showDate: true,
        index: item.index,
        key: item.key,
        card: item.card
      })
    },
    /**
     * @desc   : 关闭日期pop
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    cancelDatePop() {
      this.setData({
        showDate: false
      })
    },
    /**
     * @desc   : 选择日期
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    chooseDate(e) {
      let form = this.data.form;
      let index = this.data.index;
      let card = this.data.card;
      let code = this.data.key;
      form[code + '_time'] = e.detail
      form[code] = util.toDateStr(e.detail);
      let contentObj = this.data.contentObj;
      if (card && contentObj[card][index]?.errMsg && e.detail) {
        contentObj[card][index].errMsg = undefined;
      }
      this.setData({
        value: JSON.stringify(form),
        form: form,
        contentObj: contentObj,
        showDate: false
      })
    },
    /**
     * @desc   : 修改输入框的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    changeField(e) {
      let ds = e.currentTarget.dataset
      let key = ds.key
      let item = ds.item
      let form = this.data.form
      form[key] = e.detail
      let contentObj = this.data.contentObj;
      // 输入值后清空校验提示信息
      if (item.errMsg && e.detail) {
        contentObj[ds.card][ds.index].errMsg = undefined;
      }
      this.setData({
        value: JSON.stringify(form),
        form: form,
        contentObj: contentObj
      })
    },
    /**
     * @desc   : 清空输入框的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    clearField(e) {
      console.log('eee', e);
      let ds = e.currentTarget.dataset
      let key = ds.key
      let form = this.data.form
      form[key] = undefined
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
      // 如果要清除其他值，需要调用
      this.triggerEvent("clear", {
        code: ds.key
      })
    },
    /**
     * @desc   : 清空选单的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    clearChoose(e) {
      let ds = e.currentTarget.dataset
      let key = ds.key
      let name = ds.name
      let form = this.data.form
      form[key] = undefined
      form[name] = undefined
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
      // 如果要清除其他值，需要调用
      this.triggerEvent("clear", {
        code: ds.key
      })
    },
    /**
     * @desc   : 清空地址的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    clearAddress(e) {
      let form = this.data.form
      form['address'] = undefined
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
      // 如果要清除其他值，需要调用
      this.triggerEvent("clear", {
        code: ds.key
      })
    },
    /**
     * @desc   : 清空日期的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    clearDate(e) {
      let ds = e.currentTarget.dataset
      let key = ds.key
      let form = this.data.form
      form[key] = undefined
      form[key + '_time'] = undefined
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
    },
    /**
     * @desc   : 修改数值输入框的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    changeNumberField(e) {
      let ds = e.currentTarget.dataset
      let key = ds.key
      let item = ds.item
      let form = this.data.form
      form[key] = e.detail.value
      let contentObj = this.data.contentObj;
      // 输入值后清空校验提示信息
      if (item.errMsg && e.detail) {
        contentObj[ds.card][ds.index].errMsg = undefined;
      }
      this.setData({
        value: JSON.stringify(form),
        form: form,
        contentObj: contentObj
      })
    },
    /**
     * @desc   : 修改电话的值
     * @author : 周兴
     * @date   : 2024/2/2 11:46
     */
    changePhone(e) {
      let ds = e.currentTarget.dataset;
      let key = ds.key;
      let index = ds.index;
      let card = ds.card;
      let form = this.data.form
      form[key] = e.detail.detail
      let contentObj = this.data.contentObj;
      if (card && contentObj[card][index]?.errMsg && e.detail.detail) {
        contentObj[card][index].errMsg = undefined;
      }
      this.setData({
        value: JSON.stringify(form),
        form: form,
        contentObj: contentObj
      })
    },
    /**
     * @desc   : 给电话赋值错误信息
     * @author : 周兴
     * @date   : 2024/2/20 11:46
     */
    changePhoneblur(e) {
      let ds = e.currentTarget.dataset
      let errMsg = e.detail.errMsg;
      let card = ds.card;
      let index = ds.index;
      let contentObj = this.data.contentObj;
      if (errMsg && card && contentObj[card][index]) {
        contentObj[card][index].errMsg = errMsg;
        this.setData({
          errMsg: errMsg
        })
      }
      this.triggerEvent('changePhoneblur', e)
    },
    /**
     * @desc : 小程序地图调用
     * @author : 周兴
     * @date : 2024/2/18 18:16
     */
    onClickWxchartAddress(e) {
      // 跳转新建地图实例
      common.onClickWxchartAddress();
      let item = e.currentTarget.dataset;
      this.setData({
        index: item.index,
        card: item.card
      })
    },
    /**
     * @desc   : 改变选择框内容
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    onChange(e) {
      let key = e.currentTarget.dataset.key
      let checkFlag = e.currentTarget.dataset.value
      let form = this.data.form
      form[key] = !checkFlag
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
    },
    /**
     * @desc   : 改变选择框内容
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    changeTabs(e) {
      let key = e.currentTarget.dataset.key
      let id = e.detail.id
      let form = this.data.form
      form[key] = id
      this.setData({
        value: JSON.stringify(form),
        form: form
      })
    },

    /**
     * @desc   : 打开日期pop
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    openDatePopTime(e) {
      console.log('openDatePopTime')
      let item = e.currentTarget.dataset;
      this.setData({
        showDateTime: true,
        index: item.index,
        key: item.key,
        card: item.card
      })
    },
    /**
     * @desc   : 关闭日期pop
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    cancelDatePopTime() {
      this.setData({
        showDateTime: false
      })
    },
    /**
     * @desc   : 选择日期
     * @author : 周兴
     * @date   : 2024/1/26 11:46
     */
    chooseDateTime(e) {
      let form = this.data.form;
      let index = this.data.index;
      let card = this.data.card;
      let code = this.data.key;
      form[code + '_time'] = e.detail
      form[code] = util.formatDataTime(new Date(e.detail));
      let contentObj = this.data.contentObj;
      if (card && contentObj[card][index]?.errMsg && e.detail) {
        contentObj[card][index].errMsg = undefined;
      }
      this.setData({
        value: JSON.stringify(form),
        form: form,
        contentObj: contentObj,
        showDateTime: false
      })
    },
    /**
     * @desc   : 是点击事件
     * @author : 于继渤
     * @date   : 2024/1/26 11:46
     */
    onChangeCheckedBoxYes(e) {
      let form = this.data.form;
      let code = e.currentTarget.dataset.key;
      form[code] = e.detail
      this.setData({
        value: JSON.stringify(form),
        form: form,
      })
    },
    /**
     * @desc   : 否点击事件
     * @author : 于继渤
     * @date   : 2024/1/26 11:46
     */
    onChangeCheckedBoxNo(e) {
      let form = this.data.form;
      let code = e.currentTarget.dataset.key;
      form[code] = !e.detail
      this.setData({
        value: JSON.stringify(form),
        form: form,
      })
    },
    /**
     * @desc : 上传附件超出大小
     * @author : 周兴
     * @date : 2024/3/27 16:16
     */
    overSize(e) {
      util.showToast('文件超出' + Constants.uploadFileConfig.maxSizeMB);
    },
    /**
     * @desc : 上传附件
     * @author : 周兴
     * @date : 2024/3/27 16:16
     */
    afterRead(e) {
      // this.setData({
      //     uploadFileFlag:true
      // })
      const _this = this;
      const {
        file
      } = e.detail;
      // 配置存放的文件夹 公司code - 表名 - 年月 -- 日
      let folder = app.globalData.company.cpCode + '/' + this.data.table + '/' + new Date().toYearMonth2() + '/' + new Date().toDay()
      let url = config.upload_url;
      url = url.replace('mdm-server', 'mdm-server' + '-' + app.globalData.company.svcCode.replace('_', '-'))
      file.forEach(res => {
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        wx.uploadFile({
          url: url,
          filePath: res.path,
          name: 'file',
          formData: {
            'folder': folder
          },
          header: {
            'Authorization': 'Bearer ' + app.globalData.token
          },
          success(res) {
            let data = JSON.parse(res.data)
            if (data.code === 200) {
              _this.setData({
                uploadFileFlag: false
              })
              let form = _this.data.form
              let annexPaths = form['annexPaths'] || []
              data.data.url = config.image_url + data.data.path
              annexPaths.push(data.data)
              form.annexPaths = annexPaths;
              _this.setData({
                form: form,
                value: JSON.stringify(form)
              })
              console.log('ff', _this.data.form);
            }
          },
        })
      })
    },
    /**
     * @desc : 获取语言的方法
     * @author : 周兴
     * @date : 2024/1/19
     */
    $t(name) {
      if (this.data.$t[name]) {
        return this.data.$t[name];
      } else {
        return name;
      }
    },
  },
})