<template>
  <div class="box d-flex pa-3">
    <!-- 新增模型 -->
    <div class="box-left mr-3">
      <m-card class="box-left-card" bodyStyle="display: flex; flex-direction: column;" :px5="false" title="DDL选择" v-loading="loadingUpload">
        <template #title>
          <upload-btn
            text
            color="primary"
            @change="handleChangeFile"
          >
            <v-icon left>mdi-import</v-icon>
            导入DDL
          </upload-btn>
        </template>
        <div class="pa-3">
          <v-text-field
            v-model="search"
            label="名称查找"
            placeholder="请输入名称"
            dense
            hide-details
            outlined
            clearable
            append-icon="mdi-magnify"
            @input="handleSearch"
            @click:append="handleSearch"
            @keydown.enter.native="handleSearch"
          ></v-text-field>
          <div class="pt-3 pl-3 d-flex justify-end">
            共 {{ Object.keys(items).length }} 个数据
          </div>
        </div>
        <div class="scrollBox">
          <v-expansion-panels>
            <v-expansion-panel
              v-for="(item, key) in items"
              :key="key"
            >
              <v-expansion-panel-header>
                <div class="d-flex justify-space-between align-center">
                  <div>
                    <v-chip color="error" small v-if="item.exist">已存在</v-chip>
                    {{ key }}
                  </div>
                  <div>
                    <v-btn
                      :disabled="select === key"
                      text
                      color="primary"
                      small
                      @click.stop="handleSelect(item, key)">使用该资源</v-btn>
                  </div>
                </div>
              </v-expansion-panel-header>
              <v-expansion-panel-content>
                <v-simple-table
                  fixed-header
                  height="400px"
                >
                  <template v-slot:default>
                    <thead>
                      <tr>
                        <th class="text-left">
                          元数据中文名
                        </th>
                        <th class="text-left">
                          元数据英文名
                        </th>
                        <th class="text-left">
                          元数据类型
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="val in item.meta" :key="key + val.name_zh">
                        <td>{{ val.name_zh }}</td>
                        <td>{{ val.name_en }}</td>
                        <td>{{ val.data_type }}</td>
                      </tr>
                    </tbody>
                  </template>
                </v-simple-table>
              </v-expansion-panel-content>
            </v-expansion-panel>
          </v-expansion-panels>
        </div>
      </m-card>
    </div>
    <div class="box-right">
      <v-card class="box-right-card d-flex flex-column" elevation="5">
        <div>
          <v-tabs v-model="tab">
            <v-tab>元数据设置</v-tab>
            <v-tab>执行脚本</v-tab>
            <v-tab>基础信息配置</v-tab>
          </v-tabs>
        </div>

        <v-tabs-items v-model="tab">
          <v-tab-item>
            <div class="box-right-card-content pa-3 d-flex flex-column">
              <!-- <div class="d-flex">
                <m-form style="flex: 1" ref="form" :items="formItems"></m-form>
                <v-btn color="primary" class="ml-3" @click="handleAdd">添加</v-btn>
              </div> -->
              <v-simple-table
                ref="table"
                fixed-header
                style="height: 0; flex: 1"
                :height="height"
              >
                <template v-slot:default>
                  <thead>
                    <tr>
                      <th class="text-left th-title">
                        元数据
                      </th>
                      <th class="text-left th-title">
                        元数据英文名
                      </th>
                      <th class="text-left th-title">
                        数据类型
                      </th>
                      <th class="text-left th-title">
                        主数据
                      </th>
                      <th class="text-left th-title">
                        标准
                      </th>
                      <th class="text-right th-title">
                        操作
                        <v-btn
                          v-if="selected.length"
                          small
                          color="error"
                          class="ml-3"
                          @click="handleClear">清空</v-btn>
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-if="selected.length === 0" style="pointer-events: none;" class="text-center grey--text">
                      <td colspan="5">没有数据，可通过左侧数据资源进行选择</td>
                    </tr>
                    <tr
                      v-for="(item, index) in selected"
                      :key="item.name_zh"
                    >
                      <td>{{ item.name_zh }}</td>
                      <td>{{ item.name_en }}</td>
                      <td>
                        <m-editTable
                          :text="item.data_type"
                          :size="999"
                          :init="initDataType"
                          @use="$el => item.data_type = $el.value"
                        >
                          <template #title>
                            [{{ item.name_zh }}]元数据类型选择
                          </template>
                        </m-editTable>
                      </td>
                      <td>
                        <m-editTable
                          :text="item.master_data?.name_zh || '--'"
                          :init="originInit"
                          item-label="name_zh"
                          item-value="id"
                          @use="$el => originSave($el, item)"
                        >
                          <template #title>
                            [{{ item.name_zh }}] 主数据选择
                          </template>
                        </m-editTable>
                        <v-btn color="error" icon v-if="item.master_data?.id" @click="originClose(item)">
                          <v-icon>mdi-close</v-icon>
                        </v-btn>
                      </td>
                      <td>
                        <m-editTable
                          :text="item.data_standard?.name_zh || '--'"
                          :init="standardInit"
                          item-label="name_zh"
                          item-value="id"
                          @use="$el => standardSave($el, item)"
                        >
                          <template #title>
                            [{{ item.name_zh }}] 数据标准选择
                          </template>
                        </m-editTable>
                        <v-btn color="error" icon v-if="item.data_standard?.name_zh" @click="standardClose(item)">
                          <v-icon>mdi-close</v-icon>
                        </v-btn>
                      </td>
                      <td class="text-right">
                        <v-btn
                          color="error"
                          text
                          @click="handleRemove(index)"
                        >
                          移除
                        </v-btn>
                      </td>
                    </tr>
                  </tbody>
                </template>
              </v-simple-table>
            </div>
          </v-tab-item>
          <v-tab-item>
            <execute-script></execute-script>
          </v-tab-item>
          <v-tab-item>
            <v-overlay :value="overlay">
              <div class="d-flex flex-column align-center justify-center" style="width: 300px;">
                <div class="mb-3">正在提交</div>
                <v-progress-linear
                  color="primary"
                  indeterminate
                  rounded
                  height="6"
                ></v-progress-linear>
              </div>
            </v-overlay>
            <div class="pa-3 d-flex align-center justify-center flex-column">
              <edit-base ref="base" style="max-width: 500px;" :item-data="itemData" :names="names"></edit-base>
              <v-btn
                class="buttons"
                color="primary"
                rounded
                :disabled="loading"
                @click="handleSubmit"
              >
                <v-icon left>mdi-send-variant</v-icon>
                保存
              </v-btn>
            </div>
          </v-tab-item>
        </v-tabs-items>
      </v-card>
    </div>
  </div>
</template>

<script>
import MCard from '@/components/MCard'
// import DataList from './dataList'
import UploadBtn from '@/components/UploadBtn'
import ExecuteScript from './executeScript'
// import MForm from '@/components/Form/list'
import EditBase from './editBase'
import { api } from '@/api/dataGovernance'
import MEditTable from '../../components/editTable'
import { metadataType } from '@/utils/dataGovernance'
export default {
  name: 'modules-edit',
  components: {
    MCard,
    EditBase,
    MEditTable,
    // MForm,
    UploadBtn,
    ExecuteScript
  },
  props: {
    itemData: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      // formItems: {
      //   options: [
      //     {
      //       type: 'text',
      //       key: 'name_zh',
      //       outlined: true,
      //       dense: true,
      //       col: 4,
      //       value: '',
      //       label: '元数据名称',
      //       rules: [v => !!v || '请输入元数据名称']
      //     },
      //     {
      //       type: 'text',
      //       key: 'name_en',
      //       outlined: true,
      //       dense: true,
      //       col: 4,
      //       value: '',
      //       label: '元数据英文名称',
      //       rules: [v => !!v || '请输入元数据英文名称']
      //     },
      //     {
      //       type: 'autocomplete',
      //       key: 'data_type',
      //       outlined: true,
      //       dense: true,
      //       col: 4,
      //       value: '',
      //       label: '元数据类型',
      //       items: metadataType,
      //       rules: [v => !!v || '请选择元数据类型']
      //     }
      //   ]
      // },
      metadataType: metadataType,
      loadingUpload: false,
      isModel: false,
      tab: 0,
      overlay: false,
      show: false,
      height: 0,
      selected: [], // 已选资源
      // selectItem: null,
      sendBtn: [
        {
          icon: 'mdi-send-variant',
          key: 'submit',
          color: 'primary',
          loading: false,
          disabled: false,
          text: '确认提交',
          handle: this.handleSubmit
        }
      ],
      names: {},
      loading: false,
      // relationList: [],
      // targetRelation: null,
      search: null,
      items: {},
      origin: {},
      select: null
    }
  },
  created () {
    if (!this.itemData.data_model) {
      return
    }
    this.selected = this.itemData.data_model.resource_selected.reduce((r, v) => {
      r.push(...v.meta_ids)
      return r
    }, [])
  },
  mounted () {
    this.$nextTick(() => {
      this.height = this.$refs.table.$el.clientHeight
    })
  },
  methods: {
    initDataType () {
      return new Promise((resolve, reject) => {
        resolve({
          items: metadataType,
          total: metadataType.length
        })
      })
    },
    originInit (query) {
      return new Promise((resolve, reject) => {
        api.getResourceAndModelList(query).then(({ data }) => {
          // const types = { resource: '数据资源', model: '数据模型' }
          resolve({
            items: data.records.map(e => {
              return {
                ...e,
                name_zh: e.name_zh
                // title: `[${types[e.type]}] ${e.name}`
              }
            }),
            total: data.total
          })
        }).catch(error => {
          reject(error)
        })
      })
    },
    originSave (use, item) {
      item.master_data = {
        id: use.id,
        name_zh: use.name_zh
      }
    },
    originClose (item) {
      item.master_data = {
        id: null,
        name_zh: null
      }
    },
    handleSelect (item, key) {
      this.select = key
      this.selected = [...item.meta]
      this.names = {
        name_zh: item.table_info?.name_zh,
        name_en: item.table_info?.name_en
      }
    },
    async handleChangeFile (file) {
      this.loadingUpload = true
      const query = new FormData()
      query.append('file', file)
      try {
        const { data } = await api.resourceParseDDL(query)
        this.select = null
        this.items = data.reduce((res, item) => {
          const { columns, exist, table_info: tableInfo } = item
          const key = tableInfo.name_zh || tableInfo.name_en
          res[key] = {
            exist,
            table_info: tableInfo,
            meta: columns.map(e => {
              return {
                ...e,
                id: null,
                data_standard: null,
                master_data: {
                  id: null,
                  name_zh: null
                }
              }
            })
          }
          return res
        }, {})
        this.origin = { ...this.items }
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loadingUpload = false
      }
    },
    handleSearch () {
      if (!this.search) {
        this.items = { ...this.origin }
        return
      }
      this.items = Object.keys(this.origin).filter(e => e.includes(this.search)).reduce((res, key) => {
        res[key] = this.origin[key]
        return res
      }, {})
    },
    standardSave (use, item) {
      item.data_standard = {
        id: use.id,
        name_zh: use.name_zh
      }
    },
    standardInit (query) {
      return new Promise((resolve, reject) => {
        api.dataStandardList(query).then(({ data }) => {
          resolve({
            items: data.records,
            total: data.total
          })
        }).catch(error => {
          reject(error)
        })
      })
    },
    standardClose (item) {
      item.data_standard = null
    },
    handleShow () {
      this.show = true
    },
    // handleAdd () {
    //   if (!this.$refs.form.validate()) {
    //     return
    //   }
    //   const obj = this.formItems.options.reduce((r, v) => {
    //     r[v.key] = v.value
    //     return r
    //   }, {})
    //   this.selected.push({
    //     ...obj,
    //     id: null,
    //     data_standard: null,
    //     origin: null,
    //     originName: null
    //   })
    // },
    // 清空
    handleClear () {
      this.$confirm('提示', '是否确认清空').then(() => {
        this.selected.splice(0, this.selected.length)
        this.select = null
        //   this.targetRelation = null
        // this.$refs.dataList.initUsed()
      //   this.getModelRelation()
      })
    },
    // 移除
    handleRemove (index) {
      this.selected.splice(index, 1)
      // 更新长度
      this.$refs.dataList.initUsed()
    },
    async handleSubmit () {
      if (!this.selected.length) {
        this.$snackbar.error('请选择元数据')
        return
      }
      const obj = this.$refs.base.getValue()
      if (!obj) {
        return
      }
      const idList = [
        {
          metaData: this.selected.map(e => {
            return {
              id: e.id,
              name_en: e.name_en,
              data_type: e.data_type,
              name_zh: e.name_zh,
              comment: e.comment,
              is_primary: e.is_primary,
              nullable: e.nullable,
              data_standard: e.data_standard?.id ?? null,
              master_data: e.master_data?.id ?? null
            }
          })
        }
      ]
      const query = {
        ...obj,
        name_en: this.names.name_en,
        origin: 'sql'
      }
      if (this.itemData.id) {
        Object.assign(query, {
          id: this.itemData.id,
          ...idList[0]
        })
      } else {
        Object.assign(query, {
          id_list: idList
        })
      }
      this.overlay = true
      const subApi = this.itemData.id ? api.updateModel : api.saveModelByDDL
      try {
        await subApi(query)
        this.$snackbar.success('操作成功')
        this.$emit('close')
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.overlay = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.scrollBox {
  height: 0;
  flex: 1;
  overflow: auto;
}
  .th-title {
    font-size: 14px !important;
    font-weight: 600;
    color: #1976D2 !important;
  }
  ::v-deep .v-banner__wrapper {
    padding: 8px 16px !important;
  }
  .box {
    width: 100%;
    &-left {
      width: 600px;
      &-card {
        height: 100%;
        display: flex;
        flex-direction: column;
      }
    }
    &-right {
      width: 0;
      flex: 1;
      &-card {
        height: 100%;
        &-content {
          height: 100%;
          overflow: auto;
        }
      }
    }
    &-base {
      position: relative;
      width: 400px;
      height: 100%;
      &-content {
        height: 100%;
        &-control {
          height: 100%;
          &-edit {
            flex: 1;
            overflow: auto;
          }
        }
      }
    }
  }
  .point {
    cursor: pointer;
  }
  .title {
    color: #1976D2;
    font-weight: 600;
  }
  ::v-deep .v-tabs-items {
  height: 0;
  flex: 1;
  .v-window-item {
    overflow: auto;
    height: 100%;
  }
  .v-window__container {
    height: 100%;
  }
}
</style>
