<template>
  <div class="box d-flex pa-3">
    <!-- 新增模型 -->
    <div class="box-left mr-3">
      <m-card class="box-left-card" :px5="false" :title="`数据${ isModel ? '模型' : '资源'}选择`">
        <template #title>
          <v-switch
            v-if="!itemData.id"
            v-model="isModel"
            hide-details
            dense
            class="mt-0"
            label="使用模型"
            @change="handleSwitch"
          ></v-switch>
        </template>
        <data-list
          ref="dataList"
          :is-model="isModel"
          :selected="selected"
          @use="handleChange"
          @useAll="handleChangeAll"
        ></data-list>
      </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">
              <v-simple-table
                ref="table"
                fixed-header
                style="height: 0; flex: 1"
                :height="height + 'px'"
              >
                <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-right th-title">
                        操作
                        <EditMetadataAdd @use="onUse"></EditMetadataAdd>
                        <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" style="pointer-events: none;" class="text-center grey--text">
                      <td colspan="5">没有数据，可通过左侧数据资源进行选择</td>
                    </tr>
                    <tr
                      v-for="(item, index) in selected"
                      :key="`${item.id}-${item.originId}`"
                    >
                      <td>{{ item.name_zh }}</td>
                      <td>{{ item.data_type }}</td>
                      <td v-if="!itemData.id">
                        {{ item.master_data?.name_zh || '--' }}
                      </td>
                      <td v-else>
                        <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?.name_zh" @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>
                    <!-- <tr
                      v-for="(item, index) in addItems"
                      :key="index"
                    >
                      <td>
                        <v-text-field
                          label="元数据名称"
                          v-model="item.name"
                          outlined dense hide-details></v-text-field>
                      </td>
                      <td>
                        <v-text-field v-model="item.data_type" outlined dense hide-details></v-text-field></td>
                      <td>
                        <m-editTable
                          :text="item.master_data?.name || '--'"
                          :init="originInit"
                          item-label="title"
                          item-value="id"
                          @use="$el => originSave($el, item)"
                        >
                          <template #title>
                            [{{ item.master_data?.name }}] 主数据选择
                          </template>
                        </m-editTable>
                        <v-btn color="error" icon v-if="item.master_data?.name" @click="originClose(item)">
                          <v-icon>mdi-close</v-icon>
                        </v-btn>
                      </td>
                      <td>
                        <m-editTable
                          :text="item.data_standard?.name || '--'"
                          :init="standardInit"
                          item-label="name"
                          item-value="id"
                          @use="$el => standardSave($el, item)"
                        >
                          <template #title>
                            [{{ item.name }}] 数据标准选择
                          </template>
                        </m-editTable>
                        <v-btn color="error" icon v-if="item.data_standard?.name" @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>
                        <v-btn
                          color="primary"
                          text
                          @click="handleRemove(index)"
                        >
                          保存
                        </v-btn>
                      </td>
                    </tr> -->
                  </tbody>
                </template>
              </v-simple-table>
            </div>
          </v-tab-item>
          <!-- <v-tab-item>
            <ExecuteScript></ExecuteScript>
          </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;" hideEnName :item-data="itemData"></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 ExecuteScript from './executeScript'
import EditBase from './editBase'
import MEditTable from '../../components/editTable'
// import MForm from '@/components/Form/list'
// import { metadataType } from '@/utils/dataGovernance'
import EditMetadataAdd from './editMetadataAdd'
import { api } from '@/api/dataGovernance'
export default {
  name: 'modules-edit',
  components: {
    EditMetadataAdd,
    MCard,
    MEditTable,
    EditBase,
    DataList
    // MForm,
    // ExecuteScript
  },
  props: {
    itemData: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      code: '',
      isModel: false,
      tab: 0,
      overlay: false,
      show: false,
      height: 0,
      selected: [], // 已选资源
      addItems: [], // 新增资源
      sendBtn: [
        {
          icon: 'mdi-send-variant',
          key: 'submit',
          color: 'primary',
          loading: false,
          disabled: false,
          text: '确认提交',
          handle: this.handleSubmit
        }
      ],
      loading: false
    }
  },
  created () {
    if (Object.keys(this.itemData).length === 0) {
      return
    }
    this.isModel = this.itemData.data_model.origin !== 'resource'
  },
  mounted () {
    this.$nextTick(() => {
      this.height = this.$refs.table.$el.clientHeight
      if (Object.keys(this.itemData).length === 0) {
        return
      }
      this.selected = this.itemData.data_model.resource_selected.reduce((r, v) => {
        r.push(...v.meta_ids.map(_e => {
          return {
            ..._e,
            originId: v.resource_id,
            originName: v.data_resource
          }
        }))
        if (this.itemData?.id === 176) r = r.reverse()
        return r
      }, [])
    })
  },
  methods: {
    onUse (item) {
      this.selected.push({
        data_standard: {
          id: null,
          name_zh: null
        },
        data_type: item.data_type,
        name_en: item.name_en,
        id: item.id,
        master_data: {
          name_zh: null,
          id: null
        },
        name_zh: item.name_zh,
        originId: null,
        originName: null
      })
    },
    handleSwitch () {
      this.selected.splice(0, this.selected.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,
                title: `[${types[e.type]}] ${e.name}`
              }
            }),
            total: data.total
          })
        }).catch(error => {
          reject(error)
        })
      })
    },
    originSave (use, item) {
      item.master_data = {
        name_zh: use.title,
        id: use.id
      }
    },
    originClose (item) {
      item.master_data = {
        name_zh: null,
        id: null
      }
    },
    standardSave (use, item) {
      item.data_standard = {
        id: use.id,
        name_zh: use.name
      }
    },
    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
    },

    // 清空
    handleClear () {
      this.$confirm('提示', '是否确认清空').then(() => {
        this.selected.splice(0, this.selected.length)
        this.$refs.dataList.initUsed()
      })
    },
    // 使用
    async handleChange (node) {
      this.tab = 0
      this.selected.push({
        ...node
      })
    },
    async handleChangeAll (nodes) {
      this.tab = 0
      this.selected.push(...nodes)
    },
    // 移除
    handleRemove (index) {
      this.selected.splice(index, 1)
      // 更新长度
      this.$refs.dataList.initUsed()
    },
    // handleAdd () {
    //   // 新增一个元数据
    //   this.addItems.push({
    //     master_data: {},
    //     data_standard: {},
    //     name: null,
    //     en_name: null,
    //     data_type: null
    //   })
    // },
    async handleSubmit () {
      const obj = this.$refs.base.getValue()
      if (!obj) {
        return
      }
      const idList = this.selected.reduce((r, v) => {
        if (this.itemData.id) {
          r.push({
            master_data: v.master_data?.id ?? null,
            data_standard: v.data_standard?.id ?? null,
            name_zh: v.name_zh,
            name_en: v.name_en,
            data_type: v.data_type,
            id: v.id
          })
          return r
        }
        // 查找是否存在该资源 || 模型
        const item = r.find(e => {
          return this.isModel ? e.model_id === v.originId : e.resource_id === v.originId
        })
        if (!item) {
          const obj = {
            metaData: [{
              id: v.id,
              data_standard: v.data_standard?.id ?? null
            }]
          }
          if (this.isModel) {
            r.push({ ...obj, model_id: v.originId })
          } else {
            r.push({ ...obj, resource_id: v.originId })
          }
          return r
        }
        item.metaData.push({
          id: v.id,
          data_standard: v.data_standard?.id ?? null
        })
        return r
      }, [])
      const query = {
        blood_resource: this.selected[0]?.originId ?? null,
        ...obj
      }
      if (this.itemData.id) {
        Object.assign(query, {
          id: this.itemData.id,
          origin: this.itemData.origin,
          metaData: idList
        })
      } else {
        Object.assign(query, {
          origin: this.isModel ? 'model' : 'resource',
          id_list: idList
        })
      }
      this.overlay = true
      const subApi = this.itemData.id ? api.updateModel : this.isModel ? api.addModelByModel : api.addModel
      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>
  .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>
