<template>
<a-spin :spinning="confirmLoading">

   <a-tabs v-model="activeKey" @change="handleChangeTabs">
   <!--主表区域 -->
    <a-tab-pane tab="报表基础类" :key="refKeys[0]" :forceRender="true">
         <a-form-model ref="form" :model="model" :rules="validatorRules">
           <a-row>
                  <a-col :xs="24" :sm="12">
                    <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="title">
                      <a-input v-model="model.title" :required='true' placeholder="请输入标题" ></a-input>
                    </a-form-model-item>
                  </a-col>
                 <a-col :xs="24" :sm="12">
                   <a-form-model-item label="编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                     <a-input v-model="model.code" placeholder="请输入编码" ></a-input>
                   </a-form-model-item>
                 </a-col>
                  <a-col :xs="24" :sm="12">
                    <a-form-model-item label="从第几行写入数据" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fromNum">
                      <a-input-number v-model="model.fromNum" placeholder="请输入从第几行写入数据" style="width: 100%" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="12">
                    <a-form-model-item label="复制第几页" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="copyNum">
                      <a-input v-model="model.copyNum" placeholder="请输入复制第几页" ></a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="12">
                    <a-form-model-item label="是否文本化" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="toText">
                      <j-dict-select-tag type="list" v-model="model.toText"  dictCode="yn" placeholder="请选择是否文本化" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="12">
                    <a-form-model-item label="模板地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateUrl">
                      <j-upload v-model="model.templateUrl"   ></j-upload>
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="12">
                    <a-form-model-item label="报表模式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exportType">
                      <j-dict-select-tag type="radio" v-model="model.exportType"  dictCode="export_type" placeholder="请选择报表模式" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="12">
                    <a-form-model-item label="报表类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reportType">
                      <j-dict-select-tag type="radio" v-model="model.reportType"  dictCode="report_type" placeholder="请选择报表模式" />
                    </a-form-model-item>
                  </a-col>
                   <a-col :xs="24" :sm="12">
                     <a-form-model-item label="所属分组" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="groupId">
                       <j-dict-select-tag type="list" v-model="model.groupId"  dict-code='gt_export_group,name,id' placeholder="请选择分组" />
                     </a-form-model-item>
                   </a-col>
                  <a-col :span="24">
                    <a-form-model-item label="需要执行的SQL" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="exportSql">
                      <a-textarea v-model="model.exportSql" rows="4" placeholder="请输入需要执行的SQL" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="12">
                    <a-form-model-item label="数据源id" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="datasourceId">
                      <j-dict-select-tag type="list" v-model="model.datasourceId"  dictCode="sys_data_source,name,id" placeholder="请选择数据源id" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :xs="24" :sm="12">
                    <a-button @click="handleSql" type = "primary" >解析SQL</a-button>
                  </a-col>

                </a-row>
              </a-form-model>

     </a-tab-pane>
   <!--子表单区域 -->
     <a-tab-pane tab="报表字段信息" :key="refKeys[1]" :forceRender="true">
       <j-editable-table
         :ref="refKeys[1]"
         :loading="gtExportColumnTable.loading"
         :columns="gtExportColumnTable.columns"
         :dataSource="gtExportColumnTable.dataSource"
         :maxHeight="300"
         :rowNumber="true"
         :rowSelection="true"
         :actionButton="true"/>
     </a-tab-pane>

     <a-tab-pane tab="报表替换规则类" :key="refKeys[2]" :forceRender="true">
       <j-editable-table
         :ref="refKeys[2]"
         :loading="gtExportRuleTable.loading"
         :columns="gtExportRuleTable.columns"
         :dataSource="gtExportRuleTable.dataSource"
         :maxHeight="300"
         :rowNumber="true"
         :rowSelection="true"
         :actionButton="true"/>
     </a-tab-pane>

   </a-tabs>

 </a-spin>
</template>

<script>
import { httpAction } from '@/api/manage'
import { FormTypes,getRefPromise } from '@/utils/JEditableTableUtil'
import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
import { validateDuplicateValue } from '@/utils/util'
import { VALIDATE_NO_PASSED, validateFormModelAndTables } from '@/utils/JEditableTableUtil'

export default {
 name: 'GtExportForml',
 mixins: [JEditableTableModelMixin],
 components: {
 },
 data() {
   return {
     labelCol: {
       xs: { span: 24 },
       sm: { span: 6 },
     },
     wrapperCol: {
       xs: { span: 24 },
       sm: { span: 16 },
     },
     labelCol2: {
       xs: { span: 24 },
       sm: { span: 3 },
     },
     wrapperCol2: {
       xs: { span: 24 },
       sm: { span: 20 },
     },
     // 新增时子表默认添加几行空数据
     addDefaultRowNum: 1,
     model:{
       fromNum:1,
       exportType:1
     },
        validatorRules: {
        },
     refKeys: ['gtExport','gtExportColumn', 'gtExportRule', ],
     tableKeys:['gtExportColumn', 'gtExportRule', ],
     activeKey: 'gtExport',
     // 报表字段信息
     gtExportColumnTable: {
       loading: false,
       dataSource: [],
       columns: [
         {
           title: '字段名',
           key: 'fieldName',
           type: FormTypes.input,
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '显示名',
           key: 'showName',
           type: FormTypes.input,
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '排序',
           key: 'sortOrder',
           type: FormTypes.inputNumber,
           width:"50px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '字段类型',
           key: 'fieldType',
           type: FormTypes.select,
           dictCode:"field_type",
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '是否显示',
           key: 'isShow',
           type: FormTypes.select,
           dictCode:"yn",
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '是否查询',
           key: 'isCheck',
           type: FormTypes.select,
           dictCode:"yn",
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '是否必选',
           key: 'isMust',
           type: FormTypes.select,
           dictCode:"yn",
           width:"200px",
           placeholder: '请选择${title}',
           defaultValue:'',
         },
         {
           title: '是否合计',
           key: 'isSum',
           type: FormTypes.select,
           dictCode:"yn",
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '是否合并',
           key: 'isCombine',
           type: FormTypes.select,
           dictCode:"yn",
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '合并相关列',
           key: 'combineColumn',
           type: FormTypes.select,
           dictCode:"",
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '是否分页',
           key: 'isPage',
           type: FormTypes.select,
           dictCode:"yn",
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '是否分表',
           key: 'isSubmeter',
           type: FormTypes.select,
           dictCode:"yn",
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '相关规则',
           key: 'rule',
           type: FormTypes.input,
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '分表规则',
           key: 'subRule',
           type: FormTypes.input,
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
       ]
     },
     // 报表替换规则类
     gtExportRuleTable: {
       loading: false,
       dataSource: [],
       columns: [
         {
           title: '表格的位置（多个用逗号隔开）',
           key: 'cellPlace',
           type: FormTypes.input,
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '替换的关键字',
           key: 'keyword',
           type: FormTypes.input,
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
         {
           title: '需要替换的规则',
           key: 'rule',
           type: FormTypes.input,
           width:"200px",
           placeholder: '请输入${title}',
           defaultValue:'',
         },
       ]
     },
     url: {
       add: "/export/gtExport/add",
       edit: "/export/gtExport/edit",
        gtExport: {
         list: '/export/gtExport/queryById'
        },
       gtExportColumn: {
         list: '/export/gtExport/queryGtExportColumnByMainId'
       },
       gtExportRule: {
         list: '/export/gtExport/queryGtExportRuleByMainId'
       },
       parseSql:"/export/gtExport/parseSql"
     }
   }
 },
 methods: {
   getAllTable() {
     let values = this.tableKeys.map(key => getRefPromise(this, key))
     return Promise.all(values)
   },
   /** 调用完edit()方法之后会自动调用此方法 */
   editAfter() {
     this.$nextTick(() => {
     })
     // 加载子表数据
     if (this.model.id) {
       let params = { id: this.model.id }
       this.requestSubTableData(this.url.gtExportColumn.list, params, this.gtExportColumnTable)
       this.requestSubTableData(this.url.gtExportRule.list, params, this.gtExportRuleTable)
     }
   },
   //校验所有一对一子表表单
   validateSubForm(allValues){
     return new Promise((resolve,reject)=>{
       Promise.all([
       ]).then(() => {
         resolve(allValues)
       }).catch(e => {
         reject(e)
       })
     })
   },
   /** 整理成formData */
   classifyIntoFormData(allValues) {
     let main = Object.assign(this.model, allValues.formValue)
     return {
       ...main, // 展开
       gtExportColumnList: allValues.tablesValue[0].values,
       gtExportRuleList: allValues.tablesValue[1].values,
     }
   },
    /** 确定按钮点击事件 */
     handleOk() {
       /** 触发表单验证 */
       this.getAllTable().then(tables => {
          return validateFormModelAndTables(this.$refs.form,this.model, tables)
       }).then(allValues => {
         /** 一次性验证一对一的所有子表 */
         return this.validateSubForm(allValues)
       }).then(allValues => {
         if (typeof this.classifyIntoFormData !== 'function') {
           throw this.throwNotFunction('classifyIntoFormData')
         }
         console.log("this.classifyIntoFormData",typeof this.classifyIntoFormData)
         let formData = this.classifyIntoFormData(allValues)

         // 发起请求
         return this.request(formData)
       }).catch(e => {
         if (e.error === VALIDATE_NO_PASSED) {
           // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
           this.activeKey = e.index == null ? this.refKeys[0] : this.refKeys[e.index+1]
         } else {
           console.error(e)
         }
       })
     },
   validateError(msg){
     this.$message.error(msg)
   },
 close() {
   this.visible = false
   this.$emit('close')
   this.$refs.form.clearValidate();
 },
 handleSql(){
    let that = this;
    let datasourceId = that.model.datasourceId;
    let exportSql = that.model.exportSql;
    if(!datasourceId){
      that.$message.error("请选择数据源");
    }else if(!exportSql){
      that.$message.error("请输入报表SQL")
    }else{
      let param = {"datasource_id":datasourceId,"sql":exportSql};
        that.confirmLoading = true;
        httpAction(this.url.parseSql,param,"POST").then((res)=>{
          if(res.success){
            if(res.result.length>0){
              let _result = res.result;
              that.$message.success("解析成功"+res.result.length+"个字段");
              //清空报表字段信息，然后添加获取的结果
              that.gtExportColumnTable.dataSource = [];
              let _index = 0;
              _result.forEach(col => {
                that.gtExportColumnTable.dataSource.push({"fieldName":col,"showName":col,"sortOrder":_index});
                _index++;
              });
            }else{
              that.$message.error("解析失败");
            }
            // that.$emit('ok');
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.confirmLoading = false;
        })
    }
    return false;
  }
 }
}
</script>

<style scoped>
</style>