<template>
  <div class="d-flex fullscreen" v-loading="loading">
    <v-card style="width: 400px;" class="mr-3 fullHeight">
      <v-banner single-line>
        <div class="py-2 title">方案列表</div>
      </v-banner>
      <v-list>
        <v-list-item
          v-for="item in items"
          :key="item.performanceSolutionId"
        >
          <v-list-item-content>
            <v-list-item-title v-text="item.title"></v-list-item-title>
          </v-list-item-content>
          <v-list-item-action>
              <v-btn
                text
                color="primary"
                @click.stop="onClick(item)"
              >
                查看方案
              </v-btn>
            </v-list-item-action>
        </v-list-item>
      </v-list>
    </v-card>
    <v-card class="width-auto">
      <div class="pa-3 fullscreen">
        <div class="fullscreen d-flex flex-column">
          <div class="mt-3 d-flex">

            <v-text-field
              outlined
              dense
              hide-details
              label="请输入来源表"
              v-model="changeObj.source_table"
              placeholder="请输入来源表"
              ></v-text-field>
              <!-- :rules="[v => !!v || '请输入来源表']" -->
              <v-text-field
              class="ml-3"
              outlined
              dense
              hide-details
              label="请输入目标表"
              v-model="changeObj.target_table"
              placeholder="请输入目标表"
              >
              <!-- :rules="[v => !!v || '请输入目标表']" -->
            </v-text-field>
          </div>
          <v-card outlined class="height-auto mt-3">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editor"
                :defaultConfig="toolbarConfig"
                :mode="mode"
            ></Toolbar>
            <Editor
                style="overflow-y: hidden; height: calc(100% - 50px);"
                v-model="changeObj.script_requirement"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="onCreated"
            />
          </v-card>
          <div class="d-flex align-end justify-end pa-3">
            <v-btn color="primary" @click="onGenerating">生成代码</v-btn>
          </div>
          <div>
            <v-textarea
              v-model="changeObj.script_content"
              outlined
              hide-details
              label="请输入执行代码"
              :rows="10"
              dense
            ></v-textarea>
          </div>
        </div>
      </div>
    </v-card>
    <v-card style="width: 400px;" class="ml-3 fullHeight d-flex flex-column">
      <v-banner single-line>
        <div class="py-2 title">基础信息</div>
        <template #actions>
          <v-btn
            text
            class="ml-3"
            color="primary"
            @click="handleSubmit"
          >
            <v-icon left>mdi-send-variant</v-icon>
            确认提交
          </v-btn>
        </template>
      </v-banner>
      <div class="pt-3 height-auto overflow-y-auto">
        <EditBase ref="editBaseRefs"></EditBase>
      </div>
    </v-card>
    <v-navigation-drawer
      v-model="drawer"
      fixed
      temporary
      right
      width="800"
    >
      <div class="fullHeight d-flex flex-column">
        <div class="mb-3">
          <v-tabs v-model="active">
            <v-tab
              v-for="item in clickItem"
              :key="item.category"
            >{{ item.category }}</v-tab>
          </v-tabs>
        </div>
        <v-card class="height-auto">
          <div class="fullHeight d-flex">
            <div>
              <v-tabs v-model="tab" vertical>
                <v-tab>计算规则</v-tab>
                <v-tab>参数</v-tab>
              </v-tabs>
            </div>
            <div class="pa-3 width-auto">
              <div class="fullscreen overflow-y-auto">
                <v-tabs-items v-model="tab">
                  <v-tab-item>
                    <div class="text-right mb-3"><v-btn color="primary" @click="onUse">使用规则</v-btn></div>
                    <div v-html="ruleItem.calculateFormulas?.[0]?.content"></div>
                  </v-tab-item>
                  <v-tab-item class="pa-3">
                    <div class="text-right mb-3"><v-btn color="primary" @click="onUseParam">使用参数</v-btn></div>
                    <v-expansion-panels
                      v-model="panelActive"
                      multiple
                    >
                      <v-expansion-panel
                        v-for="(item,i) in ruleItem.calculateConfigurations"
                        :key="i"
                      >
                        <v-expansion-panel-header>{{ item.name }}</v-expansion-panel-header>
                        <v-expansion-panel-content>
                          <div class="d-flex mb-3">
                            <div>参数名称：</div>
                            <div>{{ item.name }}</div>
                          </div>
                          <div class="d-flex">
                            <div>参数值：</div>
                            <div>
                              <template v-if="item.valueCategory === 0">
                                {{ item.value }}
                              </template>
                              <template v-else>
                                <v-card outlined>
                                  <v-simple-table style="min-width: 500px;">
                                    <template v-slot:default>
                                      <thead>
                                        <tr>
                                          <th class="text-left"> 名称 </th>
                                          <th class="text-left"> 值 </th>
                                        </tr>
                                      </thead>
                                      <tbody>
                                        <tr
                                          v-for="val in JSON.parse(item.value)"
                                          :key="val.name"
                                        >
                                          <td>{{ val.name }}</td>
                                          <td>{{ val.value }}</td>
                                        </tr>
                                      </tbody>
                                    </template>
                                  </v-simple-table>
                                </v-card>
                              </template>
                            </div>
                          </div>
                        </v-expansion-panel-content>
                      </v-expansion-panel>
                    </v-expansion-panels>
                  </v-tab-item>
                </v-tabs-items>
              </div>
            </div>
          </div>
        </v-card>
      </div>
    </v-navigation-drawer>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
// import NonePage from '@/components/Common/empty.vue'
import EditBase from './editBase.vue'
import axios from 'axios'
import {
  api
} from '@/api/dataGovernance'
export default {
  name: 'editPage',
  components: { Editor, Toolbar, EditBase },
  props: {
    itemData: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      drawer: false,
      editor: null,
      // editorHtml: null,
      toolbarConfig: {
        toolbarKeys: [
          'headerSelect',
          // 分割线
          '|',
          'bold',
          'italic'
        ]
      },
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default', // or 'simple'
      loading: false,
      items: [],
      rulesItems: [],
      active: 0,
      tab: 0,
      panelActive: [],
      clickItem: null,
      clickId: null,
      changeObj: {
        script_content: '',
        script_requirement: '',
        source_table: null,
        target_table: null
      }
    }
  },
  computed: {
    ruleItem () {
      if (!this.clickItem) {
        return {
          calculateFormulas: [],
          calculateConfigurations: []
        }
      }
      return this.clickItem[this.active]
    }
  },
  async created () {
    this.loading = true
    if (Object.keys(this.itemData).length) {
      await this.getDetails()
    }
    await this.getList()
    this.loading = false
  },
  beforeDestroy () {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    onCreated (editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onUse () {
      this.changeObj.script_requirement += `\n${this.ruleItem.calculateFormulas?.[0]?.content}`
    },
    onUseParam () {
      const str = this.ruleItem.calculateConfigurations.reduce((t, v) => {
        return t + `<p>${v.name}=${v.value}</p>`
      }, '\n')
      this.changeObj.script_requirement += str
      console.log(str)
    },
    // 详情
    async getDetails () {
      try {
        const { data } = await api.getDataFlowDetails(this.itemData.id)
        this.$nextTick(() => {
          this.$refs.editBaseRefs.setValues(data)
        })
        this.changeObj = {
          script_content: data.script_content,
          script_requirement: data.script_requirement,
          source_table: data.source_table || '',
          target_table: data.target_table || ''
        }
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    async getList () {
      try {
        const { data } = await this.fetchData('/op/base/performance/solution/page', {
          page: {
            size: 999,
            current: 1
          }
        })
        this.items = data.records.map(e => e.entity)
      } catch (err) {
        this.items = []
        this.$snackbar.error(err)
      }
    },
    fetchData (url, params) {
      return new Promise((resolve, reject) => {
        axios.post(url, params, { // 配置对象
          headers: {
            'Content-Type': 'application/json'
          },
          timeout: 5000, // 超时时间(毫秒)
          responseType: 'json' // 响应数据类型
        }).then(res => {
          const { data } = res
          if (data.code !== 20000) {
            reject(data.message)
            return
          }
          resolve(data)
        }).catch(reject)
      })
    },
    async onGenerating () {
      // const text = this.editor.getText()
      if (!this.changeObj.script_requirement) {
        this.$snackbar.warning('请输入内容')
        return
      }
      // if (!this.changeObj.source_table) {
      //   this.$snackbar.warning('请先填写来源表')
      //   return
      // }
      // if (!this.changeObj.target_table) {
      //   this.$snackbar.warning('请先填写目标表')
      //   return
      // }
      // if
      this.loading = true
      try {
        const { data } = await api.getDataFlowScript({
          request_data: this.changeObj.script_requirement,
          input: this.changeObj.source_table || '',
          output: this.changeObj.target_table || ''
        })
        // this.changeObj.script_requirement = text
        this.changeObj.script_content = data.script_content
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    },
    async handleSubmit () {
      const params = this.$refs.editBaseRefs.getValue()
      if (!params) {
        return
      }
      // const { script_content: scriptContent, source_table: sourceTable, target_table: targetTable } = this.changeObj
      // const { script_content: scriptContent } = this.changeObj
      // if (!scriptContent) {
      //   this.$snackbar.warning('请先生成脚本')
      //   return
      // }
      // if (!sourceTable) {
      //   this.$snackbar.warning('请先填写来源表')
      //   return
      // }
      // if (!targetTable) {
      //   this.$snackbar.warning('请先填写目标表')
      //   return
      // }
      const query = {
        ...params,
        ...this.changeObj
      }
      const isEdit = Object.keys(this.itemData).length > 0
      try {
        if (isEdit) {
          await api.updateDataFlow(this.itemData.id, query)
        } else {
          await api.addDataFlow(query)
        }
        this.$snackbar.success(isEdit ? '更新成功' : '新增成功')
        this.$emit('success')
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    async onClick (e) {
      try {
        this.loading = true
        const { data } = await this.fetchData('/op/base/performance/solution/detail', {
          performanceSolutionId: e.performanceSolutionId
        })
        this.clickId = data.entity.performanceSolutionId
        if (!data.performanceSolutionDetailRespCategoryVos.length) {
          this.loading = false
          this.$snackbar.warning('该方案暂无数据')
          this.drawer = false
          return
        }
        this.clickItem = data.performanceSolutionDetailRespCategoryVos
        this.drawer = true
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  color: #1976D2;
  font-weight: 600;
}
.fullscreen {
  height: 100%;
  width: 100%;
}
.fullHeight {
  height: 100%;
}
.width-auto {
  width: 0;
  flex: 1;
}
.height-auto {
  height: 0;
  flex: 1;
}
::v-deep ul {
  padding-left: 0;
}
</style>
