<template>
    <span class="pages">
        <ed-dialog :close-on-press-escape="false" :destroy-on-close="true" :fullscreen="true"
                   :visible.sync="dialogVisible" class="easy-dialog">
            <template slot="title">
                <div class="es-dialog--operate">
                    <span @click="updateRightProp('global')">{{ title }}</span>
                    <div>
                        <el-button :loading="loading" size="mini" type="primary" @click="preview">预览</el-button>
                        <el-button :loading="loading" size="mini" @click="loadData">刷新</el-button>
                    </div>
                </div>
            </template>
            <el-row :gutter="10" class="es-row">
                <el-col :span="5" class="es-row--col">
                    <el-card class="es-box-card" style="overflow:auto">
                        <div slot="header" class="es-box-card--header">
                            <div>模板定义</div>
                            <div>
                                <el-button type="text" @click="addOneModule"><i class="el-icon-plus"/>新增一级模块</el-button>
                            </div>
                        </div>
                        <el-card v-for="(module, index) in oneModules" :key="module.id"
                                 :class="['view-list-card', { active: oneModuleActive == index }]"
                                 shadow="never"
                                 @click.native="clickOneModule(module, index)">
                            <span> {{
                                module.moduleCode ? `${module.moduleName}【${module.moduleCode}】` : module.moduleName
                              }}</span>
                            <span style="float: right;">
                                <i v-show="index < oneModules.length - 1" class="el-icon-bottom icon"
                                   @click.stop="downModule(module, index, 'one')"/>
                                <i v-show="index > 0" class="el-icon-top icon"
                                   @click.stop="upModule(module, index, 'one')"/>
                                <i class="el-icon-edit icon" @click.stop="editModule(module, index, 'one')"/>
                                <el-popconfirm :title="`确定删除一级模块【${module.moduleName}】吗?`"
                                               @confirm="deleteModule(module, index, 'one')">
                                    <i slot="reference" class="el-icon-delete icon"/>
                                </el-popconfirm>
                            </span>
                        </el-card>
                    </el-card>
                </el-col>
                <el-col :span="14" class="es-row--col">
                    <el-card v-if="oneModuleActive >= 0 && oneModules.length > oneModuleActive" class="es-box-card"
                             style="overflow:auto">
                        <div slot="header" class="es-box-card--header">
                            <div>{{ oneModules[oneModuleActive].moduleName }}-二级模块</div>
                            <div>
                                <el-button type="text" @click="addTwoModule"><i class="el-icon-plus"/>新增二级模块</el-button>
                            </div>
                        </div>
                        <el-card v-for="(twoModule, index) in oneModules[oneModuleActive]?.twoModules"
                                 :key="twoModule.id"
                                 class="el-card-margin" shadow="never" @click.native="clickTwoModule(twoModule, index)">
                            <div slot="header" class="clearfix">
                                <span> {{
                                    twoModule?.moduleCode ? `${twoModule?.moduleName}【${twoModule?.moduleCode}】` :
                                        twoModule?.moduleName
                                  }}</span>
                                <span style="float: right;">
                                    <i v-show="index < oneModules[oneModuleActive]?.twoModules?.length - 1"
                                       class="el-icon-bottom icon"
                                       @click.stop="downModule(twoModule, index)"/>
                                    <i v-show="index > 0" class="el-icon-top icon"
                                       @click.stop="upModule(twoModule, index)"/>
                                    <i class="el-icon-edit icon" @click.stop="editModule(twoModule, index, 'two')"/>
                                    <el-popconfirm :title="`确定删除二级模块【${twoModule.moduleName}】吗?`"
                                                   @confirm="deleteModule(twoModule, index)">
                                        <i slot="reference" class="el-icon-delete icon"/>
                                    </el-popconfirm>
                                </span>
                            </div>
                            <easy-data-view v-if="oneModuleActive >= 0" ref="TwoBasicDescribe"
                                            :column="3" :dataSourceName="twoForm.dataSourceName"
                                            :formData="{keyInfoView: twoModule}" :moduleProp="{showNull: false}">
                                <template v-slot:passModule="{formData, column}">
                                  {{ getOptionsLabel(formData, column) }}
                                </template>
                            </easy-data-view>
                        </el-card>
                    </el-card>
                    <el-card v-else class="es-box-card">
                        请选择左侧一级模块
                    </el-card>
                </el-col>
                <el-col :span="5" class="es-row--col">
                    <el-card v-if="oneModuleActive >= 0" class="es-box-card" style="overflow:auto">
                        <el-collapse v-model="propActiveName" accordion>
                            <el-collapse-item name="global" title="全局属性">
                                <el-card class="es-box-card">
                                    <EasyDataForm v-if="dialogVisible" ref="GlobalPropEasyDataList"
                                                  :dataSourceName="global.dataSourceName" :formData="global.formData"
                                                  :label-position="labelPosition"/>
                                </el-card>
                            </el-collapse-item>
                            <el-collapse-item name="oneProp" title="一级模块属性">
                                <el-card class="es-box-card">
                                    <EasyDataForm
                                        v-if="dialogVisible"
                                        ref="OnePropEasyDataList" :dataSourceName="oneProp.dataSourceName"
                                        :formData="oneProp.formData" :label-position="labelPosition"
                                        labelWidth="120px"/>
                                </el-card>
                            </el-collapse-item>
                            <el-collapse-item name="twoProp" title="二级模块属性">
                                <el-card class="es-box-card">
                                    <EasyDataForm v-if="dialogVisible" ref="TwoPropEasyDataList"
                                                  :dataSourceName="twoProp.dataSourceName" :formData="twoProp.formData"
                                                  :label-position="labelPosition"/>
                                </el-card>
                            </el-collapse-item>
                        </el-collapse>
                    </el-card>
                </el-col>
            </el-row>
            <template slot="footer">
                <el-button :loading="loading" size="small" type="primary" @click="save">保存</el-button>
                <el-button :loading="loading" size="small" type="success" @click="saveAndClose">保存并关闭</el-button>
                <el-button size="small" type="info" @click="close">关 闭</el-button>
            </template>
        </ed-dialog>

        <AddDialog ref="oneAddModuleRef" :dataSourceName="oneForm.dataSourceName" @ok="saveNewOneModule">
        </AddDialog>

        <AddDialog ref="twoAddModuleRef" :dataSourceName="twoForm.dataSourceName" @ok="saveNewTwoModule">
        </AddDialog>

        <TemplatePreview ref="templatePreviewRef" :bizParamStr="templateModel?.moduleInfo?.keyInfoObject.biz_params"
                         :title="templateModel?.moduleInfo?.keyInfoObject.template_name"/>
    </span>
</template>

<script>
import {randomUUID}    from '../../../../utils/utils'
import AddDialog       from './model/AddDialog'
import hooks           from '../hooks'
import {initControls}  from "../../../../api/easyData";
import {setFormData}   from "../../../../utils/useBusiness";
import TemplatePreview from './model/TemplatePreview2';

export default {
  name: 'DefineModal',
  mixins: hooks,
  components: {AddDialog, TemplatePreview},
  data() {
    return {
      title: '模板定义-',
      dialogVisible: false,
      loading: false,
      templateId: '',
      //动态模版
      templateModel: {},
      //一级模块
      oneModules: [],
      oneModuleActive: -1,
      twoModuleActive: -1,
      labelPosition: 'right',
      url: {
        getModule: '/easydata/template/getModule',
        saveModule: '/easydata/template/saveModule',
        previewModule: '/easydata/template/getPreviewTemplate'
      },

      propActiveName: 'global',
      //一级模块表单
      oneForm: {
        dataSourceName: "easy_template_module_one_form",
        controlInfos: [],
        title: '',
        formData: {},
        visible: false
      },
      //二级模块表单
      twoForm: {
        dataSourceName: "easy_template_module_form",
        controlInfos: [],
        formData: {},
        title: '',
        visible: false
      },
      //全局模版属性
      global: {
        dataSourceName: "easy_template_prop_form",
        formData: {},
        controlInfos: [],
      },
      //一级模块属性
      oneProp: {
        dataSourceName: "easy_template_module_prop_form",
        formData: {},
        controlInfos: []
      },
      //二级模块属性
      twoProp: {
        dataSourceName: "easy_template_module_prop_form_view",
        formData: {},
        controlConfig: null,
        controlInfos: []
      },
      options: []
    }
  },
  methods: {
    async showModal(record) {
      this.title = '模板定义-' + record.keyInfo.template_name
      this.templateId = record.id
      this.clear()
      this.loadData()
      await this.queryControlInfos();
      this.dialogVisible = true
    },
    clear() {
      this.templateModel = {}
      this.oneModules = []
      this.global.formData = {}
      this.oneProp.formData = {}
      this.twoProp.formData = {}
      this.oneModuleActive = -1
      this.twoModuleActive = -1
    },
    /**
     * 查询各个数据源的配置信息
     */
    async queryControlInfos() {
      const result1 = await initControls(this.oneForm.dataSourceName)
      this.oneForm.controlInfos = result1?.data?.controlInfos
      const result2 = await initControls(this.twoForm.dataSourceName)
      this.twoForm.controlInfos = result2?.data?.controlInfos
      const result3 = await initControls(this.oneProp.dataSourceName)
      this.oneProp.controlInfos = result3?.data?.controlInfos
      const result4 = await initControls(this.twoProp.dataSourceName)
      this.twoProp.controlInfos = result4?.data?.controlInfos
    },
    async loadData() {
      if (this.templateId) {
        this.loading = true
        const res = await this.$EdFrame.postAction(this.url.getModule, {id: this.templateId});
        this.loading = false;
        if (res && res.success && res.data) {
          this.templateModel = res.data
          this.global.formData = Object.assign({id: this.templateModel.template.id}, {key: this.templateModel.prop})
          this.oneModules = res.data.oneModules
          this.oneModuleActive = 0
          this.updateRightProp("global");
          if (this.oneModules.length > 0) {
            let oneModule = this.oneModules[0]
            this.clickOneModule(oneModule, 0)
            if (oneModule.twoModules && oneModule.twoModules.length > 0) {
              this.clickTwoModule(oneModule.twoModules[0], 0)
            }
          }
          this.getOptions();
        }
        //查询一级模块、二级模块配置信息
      }
    },
    //点击一级模块
    async clickOneModule(item, index) {
      this.oneModuleActive = index
      await this.updateRightProp('oneProp')
    },
    //点击二级模块
    clickTwoModule(item, index) {
      this.twoModuleActive = index
      this.updateRightProp('twoProp')
    },
    addOneModule() {
      this.$refs.oneAddModuleRef.showModel({}, '新增一级模块')
    },
    addTwoModule() {
      if (this.oneModuleActive >= 0 && this.oneModules.length > this.oneModuleActive) {
        this.$refs.twoAddModuleRef.showModel({}, '新增二级模块')
      } else {
        this.$message.warning("请选择左侧一级模块")
      }
    },
    /**
     * 删除模块
     * @param {*} module
     * @param {*} index
     */
    deleteModule(module, index, type) {
      if ('one' == type) {
        this.oneModules.splice(index, 1)
      } else {
        let {twoModules} = this.oneModules[this.oneModuleActive]
        twoModules.splice(index, 1)
        this.$set(this.oneModules[this.oneModuleActive], 'twoModules', twoModules)
      }
    },
    /**
     * 下移模块
     * @param {*} module
     * @param {*} index
     */
    downModule(module, index, type) {
      if ('one' == type) {
        if (this.oneModules.length == index + 1) {
          return;
        }
        if (this.oneModuleActive == index) {
          this.oneModuleActive = index + 1
        } else if (this.oneModuleActive == index + 1) {
          this.oneModuleActive = index
        }
        this.oneModules.splice(index, 1)
        this.oneModules.splice(index + 1, 0, module)
      } else {
        let {twoModules} = this.oneModules[this.oneModuleActive]
        if (twoModules.length == index + 1) {
          return;
        }
        twoModules.splice(index, 1)
        twoModules.splice(index + 1, 0, module)
        this.$set(this.oneModules[this.oneModuleActive], 'twoModules', twoModules)
      }
    },
    /**
     * 上移模块
     * @param {*} module
     * @param {*} index
     */
    upModule(module, index, type) {
      if (index == 0) {
        return;
      }
      if ('one' == type) {
        if (this.oneModuleActive == index) {
          this.oneModuleActive = index - 1
        } else if (this.oneModuleActive == index - 1) {
          this.oneModuleActive = index
        }
        this.oneModules.splice(index, 1)
        this.oneModules.splice(index - 1, 0, module)
      } else {
        let {twoModules} = this.oneModules[this.oneModuleActive]
        twoModules.splice(index, 1)
        twoModules.splice(index - 1, 0, module)
        this.$set(this.oneModules[this.oneModuleActive], 'twoModules', twoModules)
      }
    },
    async editModule(module, index, type) {
      let options = await this.getOptions();
      this.$refs[type + 'AddModuleRef'].showModel(Object.assign({}, {
        id: module.id,
        key: module
      }), `编辑${type === 'one' ? '一级' : '二级'}模块`, options)
    },
    getOptionsLabel(formData, column) {
      let columnName = column ? column.prop.replace('keyInfoView.', '') : column
      let itemValue = ""
      if (columnName === 'passModule') {
        itemValue = formData.passModule
        return itemValue && itemValue.length && itemValue.map(checkedTree => {
          let i = 0
          let item = this.options.find(o => o.value == checkedTree[0])
          while (item && item.children) {
            i++
            item = item.children.find(o => o.value == checkedTree[i])
          }
          return item ? item.label : checkedTree
        }).join(",")
      } else {
        return itemValue
      }
    },
    /** 实时加载模块传递的options */
    async getOptions() {
      let options = []
      if (this.oneModules) {
        let param = await this.getSaveData();
        if (param.data && param.data.length > 0) {
          options = param.data.map(oneModule => {
            let children = []
            if (oneModule.twoModules && oneModule.twoModules.length > 0) {
              children = oneModule.twoModules.map(twoModule => {
                return {
                  value: twoModule.id,
                  label: twoModule.moduleName
                }
              })
            }
            return {
              value: oneModule.id,
              label: oneModule.moduleName,
              children: children
            }
          })
          console.info("options", options, param.data)
          this.options = options
        }
      }
      return this.options;
    },
    /**
     * 保存新增或修改的一级模块
     */
    async saveNewOneModule(record) {
      if (record && record.key) {
        let fromData = record.key
        if (fromData.id) {
          let updateIndex = this.oneModules.findIndex(e => {
            if (e.id === fromData.id) {
              return e
            }
          })
          this.oneModules.splice(updateIndex, 1, fromData)
          this.clickOneModule(fromData, updateIndex)
        } else {
          let newOneModule = {
            id: randomUUID(),
            twoModules: [],
            ...fromData,
          }
          this.oneModules.push(newOneModule)
          this.clickOneModule(newOneModule, this.oneModules.length - 1)
        }
      }
    },
    async saveNewTwoModule(record) {
      if (this.oneModuleActive >= 0 && this.oneModules.length > this.oneModuleActive && record && record.key) {
        let oneModule = this.oneModules[this.oneModuleActive]
        let twoModules = this.oneModules[this.oneModuleActive].twoModules || []
        let fromData = record.key
        if (record.id) {
          let updateIndex = twoModules.findIndex(e => {
            if (e.id == fromData.id) {
              return e
            }
          })
          twoModules.splice(updateIndex, 1, fromData)
          this.clickTwoModule(fromData, updateIndex)
        } else {
          let newTwoModule = {
            id: randomUUID(),
            prop: {},
            ...fromData,
          }
          twoModules.push(newTwoModule)
          this.clickTwoModule(newTwoModule, twoModules.length - 1)
        }
        this.$set(this.oneModules[this.oneModuleActive], 'twoModules', twoModules)
      }
      this.twoForm.visible = false
    },
    async saveAndClose() {
      await this.save();
      this.close();
    },
    close() {
      this.clear()
      this.dialogVisible = false
    },
    /** 预览 */
    async preview() {
      if (this.oneModules) {
        let param = await this.getSaveData();
        let res = await this.$EdFrame.postAction(this.url.previewModule, param)
        let config = {
          prop: res.data.prop,
          modules: res.data.oneModules,
          template: res.data.template,
          moduleInfo: res.data.moduleInfo.keyInfoObject
        }

        console.info("previe!!!!!!!!!!w", res, param, this.templateModel)
        this.$refs.templatePreviewRef.showModal(config);
      } else {
        this.$message.warning("请至少添加一个一级模块，一个二级模块")
      }
    },
    async save() {
      let param = await this.getSaveData();
      try {
        let res = await this.$EdFrame.postAction(this.url.saveModule, param);
        if (res.success) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        this.$message.error(error)
      }
    },
    async getSaveData() {
      await this.recordRightProp()
      let param = Object.assign({}, this.templateModel.template)
      // 获取全局属性
      const formData = await this.$refs.GlobalPropEasyDataList?.getFormData();
      param.key = Object.assign({template_id: this.templateId}, formData?.key)
      if (this.oneModules) {
        param.data = this.oneModules.map(oneModule => {
          let newOneModule = setFormData(Object.assign({id: oneModule.id}, {key: oneModule}), this.oneForm.controlInfos)
          newOneModule.prop = setFormData(Object.assign({}, {key: oneModule.prop}), this.oneProp.controlInfos)
          let {twoModules} = oneModule
          if (twoModules) {
            newOneModule.twoModules = twoModules.map(twoModule => {
              let newTwoModule = setFormData(Object.assign({id: twoModule.id}, {key: twoModule}), this.twoForm.controlInfos)
              newTwoModule.prop = setFormData(Object.assign({}, {key: twoModule.prop}), this.twoProp.controlInfos)
              return newTwoModule
            })
          }
          return newOneModule;
        })
      }
      return param
    }
  }
}
</script>
<style lang="scss" scoped>
.icon {
  margin: 0px 5px;
  cursor: pointer;
}

.el-card-margin {
  margin-bottom: 20px;
}

@import "../../../../style/index.scss";
</style>
