<template>
  <div>
    <el-card v-for="(module, index) in modules" :key="index" class="es-box-card">
      <div slot="header" class="es-box-card--header">
        <span>{{ module.moduleName }}</span>
        <el-button v-if="module.dataFrom.value === 'fromInterface'" :loading="queryLoading(module.id)"
                   @click="callInterface(module)">
          {{ module.interfaceButtonName || '获取数据' }}
        </el-button>
      </div>

      <div class="es-card--content">
        <component :is="components[index].component" :id="components[index].id"
                   :ref="components[index].ref"
                   v-bind="buildProps(module)"
                   v-on="$listeners"/>
      </div>
    </el-card>
  </div>
</template>

<script lang="jsx">
import {packages} from '../../index'
import business   from '../hooks/business'
import {TempType} from "../../../api/easyData";
import { getVarType } from '../../../utils/utils';

export default {
  name: "TemplateView",
  mixins: [business],
  inject: ['_tempV'],
  props: {
    modules: {type: [Object, Array]},
    oneModuleName: {type: String},
    oneModuleId: {type: String},
    current: {type: Number, default: 0},
    saveData: {type: Object},
    errorMessage: {type: Object},
    bizParams: {type: Object},
    formData: {type: Object} //外部传入的初始化数据
  },
  data() {
    return {
      components: [],
      showSubmit: true,
      btnLoading: false
    }
  },
  watch: {
    modules: {
      handler(newVal, oldVal) {
        if (newVal && newVal !== oldVal) {
          this.loadComponents()
          this.clickInterfaceData()
        }
      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    /**
     * 查询二级模块返回数据
     * @param module
     */
    showSaveDataModule(module) {
      console.info(this.saveData[module.id], module)
    },
    /**
     * @name buildProps
     * @param module
     * @return {{}}
     * @description 组装props参数
     */
    buildProps(module) {
      if (!this.saveData) return false
      let props = {}
      props.bizParams = this.bizParams
      props.formData =  this.initFormData(module);
      props.dataSourceName = module.dataSourceName.value
      props.viewId = module.dataSourceViewId ? module.dataSourceViewId.value : 'default'
      props.passModuleIds = (module.passModule && getVarType(module.passModule) === 'array') ? module.passModule.map(modulesId=> modulesId[modulesId.length -1]) : []
      props.extraParams = Object.assign({}, this.extraParams, module.customizeExtraParams ? JSON.parse(module.customizeExtraParams): {})

      props.moduleProp = this.initModuleProp(module)
      //console.info("props:::::", props)
      return props
    },

    /** 初始化 */
    initFormData(module) {
      let initFormData = {}
      let moduleId = module.id
      if(this.formData && module.passFormData && !this.saveData[moduleId].key) {
        module.passFormData.split(',').forEach(formDataKey=>{
          if(!initFormData.key) initFormData.key= {}
          if(formDataKey) initFormData.key[formDataKey] = this.formData[formDataKey]
        })
      }
      return Object.assign({},initFormData, this.saveData[moduleId])
    },

    /**
     * @name loadComponents
     * @description 载入组件信息
     */
    loadComponents() {
      this.modules.forEach((module, index) => {
        this.components.push({
          id: module.id,
          ref: module.id,
          index: index,
          moduleName: module.moduleName,
          oneModuleName: this.oneModuleName,
          dataSourceName: module.dataSourceName.value,
          component: this.getComponents(module)
        })
      })
    },

    /**
     * @name clickInterfaceData
     * @description 自动查询接口数据
     */
    clickInterfaceData(){
      this.modules.forEach((module, index) => {
        let {autoQuery} = module
        if(autoQuery && autoQuery.value === true) {
          this.callInterface(module)
        }
      })
    },

    // 导入组件
    getComponents(module) {
      // 自定义组件
      if(module.dataFrom && "fromCustomize" === module.dataFrom.value && module.customizeRender) {
        return module.customizeRender.value
      }
      // 默认组件
      else if (module.dataSourceRender) {
        return packages[module.dataSourceRender.value]
      }
      this.$message.error("未找到组件，请配置二级模块渲染组件：" + module.moduleName)
    },

    // 重置当前模块数据
    async callInterface(module) {
      this.btnLoading = true
      await this._tempV.getQueryTwoData(this.oneModuleId, module)
      this.$nextTick(() => {
        this.btnLoading = false
      })
    },

    // 设置二级模块数据
    setFormData(id, data) {
      this.$refs[id][0].formData = data
    },

    /**
     * 获取单一模板数据
     */
    getFormData(isValidate) {
      let currentData = []
      return new Promise(async (resolve, reject) => {
        try {
          if (this.components.length === 0) {
            reject('获取模板数据失败，未查询到模板信息')
          }

          for (let i = 0; i < this.components.length; i++) {
            let {id, moduleName, oneModuleName} = this.components[i]
            try {
              if (this.$refs[id]) {
                let refs = this.$refs[id][0]
                let dataType = refs.getType()
                if (dataType === TempType.save) {
                  let formData = await refs.getFormData(isValidate)
                  currentData.push(formData)
                }
              } else {
                reject(`加载[${moduleName}]失败,原因:{0}${this.$refs[id]}`)
                break;
              }
            } catch (err) {
              console.log(err)
              if (err) {
                let errMessage = err[Object.keys(err)[0]][0].message
                reject(`请检查一级模块[${oneModuleName}]子模块[${moduleName}]，${errMessage}`)
                break;
              }
              reject(`请检查一级模块[${oneModuleName}]子模块[${moduleName}]输入项`)
              break;
            }
          }
          resolve(currentData)
        } catch (e) {
          reject(e)
        }
      })
    },

    /**
     * 校验二级模块数据
     */
    validate() {
      let PromiseAll = []
      this.modules.map(module => PromiseAll.push(this.$refs[module.id][0].getFormData(true)))
      return new Promise((resolve, reject) => {
        Promise.all(PromiseAll).then(valid => {
          resolve(true)
        }).catch(err => {
          reject(err)
        })
      })
    },


    /**
     * @name doShowSubmit
     * @param isShow
     */
    doShowSubmit(isShow) {
      this.showSubmit = isShow
    },

    /** 是否列表控制显示新增按钮 */
    isShowEasyDataListAdd(module) {
      const {dataSourceRender, showAddBtn} = module
      return module && dataSourceRender && showAddBtn && 'EasyDataList' === dataSourceRender.value && showAddBtn.value === 'true'
    },
    addEasyDataList() {

    },
    queryLoading(moduleId) {
      if (this.btnLoading) return this.btnLoading
      let data = this.saveData[moduleId]
      return Object.keys(data).length === 0;
    },

    /** 初始化二级模块自定义属性 */
    initModuleProp(module) {
      let moduleProp = {}
      moduleProp.autoQuery = false //不做自动查询，传入formData直接显示
      moduleProp.showAction = this.getModuleProp(module, 'showAction')
      moduleProp.showAddBtn = this.getModuleProp(module, 'showAddBtn')
      if (module.prop) {
        Object.keys(module.prop).map(key => {
          let item = module.prop[key]
          moduleProp[key] = item ? item.value === 'true' ? true : item.value === 'false' ? false : item.value : item
        })
      }
      return moduleProp
    },
  }
}
</script>
<style scoped>
.es-box-card {
  margin-top: 10px;
}
</style>
