// nova-tourism/components/dev-route/index.js
let Parse = getApp().Parse;
const company = getApp().globalData.company
const uid = Parse.User.current()?.id
const req = require('../../../utils/request')
Component({
  //字段编辑对象示例：
  // edit_field_map: {
  //   isRecom:{
  //     isHide:true,//是否隐藏 - 此项非DevRouter编辑
  //     disabled: true,//禁止编辑
  //     required: true,//必填项
  //     default:true,//默认值
  //   },
  // }, 
  /**
   * 组件的属性列表
   */
  properties: {
    rid: null, //devRouter的id
    object_id: null, //编辑的objcetId
    edit_field_map: null, //字段编辑对象
    is_btn: null, //是否显示提交按钮（save当前对象）
  },

  /**
   * 组件的初始数据
   */
  data: {
    color: '#46a9a4', //主题色
    text_color: 'black', //文字颜色
    editMap: {},
    editFields: [], //编辑对象列表
    isShowPointer: false, //指针弹框
    pointerList: [], //指针列表
    pointer_val: null, //搜索指针的关键字
    fieldIndex: null, //当前操作的编辑对象index
    timeout: null, //指针搜索框计时器
    is_btn: null, //是否显示提交按钮（save当前对象）
    queryParamsData: null, //当前编辑的对象（不存在则 new）
  },

  lifetimes: {
    detached: function () {},
    attached: async function () {
      console.log(`
      //字段编辑对象示例：
      // edit_field_map: {
      //   isRecom:{
      //     isHide:true,//是否隐藏 - 此项非DevRouter编辑
      //     disabled: true,//禁止编辑
      //     required: true,//必填项
      //     default:true,//默认值
      //   },
      // }, 
      `)
      this.getToken()
      setTimeout(() => {
        this.refersh()
      }, 800);
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    async refersh() {
      let {
        is_btn
      } = this.properties
      this.setData({
        is_btn
      })
      await this.getDevRoute()
      this.getDataItem()
    },
    /**获取devRoute */
    async getDevRoute() {
      let {
        rid,
        edit_field_map
      } = this.properties
      console.log(edit_field_map)

      let query = new Parse.Query('DevRoute')
      let d = await query.get(rid)
      let devRoute = d?.toJSON()
      console.log(devRoute)
      let editMap = {}
      let editFieldsList = []
      for (let i in devRoute?.editFields) {
        let item = devRoute?.editFields[i]
        if (edit_field_map && item.key in edit_field_map) { //如果当前字段存在于父组件传递的默认编辑字段之内
          if (('isHide' in edit_field_map[item.key]) && edit_field_map[item.key]['isHide']) {} else { //排除isHide为true的字段,其他字段使用父组件默认编辑
            for (let map_key in edit_field_map[item.key]) {
              devRoute.editFields[i][map_key] = edit_field_map[item.key][map_key]
            }
            editFieldsList.push(devRoute.editFields[i])
            editMap[item.key] = {
              type: item.type,
              val: item.default || null
            }
          }
        } else {
          editFieldsList.push(devRoute.editFields[i])
          editMap[item.key] = {
            type: item.type,
            val: item.default || null
          }
        }
      }
      console.log(editFieldsList)
      this.setData({
        devRoute,
        className: d?.get('pageUrl')?.split('/')?.pop(),
        editFields: editFieldsList,
        editMap
      })
    },
    /**获取数据*/
    async getDataItem() {
      let {
        object_id
      } = this.properties
      if (!object_id) return
      let {
        className,
        editMap,
        editFields
      } = this.data
      let pointerKeys = editFields.filter(item => item.type == 'Pointer' || item.view == 'pointer-array')?.map(item => item.key)
      let query = new Parse.Query(className)
      for (let i in pointerKeys) {
        query.include(pointerKeys[i])
      }
      let d = await query.get(object_id)
      if (!d?.id) return
      let dataItem = d?.toJSON()
      for (let i in editFields) {
        let item = editFields[i]
        if (item.view == 'edit-image') {
          if (item.type == 'String') { //单张图片
            editMap[item.key].val = dataItem[item.key] ? [{
              url: dataItem[item.key]
            }] : item.default || null
          }
          if (item.type == 'Array') { //数组图片
            if (dataItem[item.key] && dataItem[item.key]?.length > 0) {
              editMap[item.key].val = dataItem[item.key]?.map(item => {
                return {
                  url: item
                }
              })
            } else {
              editMap[item.key].val = item.default || []
            }

          }
        } else {
          if (item.type == 'Pointer') { //指针类型
            let text = dataItem[item.key]?.storeName || dataItem[item.key]?.title || dataItem[item.key]?.name || dataItem[item.key]?.orderNum || dataItem[item.key]?.mobile
            editMap[item.key].text = text
          } else if (item.type == 'Array' && item.view == 'pointer-array') { //数组指针
            let text = []
            for (let x in dataItem[item.key]) {
              let xtem = dataItem[item.key][x]
              text.push(xtem?.storeName || xtem?.title || xtem?.name || xtem?.orderNum || xtem?.mobile)
              editMap[item.key].text = text
            }
          }
          editMap[item.key].val = dataItem[item.key] || item.default || null
        }
      }
      this.setData({
        dataItem,
        editMap,
        queryParamsData: d
      })
    },
    /** 获取token 上传图片所需*/
    async getToken() {
      let res = await Parse.Cloud.run('qiniu_uptoken', {
        company: company
      })
      this.setData({
        uploadURL: res.zoneUrl,
        domain: res.domain,
        uptokenURL: res.uptoken,
      })
    },
    /** textarea改变 - String类型*/
    changeTextarea(e) {
      let {
        editMap
      } = this.data
      console.log(e)
      let {
        key
      } = e.currentTarget.dataset
      let {
        value
      } = e.detail
      editMap[key].val = value
      this.setData({
        editMap
      })
    },

    /**上传单张图片 - String类型 */
    changeFile(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key
      } = e.currentTarget.dataset
      console.log(e.detail[0])
      editMap[key].val = e.detail
      this.setData({
        editMap
      })
    },
    /**单选框改变 - String类型 */
    radioChange(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key
      } = e.currentTarget.dataset
      editMap[key].val = e.detail
      this.setData({
        editMap
      })
    },
    /** 数字输入框改变 - Number类型*/
    changeNumber(e) {
      let {
        editMap
      } = this.data
      console.log(e)
      let {
        key
      } = e.currentTarget.dataset
      let {
        value
      } = e.detail
      editMap[key].val = value
      this.setData({
        editMap
      })
    },
    /**开关改变 */
    switchChange(e) {
      let {
        editMap
      } = this.data
      console.log(e)
      let {
        key
      } = e.currentTarget.dataset
      editMap[key].val = e.detail
      this.setData({
        editMap
      })
    },
    /**上传多张图片 - Array类型 */
    changeFile_array(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key
      } = e.currentTarget.dataset
      editMap[key].val = e.detail
      this.setData({
        editMap
      })
    },
    /**添加文本 - Array类型 */
    addTextarea(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key
      } = e.currentTarget.dataset
      editMap[key].val = [...(editMap[key].val || []), e.detail.value]
      this.setData({
        editMap
      })
    },
    /**删除文本 - Array类型 */
    delTextarea(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key,
        index
      } = e.currentTarget.dataset
      editMap[key].val?.splice(index, 1)
      this.setData({
        editMap
      })
    },
    /**指针弹框-开 */
    async openPointer(e) {
      let {
        editFields
      } = this.data
      let {
        index
      } = e.currentTarget.dataset
      if (editFields[index].disabled) {
        wx.showToast({
          title: `无法编辑${editFields[index].name}`,
          icon: 'none'
        })
        return
      }
      this.setData({
        fieldIndex: index,
        pointerList: [],
        pointer_val: '',
        isShowPointer: true
      })
      this.getPointerItem()
    },
    /**指针弹框-关 */
    closePointer() {
      this.setData({
        isShowPointer: false
      })
    },
    /**选中指针 */
    checkPointer(e) {
      let {
        editFields, //编辑对象列表
        pointerList, //指针列表
        fieldIndex, //当前操作的编辑对象index
        editMap,
      } = this.data
      let {
        index
      } = e.currentTarget.dataset
      let editField = editFields[fieldIndex]
      let p_item = pointerList[index]
      console.log(pointerList)
      pointerList = pointerList?.map((item, i) => {
        if (i == index) {
          item['dev_router_check'] = true
        } else {
          item['dev_router_check'] = false
        }
        return item
      })
      editMap[editField.key].val = {
        className: editField?.targetClass,
        __type: 'Pointer',
        objectId: p_item?.objectId
      }
      editMap[editField.key].text = p_item.storeName || p_item.name || p_item.title || p_item.orderNum || p_item.mobile
      this.setData({
        editMap,
        pointerList
      })
      this.closePointer()
    },
    /**选中指针 - Array */
    checkPointer_Array(e) {
      let {
        editFields, //编辑对象列表
        pointerList, //指针列表
        fieldIndex, //当前操作的编辑对象index
        editMap,
      } = this.data
      let {
        index
      } = e.currentTarget.dataset
      let editField = editFields[fieldIndex]
      let p_item = pointerList[index]
      console.log(editField, p_item)
      pointerList[index]['dev_router_check'] = !(pointerList[index]['dev_router_check'] || false)
      let checkList = pointerList?.filter(item => item.dev_router_check) || []
      editMap[editField.key].val = checkList.map(p_item => {
        return {
          className: editField?.targetClass,
          __type: 'Pointer',
          objectId: p_item?.objectId
        }
      })
      editMap[editField.key].text = checkList.map(p_item => {
        return p_item.storeName || p_item.name || p_item.title || p_item.orderNum || p_item.mobile
      })
      console.log(editMap)
      this.setData({
        editMap,
        pointerList
      })
    },
    /**删除数组指针 */
    delPointer(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key,
        index
      } = e.currentTarget.dataset
      editMap[key].text?.splice(index, 1)
      editMap[key].val?.splice(index, 1)
      this.setData({
        editMap
      })
    },
    /**指针搜索框变化 */
    async valChange(e) {
      await this.setData({
        pointer_val: e.detail || ''
      })
      let {
        timeout
      } = this.data
      clearTimeout(timeout)
      timeout = setTimeout(async () => {
        await this.setData({
          pointerList: [],
        })
        this.getPointerItem()
      }, 1000);
      this.setData({
        timeout
      })
    },
    /** 查询指针*/
    async getPointerItem() {
      let {
        editMap,
        pointer_val,
        pointerList,
        fieldIndex,
        editFields
      } = this.data
      let editField = editFields[fieldIndex]
      let sql = `SELECT DISTINCT(column_name) FROM information_schema.columns
      WHERE table_name = '${editField.targetClass}'`
      let columnList = await req.customSQL(sql)
      let where = {
        "$or": []
      }
      if (editField?.queryParams?.where?.type) {
        where = JSON.parse(JSON.stringify(editField?.queryParams?.where || {})) || {}
      } else {
        where = {}
      }
      console.log(where)
      for (let i in columnList) {
        let item = columnList[i]
        if (item.column_name == 'company') where['company'] = {
          "$eq": company
        }
        if (item.column_name == 'isDeleted') where['isDeleted'] = {
          "$ne": true
        }
        if (pointer_val) {
          if (item.column_name == 'name') where['$or'] = [...(where['$or'] || []), {
            "name": {
              "$regex": `${pointer_val}`
            }
          }]
          if (item.column_name == 'title') where['$or'] = [...(where['$or'] || []), {
            "title": {
              "$regex": `${pointer_val}`
            }
          }]
          if (item.column_name == 'mobile') where['$or'] = [...(where['$or'] || []), {
            "mobile": {
              "$regex": `${pointer_val}`
            }
          }]
          if (item.column_name == 'orderNum') where['$or'] = [...(where['$or'] || []), {
            "orderNum": {
              "$regex": `${pointer_val}`
            }
          }]
          if (item.column_name == 'storeName') where['$or'] = [...(where['$or'] || []), {
            "storeName": {
              "$regex": `${pointer_val}`
            }
          }]
        }
      }
      console.log(where)
      let queryParams = {
        where,
        limit: 20,
        skip: pointerList?.length || 0
      }
      let query = new Parse.Query.fromJSON(editField?.targetClass, queryParams)
      query.descending('createdAt')
      let d = await query.find()
      if (!d?.length) {
        wx.showToast({
          title: '没有更多了',
          icon: 'none'
        })
        return
      }
      editMap[editField.key].text
      let list = d?.map(item => {
        let obj = item.toJSON()
        if (editMap[editField.key]?.text && editMap[editField.key]?.text?.length > 0) {
          if (editField.type == 'Array') {
            let x = editMap[editField.key].val.findIndex(val_item => val_item.objectId == obj.objectId)
            if (x != -1) {
              obj.dev_router_check = true
            }
          } else {
            if (editMap[editField.key].val.objectId == obj.objectId) {
              obj.dev_router_check = true
            }
          }
        }
        return obj
      })
      this.setData({
        pointerList: [...(pointerList || []), ...(list || [])]
      })
    },

    /**选择位置 */
    chooseGeoPoint(e) {
      let {
        editMap
      } = this.data
      let {
        key
      } = e.currentTarget.dataset
      let that = this
      wx.chooseLocation({
        latitude: 0,
        longitude: 0,
        success: (res) => {
          console.log(res)
          editMap[key].val = {
            __type: 'GeoPoint',
            latitude: res.latitude || 0,
            longitude: res.longitude || 0
          }
          editMap[key].text = (res.address || '') + (res.name || '')
          that.setData({
            editMap
          })
        }
      })
    },
    /** textarea改变 - Object类型内属性值改变 */
    changeJsonTextarea(e) {
      let {
        editMap
      } = this.data
      console.log(e)
      let {
        key,
        json_key
      } = e.currentTarget.dataset
      let {
        value
      } = e.detail
      let obj = editMap[key].val||{}
      obj[json_key] = value
      editMap[key].val=obj
      this.setData({
        editMap
      })
    },

    //#region Object类型 规格specMap编辑  ================================================
    /**添加属性 - specMap字段 */
    addKey_ShopGoods_specMap(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key
      } = e.currentTarget.dataset
      let text = e.detail.value
      let obj = {
        value: null,
        price: null,
        vipPrice: null,
      }
      if (!editMap[key].val?.specList || editMap[key].val?.specList?.length <= 0) editMap[key].val = {
        specList: []
      }
      editMap[key].val['specList'] = [...(editMap[key]?.val?.specList || []), text]
      editMap[key].val[text] = [...(editMap[key]?.val[text] || []), obj]
      this.setData({
        editMap
      })
    },
    /**删除属性 - specMap字段 */
    delKey_ShopGoods_specMap(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key,
        spec_index
      } = e.currentTarget.dataset
      console.log(key, spec_index)
      let text = editMap[key].val.specList[spec_index]
      console.log(text)
      delete editMap[key].val[text]
      editMap[key].val.specList.splice(spec_index, 1)
      this.setData({
        editMap
      })
    },
    /**设置specMap-value */
    setValue(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key,
        spec,
        spec_map_index
      } = e.currentTarget.dataset
      editMap[key].val[spec][spec_map_index].value = e.detail.value
      this.setData({
        editMap
      })
    },
    /**设置specMap-price */
    setPrice(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key,
        spec,
        spec_map_index
      } = e.currentTarget.dataset
      editMap[key].val[spec][spec_map_index].price = parseFloat(e.detail.value || 0)
      this.setData({
        editMap
      })
    },
    /**设置specMap-vipPrice */
    setVipPrice(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key,
        spec,
        spec_map_index
      } = e.currentTarget.dataset
      editMap[key].val[spec][spec_map_index].vipPrice = parseFloat(e.detail.value || 0)
      this.setData({
        editMap
      })
    },
    /**添加specMap里面key内的item */
    addSpecMap(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key,
        spec
      } = e.currentTarget.dataset
      let obj = {
        value: null,
        price: null,
        vipPrice: null,
      }
      editMap[key].val[spec] = [...(editMap[key].val[spec] || []), obj]
      this.setData({
        editMap
      })
    },
    /**删除specMap里面key内的item */
    delSpecMapItem(e) {
      console.log(e)
      let {
        editMap
      } = this.data
      let {
        key,
        spec,
        spec_map_index
      } = e.currentTarget.dataset
      editMap[key].val[spec].splice(spec_map_index, 1)
      this.setData({
        editMap
      })
    },
    //#endregion ShopGoods表specMap字段编辑 end ================================================

    /**提交 */
    async submit() {
      let {
        editMap,
        queryParamsData,
        className,
        editFields
      } = this.data
      console.log(editMap)
      let editMapParse = {}
      if (!queryParamsData?.id) {
        let NewClass = Parse.Object.extend(className)
        queryParamsData = new NewClass()
        queryParamsData.set('company', {
          className: 'Company',
          __type: 'Pointer',
          objectId: company
        })
      }
      for (let i in editFields) {
        let item = editFields[i]
        if (item.required && ((!editMap[item.key].val) || editMap[item.key].val?.length <= 0)) {
          wx.showToast({
            title: `${item.name} 为必填项，请补充`,
            icon: 'none'
          })
          return
        }
        if ((!editMap[item.key].val) || editMap[item.key].val?.length <= 0) continue
        if (item.type == 'Number') {
          editMapParse[item.key] = parseFloat(editMap[item.key].val)
        }
        else if(item.type == 'Pointer'){
          editMapParse[item.key] = {__type:'Pointer',className:item?.targetClass,objectId:editMap[item.key].val?.objectId}
        }
        else if (item.type == 'String' && item.view == 'edit-image') {
          editMapParse[item.key] = editMap[item.key].val[0]?.url
        } else if (item.type == 'Array') {
          if (item.view == 'edit-image') {
            editMapParse[item.key] = editMap[item.key].val?.map(val_item => val_item.url)
          } else if (item.view == 'pointer-array') {
            editMapParse[item.key] = editMap[item.key].val?.map(val_item => {
              return {
                __type: 'Pointer',
                className: item.targetClass,
                objectId: val_item.objectId
              }
            })
          }
        }
        console.log(item.key, editMapParse[item.key] || editMap[item.key].val)
        queryParamsData.set(item.key, editMapParse[item.key] || editMap[item.key].val)
      }
      console.log(editMap)
      console.log(queryParamsData)
      await queryParamsData.save()
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })
      }, 1000);
    },
    /** 复制*/
    copyStr(e) {
      let {
        str
      } = e.currentTarget.dataset
      if (str) {
        wx.setClipboardData({
          data: str,
          success: () => {
            wx.showToast({
              title: '复制成功',
              icon: 'success',
            });
          },
          fail: (err) => {
            console.error('复制失败:', err);
            wx.showToast({
              title: '复制失败',
              icon: 'none',
              duration: 2000
            });
          }
        });
      } else {
        wx.showToast({
          title: '文本为空',
          icon: 'none',
          duration: 2000
        });
      }
    },
  }
})