<template>
  <div>
    <el-dialog append-to-body
               @open="open"
               title="大屏配置"
               :close-on-click-modal="false"
               v-model="show"
               width="60%">
      <div style="margin-bottom: 20px;">
        <el-button @click="openBlock"
                   type="primary">导入组件</el-button>
      </div>

      <monaco-editor v-model="json"
                     height="400"
                     language="json"></monaco-editor>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleExport"
                     type="primary">导出部署</el-button>
          <el-button @click="exportData"
                     type="primary">导出配置</el-button>
          <el-button @click="importData"
                     type="primary">确认导入</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog append-to-body
               @open="open"
               class="avue-dialog"
               title="导入组件(支持数组/对象)"
               :close-on-click-modal="false"
               v-model="show1"
               width="80%">
      <div style="margin-bottom:20px;">
        <el-button @click="openSc"
                   type="primary">收藏组件</el-button>
        <el-button @click="openScreen"
                   type="primary">大屏组件</el-button>
      </div>
      <monaco-editor v-model="json1"
                     height="500"
                     language="json"></monaco-editor>
      <template #footer>
        <span class="dialog-footer">
          <el-popconfirm title="是否重构组件ID?"
                         confirm-button-text="是"
                         cancel-button-text="否"
                         @confirm="importBlock(true)"
                         @cancel="importBlock(false)">
            <template #reference>
              <el-button type="primary">确认导入</el-button>
            </template>
          </el-popconfirm>
        </span>
      </template>
    </el-dialog>
    <el-dialog append-to-body
               class="avue-dialog"
               title="导入大屏组件"
               :close-on-click-modal="false"
               v-model="show2"
               width="60%">
      <el-input v-model="search"
                placeholder="请输入大屏的ID">
        <template #append>
          <el-button icon="el-icon-search"
                     @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
      <avue-crud v-loading="loading"
                 v-bind="$loadingParams"
                 @selection-change="selectionChange"
                 :option="option"
                 :data="data">
      </avue-crud>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importScreen"
                     type="primary">确认导入</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog append-to-body
               class="avue-dialog"
               title="导入收藏组件"
               v-model="show3"
               width="70%">
      <component-list v-if="show3"
                      :activeName="3"
                      @change="handleApiChange"
                      :menu="false"></component-list>
    </el-dialog>

    <export-tip ref="exportTip"></export-tip>
  </div>
</template>

<script>

import exportTip from '@/page/components/export-tip.vue';
import { config as defaultConfig } from '@/option/config'
import MonacoEditor from '@/page/components/monaco-editor'
import { getObj as getCompObj } from '@/api/components'
import componentList from '@/page/list/components.vue'
import { getObj } from '@/api/visual'
import { importArrayBlock } from '@/utils/utils';
export default {
  components: { MonacoEditor, componentList, exportTip },
  inject: ["contain"],
  data () {
    return {
      show: false,
      show1: false,
      show2: false,
      show3: false,
      json: {},
      json1: '',
      search: '',
      group: '',
      selection: [],
      option: {
        tip: false,
        header: false,
        selection: true,
        loading: false,
        delBtn: false,
        disabled: true,
        editBtnText: '查看',
        updateBtn: false,
        rowKey: 'index',
        column: [{
          label: '组件类型',
          prop: 'title',
          span: 24
        }, {
          label: '组件名称',
          prop: 'name',
          span: 24
        }, {
          label: '代码',
          hide: true,
          span: 24,
          rows: 8,
          type: 'textarea',
          prop: 'code'
        }]
      },
      data: []
    }
  },
  methods: {
    handleExport () {
      this.$refs.exportTip.handleOpen({ id: this.contain.id, title: this.contain.config.name })
    },
    handleApiChange (item) {
      getCompObj(item.id).then(res => {
        const data = res.data.data;
        this.json1 = JSON.parse(data.content);
        this.show3 = false;
      })
    },
    selectionChange (list) {
      this.selection = list;
    },
    handleSearch () {
      this.loading = true;
      this.data = [];
      getObj(this.search).then(res => {
        this.loading = false;
        const data = res.data.data
        if (data) {
          let list = JSON.parse(data.config.component)
          list.forEach(ele => {
            ele.code = JSON.stringify(this.deepClone(ele), null, 4)
          })
          this.data = list;
        }
      })
    },
    open () {
      this.json = {
        detail: this.contain.config,
        component: this.contain.nav
      }
      this.json1 = ''
    },
    importBlock (isId) {
      try {
        // 验证数据有效性
        if (this.json1 === undefined || this.json1 === null || this.json1 === '') {
          this.$message.warning('请先添加组件数据');
          return;
        }

        // 解析JSON数据
        let json;
        if (typeof this.json1 === 'string') {
          try {
            json = JSON.parse(this.json1);
          } catch (parseError) {
            console.error('JSON解析错误:', parseError);
            this.$message.error('JSON格式错误，请检查导入的数据格式');
            return;
          }
        } else {
          json = this.json1;
        }

        // 获取当前组的ID
        const group = this.contain.group;

        // 判断是数组还是对象
        const isArray = Array.isArray(json);
        const jsonArray = isArray ? json : [json];
        
        // 确保至少有一个组件
        if (jsonArray.length === 0) {
          this.$message.warning('没有可导入的组件');
          return;
        }

        // 处理组件数据
        importArrayBlock(jsonArray, group, { isId });
        
        // 添加到导航
        if (isArray) {
          this.contain.nav.unshift(...json);
        } else {
          this.contain.nav.unshift(json);
        }
        
        // 关闭对话框
        this.show = false;
        this.show1 = false;
        
        // 显示成功消息
        this.$message.success('导入组件成功');
      } catch (err) {
        console.error('导入组件错误:', err);
        this.$message.error(`导入数据错误: ${err.message || '未知错误'}`);
      }
    },
    openBlock () {
      this.show1 = true
    },
    importScreen () {
      let list = this.deepClone(this.selection);
      list.forEach(ele => {
        delete ele.$index
        delete ele.code
      })
      this.show2 = false
      this.json1 = list;
    },
    openSc () {
      this.show3 = true
    },
    openScreen () {
      this.data = []
      this.selection = []
      this.search = ''
      this.show2 = true
    },
    importData () {
      try {
        let json = typeof (this.json) == 'string' ? JSON.parse(this.json) : this.json
        json.detail = Object.assign(defaultConfig, json.detail);
        this.contain.config = json.detail
        this.contain.nav = json.component
        this.show = false;
        this.$message.success('数据导入成功')
      } catch (err) {
        console.log(err)
        this.$message.error('导入数据错误')
      }
    },
    exportData () {
      const blob = new Blob([this.json], { type: 'text/plain;charset=utf-8' });
      saveAs(blob, "data.json");
      this.loading = false
      this.$message.success('大屏导出成功')
    }
  }
}
</script>

<style>
</style>