<template>
<div>
  <div class="tab_top">
    <p class="tab_tittle">数据导入设置</p>
    <el-tooltip content="注：开启设置后，表单批量导入将执行设置中的预处理逻辑，默认不开始保持系统原有导入逻辑；" placement="top">
      <span>开启设置<i class="el-icon-question"></i> <el-switch v-model="importStatus" :active-value="1" :inactive-value="0"></el-switch></span>
    </el-tooltip>

  </div>
  <div class="add_options">
    <el-tooltip content="注: 可以设置需要预置字段，设置后在导入时可以填写字段值，达到批量设置效果。" placement="top">
      <span>预置参数 <i class="el-icon-question"></i></span>
    </el-tooltip>
    <el-popover ref="paramSelector" placement="bottom-start" trigger="click">
        <div style="max-height: 300px;overflow-y: auto">
          <template v-for="(item,index) in usedFormItems">
            <div :key="item.__vModel__" :title="item.__config__.label" class="weidu" @click="addOptions(item)">
              {{ item.__config__.label + '【' + item.__vModelName__ + '】' }}
            </div>
          </template>
       </div>
      <el-button slot="reference" size="mini">添加</el-button>
    </el-popover>
  </div>
  <div class="options_list">
    <div v-for="(item,index) in presetColumnsList" :key="item.id">
      <p><span>{{item.label}}</span> <i class="el-icon-delete" @click="presetColumnsList.splice(index, 1)"></i></p>
    </div>
  </div>
  <div class="add_options">
    <el-tooltip content=" 注：主要解决导入excel表格列与物理表字段匹配关联、数据字段填充处理等逻辑。" placement="top">
      <span>数据预处理设置 <i class="el-icon-question"></i></span>
    </el-tooltip>
    <span style="margin-right: -100px">样例代码</span>
  </div>
  <div style="display: flex;justify-content: space-between;">
    <aceEditor ref="dataPresetExecEditor" v-model="dataPresetExec" width="60%" height="200" lang="java" snippets wrap />
    <aceEditor ref="dataPresetExecEditorSample" v-model="dataPresetExecSample" width="37%" height="200" lang="java" snippets wrap :readonly="true" />
  </div>
  <div class="add_options">
    <el-tooltip content=" 注：主要针对数据导入前的历史数据清理校验。" placement="top">
      <span>导入预处理设置 <i class="el-icon-question"></i></span>
    </el-tooltip>
    <span style="margin-right: -100px">样例代码</span>
  </div>
  <div style="display: flex;justify-content: space-between;">
  <aceEditor ref="importPresetExecEditor" v-model="importPresetExec" width="60%" height="200" lang="java" snippets wrap />
  <aceEditor ref="importPresetExecEditorSample" v-model="importPresetExecSample" width="37%" height="200" lang="java" snippets wrap :readonly="true"/>
  </div>
  <div style="text-align: right;margin-top: 30px">
    <el-button type="success" plain @click="importConfigSave">{{ saveFlag ? '更新' : '提交' }}</el-button>
  </div>
</div>
</template>
<script>
import {getDrawingList} from "@/components/Generator/utils/db";
import aceEditor from "@/components/AceEditor/index.vue";
import {importConfigGetInfo, importConfigSave} from "@/api/onlineDev/visualDev";

export default {
  components: {aceEditor},
  props:['modelId','activeName'],
  data(){
    return {
      importStatus: 0,
      presetColumnsList: [],
      dataPresetExec: '',
      dataPresetExecSample: 'package org.springblade.db.excel.template;\n' +
        '\n' +
        'import org.springblade.bi.client.DynamicDataSourceClient;\n' +
        'import org.springblade.bi.client.form.BaseDsForm;\n' +
        'import org.springblade.bi.client.model.DataSourceModel;\n' +
        'import org.springblade.service.rpc.DataSourceClientRpc;\n' +
        'import org.springblade.service.tool.SpringContext;\n' +
        '\n' +
        'import java.util.ArrayList;\n' +
        'import java.util.HashMap;\n' +
        'import java.util.List;\n' +
        'import java.util.Map;\n' +
        '\n' +
        'public class DataPreprocessingTemplate {\n' +
        '\n' +
        '  /*\n' +
        '  * 无返回值 sql 执行方法\n' +
        '  * @param sql 需要执行的 sql\n' +
        '  * @param dsId 数据源 id\n' +
        '  * @return\n' +
        '  */\n' +
        '  private static void sqlExec(String sql, Integer dsId) {\n' +
        '    BaseDsForm form = getBaseDsForm(sql, dsId);\n' +
        '\n' +
        '    DynamicDataSourceClient dynamicDataSourceClient = SpringContext.getBean(DynamicDataSourceClient.class);\n' +
        '    dynamicDataSourceClient.execute(form);\n' +
        '\n' +
        '  }\n' +
        '\n' +
        '  /**\n' +
        '  * 组装数据源参数\n' +
        '  *\n' +
        '  * @param sql 需要执行的 sql\n' +
        '  * @param dsId 数据源 id\n' +
        '  * @return {@link BaseDsForm}\n' +
        '  */\n' +
        '  private static BaseDsForm getBaseDsForm(String sql, Integer dsId) {\n' +
        '    DataSourceClientRpc dataSourceClientRpc = SpringContext.getBean(DataSourceClientRpc.class);\n' +
        '    DataSourceModel ds = dataSourceClientRpc.getById(dsId);\n' +
        '    BaseDsForm form = new BaseDsForm();\n' +
        '    form.setPoolName(ds.getPoolName());\n' +
        '    form.setSql(sql);\n' +
        '    return form;\n' +
        '  }\n' +
        '\n' +
        '  /**\n' +
        '  * 执行数据预处理 demo\n' +
        '  *\n' +
        '  * @param dsId    数据源\n' +
        '  * @param row     行数\n' +
        '  * @param data    数据\n' +
        '  * @param presetParams 预置参数\n' +
        '  * @param cacheData  导入会话的缓存数据,单例\n' +
        '  * @return\n' +
        '  */\n' +
        '  public static List eval(Integer dsId, Integer row, Map<Integer, String> data, Map<String, Object> presetParams, List cacheData) {\n' +
        '    System.out.println("dsId:"+dsId);\n' +
        '    System.out.println("row:"+row);\n' +
        '    System.out.println("data:"+data);\n' +
        '    System.out.println("presetParams:"+presetParams);\n' +
        '    System.out.println("cacheData:"+cacheData);\n' +
        '\n' +
        '    HashMap<Object, Object> map = new HashMap<>();\n' +
        '    map.put("id", data.get(0));\n' +
        '    map.put("username", data.get(1));\n' +
        '    map.put("phone_number", data.get(2));\n' +
        '    map.put("email", data.get(3));\n' +
        '    map.put("address", data.get(4));\n' +
        '    map.put("age", data.get(5));\n' +
        '    \n' +
        '    \n' +
        '   \n' +
        '    ArrayList<Object> objects = new ArrayList<>();\n' +
        '    objects.add(map);\n' +
        '    \n' +
        '    return objects;\n' +
        '  }\n' +
        '\n' +
        '}',
      importPresetExec: '',
      importPresetExecSample: 'package org.springblade.db.excel.template;\n' +
        '\n' +
        'import org.springblade.bi.client.DynamicDataSourceClient;\n' +
        'import org.springblade.bi.client.form.BaseDsForm;\n' +
        'import org.springblade.bi.client.model.DataSourceModel;\n' +
        'import org.springblade.service.rpc.DataSourceClientRpc;\n' +
        'import org.springblade.service.tool.SpringContext;\n' +
        '\n' +
        'import java.util.List;\n' +
        'import java.util.Map;\n' +
        '\n' +
        'public class DataPreprocessingTemplate2 {\n' +
        '\n' +
        '  /*\n' +
        '  * 无返回值 sql 执行方法\n' +
        '  * @param sql 需要执行的 sql\n' +
        '  * @param dsId 数据源 id\n' +
        '  * @return\n' +
        '  */\n' +
        '  private static void sqlExec(String sql, Integer dsId) {\n' +
        '    BaseDsForm form = getBaseDsForm(sql, dsId);\n' +
        '\n' +
        '    DynamicDataSourceClient dynamicDataSourceClient = SpringContext.getBean(DynamicDataSourceClient.class);\n' +
        '    dynamicDataSourceClient.execute(form);\n' +
        '\n' +
        '  }\n' +
        '\n' +
        '  /**\n' +
        '  * 组装数据源参数\n' +
        '  *\n' +
        '  * @param sql 需要执行的 sql\n' +
        '  * @param dsId 数据源 id\n' +
        '  * @return {@link BaseDsForm}\n' +
        '  */\n' +
        '  private static BaseDsForm getBaseDsForm(String sql, Integer dsId) {\n' +
        '    DataSourceClientRpc dataSourceClientRpc = SpringContext.getBean(DataSourceClientRpc.class);\n' +
        '    DataSourceModel ds = dataSourceClientRpc.getById(dsId);\n' +
        '    BaseDsForm form = new BaseDsForm();\n' +
        '    form.setPoolName(ds.getPoolName());\n' +
        '    form.setSql(sql);\n' +
        '    return form;\n' +
        '  }\n' +
        '\n' +
        '  /**\n' +
        '  * 执行数据预处理 demo\n' +
        '  *\n' +
        '  * @param dsId    数据源\n' +
        '  * @param row     行数\n' +
        '  * @param data    数据\n' +
        '  * @param presetParams 预置参数\n' +
        '  * @param cacheData  导入会话的缓存数据,单例\n' +
        '  * @return\n' +
        '  */\n' +
        '  public static void eval(Integer dsId, Integer row, Object data, Map<String, Object> presetParams, List cacheData) {\n' +
        '    sqlExec("UPDATE tb_user SET age324 = \\"chengongle\\" WHERE username = \\"jack\\"", dsId);\n' +
        '  }\n' +
        '\n' +
        '}',
      saveFlag:false
    }
  },
  computed:{
    usedFormItems() {
      let list = []
      const loop = (data, parent) => {
        if (!data) return
        if (data.__config__ && data.__config__.jnpfKey !== 'table' && data.__config__.children && Array.isArray(data.__config__.children)) {
          loop(data.__config__.children, data)
        }
        if (Array.isArray(data)) data.forEach((d) => loop(d, parent))
        if (data.__vModel__ && data.__config__.jnpfKey !== 'table') list.push(data)
      }
      loop(getDrawingList())
      const formItems = list
      return formItems
    }
  },
  created() {
    this.init()
  },
  watch: {
    activeName: {
      deep: true,
      handler(val) {
        if (val && val === 'importSet') {
          this.init()
        }
      }
    }
  },
  methods:{
    init(){
      importConfigGetInfo({formId:this.modelId}).then((res)=>{
        if (res.data.data) {
          this.importStatus = res.data.data.status
          this.presetColumnsList = JSON.parse(res.data.data.presetColumns) || []
          this.dataPresetExec = res.data.data.dataPresetExec
          this.importPresetExec = res.data.data.importPresetExec
          this.saveFlag = true
        }else {
          this.importStatus = 0
          this.presetColumnsList = []
          this.dataPresetExec = ''
          this.importPresetExec = ''
          this.saveFlag = false
        }
      })
    },
    addOptions(item){
      if (this.presetColumnsList.find((i) => i.id === item.__vModel__)) return
      this.presetColumnsList.push({label:item.__config__.label,id:item.__vModel__});
      this.$refs.paramSelector.doClose()
    },
    importConfigSave(){
      let data = {
        formId: this.modelId,
        status: this.importStatus,
        presetColumns: JSON.stringify(this.presetColumnsList),
        importPresetExec: this.importPresetExec,
        dataPresetExec: this.dataPresetExec
      }
      importConfigSave(data).then((res)=>{
        this.$message({ message: res.data.msg, type: 'success', duration: 1500 })
        this.init()
      })
    },
  }
}
</script>

<style scoped lang="scss">
.tab_top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #cccccc;
}
.add_options{
  width: 60%;
  padding: 10px 20px;
  margin-bottom: 10px;
  border-bottom: 1px solid #cccccc;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: nowrap;
}
.weidu {
  line-height: 24px;
  box-sizing: border-box;
  border: 1px solid #1d54d5;
  background-color: #e4eafa;
  padding: 0 10px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin: 3px 0;
  cursor: pointer;
}
.options_list{
  width: 60%;
  padding: 10px 20px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: center;
  align-items: center;
  div{
    width: 33%;
    margin-bottom: 10px;
    p{
      span{
        display: inline-block;
        width: 85%;
        line-height: 24px;
        box-sizing: border-box;
        border: 1px solid #1d54d5;
        background-color: #e4eafa;
        padding: 0 10px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        vertical-align: middle;
      }
      i{
        cursor: pointer;
      }
    }
  }
}
</style>
