<template>
  <span></span>
</template>
<script>
  import utils from '@/utils.js'
  import CustomQuery from '@/services/CustomQuery'

  export default {
    name: 'HtSubtableBackfill',
    props: {
      customQuery: {
        type: Object,
        default: () => {
          return {}
        },
      },
      maxRow: Number,
      initFillDataType: String,
      extendProp: {
        type: Object,
        default: () => {
          return {}
        },
      },
      /**
       * 权限控制 permission参考结构，主要用来做子表行级权限控制 subRowAuth
  {
    "subRowAuth": {
        "fyspzt": {
            "total": [],
            "r": {
                "conditionString": "F_shzt = '待审核'",
                "conditionDes": "审核状态 = '待审核'",
                "conditionObj": "{\"junction\":\"and\",\"condition\":[{\"property\":\"F_shzt\",\"operator\":\"1\",\"dataType\":\"varchar\",\"value\":\"待审核\",\"compType\":\"2\",\"style\":\"left:150px; top:1px\",\"indexStr\":\"0\",\"format\":\"\",\"chooseDesc\":\"审核状态\"}]}"
            },
            "w": {
                "conditionString": "F_shzt = '审核通过'",
                "conditionDes": "审核状态 = '审核通过'",
                "conditionObj": "{\"junction\":\"and\",\"condition\":[{\"property\":\"F_shzt\",\"operator\":\"1\",\"dataType\":\"varchar\",\"value\":\"审核通过\",\"compType\":\"2\",\"style\":\"left:150px; top:1px\",\"indexStr\":\"0\",\"format\":\"\",\"chooseDesc\":\"审核状态\"}]}"
            }
        }
    },
    "fields": {
        "fybxnr": {
            "sqr": "w",
            "sqrq": "w",
            "bxze": "w",
            "bz": "w"
        },
        "fyspzt": {
            "fylx": "r",
            "fyje": "r",
            "fysm": "r",
            "shzt": "r"
        }
    },
    "table": {
        "fyspzt": {
            "hidden": false,
            "add": true,
            "del": false,
            "required": false
        }
    }
}
       */
      permission: {
        type: Object,
        default: () => {
          return {}
        },
      },
    },
    data() {
      return {
        dataPath: [],
      }
    },
    watch: {
      extendProp: function (newVal) {
        if (newVal) {
          this.initSubData()
        }
      },
    },
    mounted() {
      setTimeout(() => {
        this.initSubData()
      }, 500)
    },
    methods: {
      initSubData() {
        let _this = this
        if (
          !this.extendProp.initFillData ||
          this.extendProp.initFillData == 'false'
        ) {
          return
        }
        if (
          this.customQuery.alias &&
          this.customQuery.resultfield &&
          this.customQuery.resultfield.length
        ) {
          // 如果初始化类型是空时 此处不进行请求
          this.dataPath = this.getDataPath(this.customQuery.resultfield)
          const formInst = utils.getOnlineFormInstance(this)
          if (
            this.dataPath &&
            this.initFillDataType === 'empty' &&
            formInst['data'][this.dataPath[0]][this.dataPath[1]].length
          ) {
            return
          }
          let params = this.prepareLoadParams(this.customQuery.conditionfield)
          const loading = this.$loading({
            lock: true,
            text: '正在初始化子表数据...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          var tableSubRowAuth = null;
          if (this.permission && this.permission.subRowAuth && this.dataPath[1]) {
            var tableName = this.dataPath[1].replace('sub_', '');
            if (this.permission.subRowAuth[tableName]) {
              var json = {
                subRowAuth: this.permission.subRowAuth[tableName],
                resultfield: this.customQuery.resultfield,
              }
              tableSubRowAuth = JSON.stringify(json);
            }
          }
          CustomQuery.load(this.customQuery.alias, params, null, tableSubRowAuth).then(
            (rows) => {
              let data = []
              if (rows.constructor === Object) {
                data = rows.data
              } else {
                data = rows
              }
              if (loading) {
                loading.close()
              }
              this.backfill(
                this.maxRow > 0 && data.length > this.maxRow
                  ? data.splice(0, this.maxRow)
                  : data
              )
            },
            () => {
              if (loading) {
                loading.close()
              }
            }
          )
        }
      },
      getDataPath(data) {
        let path = []
        data.forEach((item) => {
          if (item.fieldPath) {
            let pathArr = item.fieldPath.split('.')
            if (pathArr.length > 1) {
              path = pathArr
            }
          }
        })
        return path
      },
      backfill(rows) {
        const formInst = utils.getOnlineFormInstance(this)
        if (this.customQuery.resultfield) {
          if (this.initFillDataType === 'cover') {
            formInst['data'][this.dataPath[0]][this.dataPath[1]] = []
          }
          rows &&
            rows.forEach((item) => {
              let subLineData = {}
              let targetArray = null
              this.customQuery.resultfield.forEach((sub) => {
                if (sub.fieldPath) {
                  targetArray = sub.fieldPath.split('.')
                  subLineData[targetArray[targetArray.length - 1]] =
                    !utils.isEmpty(item[sub.field]) ? item[sub.field] : ''
                }
              })
              if(item.sub_row_readonly != null && item.sub_row_readonly != undefined){
                subLineData.sub_row_readonly = item.sub_row_readonly;
              }
              // 得到子表的所有初始化字段
              let subInitData =
                formInst['data'][targetArray[0]].initData[
                  targetArray[1].replace('sub_', '')
                ] || {}
              delete subInitData.initData
              // 回填初始化
              if (subInitData && JSON.stringify(subInitData) != '{}') {
                subLineData = { ...subInitData, ...subLineData }
              }
              if (Object.keys(subLineData).length) {
                // 回填时默认展开逻辑添加
                subLineData.sub_guid = this.guid()
                this.$root.$emit('add-new-collapse-item', subLineData.sub_guid)
                formInst['data'][targetArray[0]][targetArray[1]].push(
                  subLineData
                )
              }
            })
        }
      },
      guid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
          /[xy]/g,
          function (c) {
            var r = (Math.random() * 16) | 0,
              v = c == 'x' ? r : (r & 0x3) | 0x8
            return v.toString(16)
          }
        )
      },
      // 准备查询参数
      prepareLoadParams(condition) {
        let params = {}
        if (condition && condition.length) {
          const formInst = utils.getOnlineFormInstance(this)
          condition.forEach((item) => {
            if (item.fieldPath) {
              let arr = item.fieldPath.split('.')
              if (!utils.isEmpty(formInst[arr[0]][arr[1]][arr[2]]))
                params[item.field] = formInst[arr[0]][arr[1]][arr[2]]
            }
          })
        }
        return params
      },
    },
  }
</script>
