export default {
  props: {
    value: {
      type: [Object, Array, String, Number],
      required: false,
    },
    title: {
      type: String,
      default: '基础数据选择',
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '',
    },
    maxTagCount: {
      type: Number,
    },
    tableKey: {
      type: String,
      default: () => 'id',
    },
    treeKey: {
      type: String,
      default: () => 'id',
    },
    searchPlaceholder: {
      type: String,
      default: '',
    },
    tableName: {
      type: String,
      required: true
    },
    /**
     * 组织机构权限类型，默认访问权限
     */
    authType: {
      type: String,
      default: 'ACCESS',
    },
    /**
     * 版本日期， 格式 9999-12-31
     */
    versionDate: {
      type: String,
      default: '',
    },
    modalWidth: {
      type: [Number, String],
      default: 970,
    },
    inputLabel: {
      type: String,
      default: 'name',
      validator: (value) => {
        return value === 'code' || value === 'name' || value === 'codeName'
      },
    },
    isLeaf: {
      type: Boolean,
      default: false
    },
    filterFormular: {
      type: String,
      default: ''
    },
    filterFormularSP: {
      type: String,
      default: ''
    },
    billdefineName: {
      type: String,
      default: ''
    },
    billId: {
      type: String,
      default: ''
    },
    isFilter: {
      type: Boolean,
      default: false
    },
    bill: {
      type: Object,
      default: () => { }
    },
    defineObject: {
      type: Object,
      default: () => {}
    },
    rowIndex: {
      type: Number,
      default: -1
    },
    isCode: {
      type: Boolean,
      default: false
    },
    isObject: {
      type: Boolean,
      
      default: false
    },
    tableStyle: {
      type: Boolean,
      default: false
    },
    groupTableName: {
      type: Object,
      default: () => ({
        tableName:'',
        groupFieldName:'',
        define:''
      })
    },
    structtype: {
      type: Number,
      default: -1
    },
    treeTableName: {
      type: String,
      default: ''
    },
    hideSelected: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      tempFilterFormular: '', // 临时公式，方便处理，不然直接修改props会有问题
      removeMasterListener: null,
      removeSubListener: null
    }
  },
  watch: {
    filterFormular: {
      handler(val) {
        this.tempFilterFormular = val;
      },
      immediate: true
    }
  },
  computed: {
    isOrg() {
      return this.tableName === 'MD_ORG'
    },
  },
  beforeDestroy () {
    this.removeMasterListener && this.removeMasterListener()
    this.removeSubListener && this.removeSubListener()
  },
  methods: {
    async getOrg(param) {
      let result = await GMS.$http
        .post('/org/data/list', param)
        .then((res) => {
          const { rows, rs } = res.data
          return rows
        })
        .catch((err) => {
          console.error('获取组织机构失败：' + JSON.stringify(err))
          console.log('error', err)
        })
      return result
    },
    handleFormular () {
      if (this.filterFormular && Object.keys(this.bill).length > 0) {
        let reg = this.filterFormular.match(/\s[A-Za-z]\w*\.[A-Za-z]\w*\s*(?=\=)/)
        if (!reg) {
          return
        }
        let changeKey = reg[0].trim()
        let oldChangeKey = ''
        let currentFiledList = this.defineObject.field.split('.') // 当前要过滤的字段
        let catchFiledList = changeKey.split('.') // 条件字段
        let initValue = this.bill.getMasterData().getValue(changeKey) // 初始的时候的替换真实的值
        initValue = this.handleNv(initValue)
        this.tempFilterFormular = this.filterFormular.replace(changeKey, initValue)
        oldChangeKey = initValue
        if (this.bill.getTableType(currentFiledList[0]).type === 'sub' && this.bill.getTableType(catchFiledList[0]).type === 'sub') {
          this.$Message.warning('暂不支持子表关联子表!')
          return
        }
        if (this.bill.getTableType(catchFiledList[0]).type === 'sub') {
          let that = this
          that.removeSubListener = this.bill.addSubDataChangeListenr("detailList", {
            changeSubDataValue: function (value, index, key) {
              if (key === changeKey) {
                const newChangeKey = that.handleNv(value)
                that.tempFilterFormular = that.tempFilterFormular.replace(oldChangeKey, newChangeKey)
                oldChangeKey = newChangeKey
                if (that.getBaseDataList) {
                  that.getBaseDataList()
                }
              }
            }
          })
        } else if (this.bill.getTableType(catchFiledList[0]).type === 'master') {
          this.removeMasterListener = this.bill.getMasterData().addListener(changeKey, {
            valueChange: function (nv, ov) {
              const newChangeKey = this.handleNv(nv)
              this.tempFilterFormular = this.tempFilterFormular.replace(oldChangeKey, newChangeKey)
              oldChangeKey = newChangeKey
              if (this.getBaseDataList) {
                this.getBaseDataList()
              }
              // 替换然后查询
            }.bind(this)
          })
        }
      }
    },
    handleNv (nv) {
      let newChangeKey = null
      if (Object.prototype.toString.call(nv) === '[object Object]') {
        newChangeKey = nv.code
      } else {
        switch (typeof nv) {
          case 'string':
            if(isNaN(nv)&&!isNaN(Date.parse(nv))){
              newChangeKey = Date(nv)
            } else {
              newChangeKey = nv.replace(/\"/, '\"')
            }
            break
          case 'number':
            newChangeKey = nv
            break
          default:
            newChangeKey = nv
            break
        }
      }
      newChangeKey = `\"${newChangeKey}\"`
      return newChangeKey
    },
    getBaseData(postData, urlParam, isInit = false) {
      let url = ''
      let postParam = {}
      if (this.isFilter && !isInit) {
        let newParam = {}
        if (this.bill && this.bill.getBuillData) {
          delete postData.expression
          delete postData['BI-SYNTAX']

          const getParamBill = () => {
            let bill = this.bill.getBuillData && this.bill.getBuillData()
            if (bill&&bill.id) {
              bill.id = this.billId
            }
            return bill
          }

          newParam = {
            baseDataDto: postData,
            filterFormular: this.filterFormularSP,
            billdefineName: this.billdefineName,
            billId: this.billId,
            bill: getParamBill(),
            rowIndex: this.rowIndex
          }
        }
        url = urlParam || `/rbcfunc/baseData/list`
        if (urlParam) {
          postParam = JSON.parse(JSON.stringify(postData))
        } else {
          postParam = JSON.parse(JSON.stringify(newParam))
        }
      } else {
        url = urlParam || `/baseData/data/list`
        postParam = JSON.parse(JSON.stringify(postData))
      }

      return GMS.$http
        .post(url, JSON.stringify(postParam), {
          headers: {
            post: {
              'Content-Type': 'application/json',
            },
          },
        })

    },

  }
}


