<template>
  <div class="code-gen-datasource">
    <el-tabs type="card">
      <el-tab-pane label="源">
        <el-menu @select="handlerSelect">
          <el-menu-item
            :index="item._id"
            v-for="item in dataSourceList"
            :key="item._id"
            :pdata="item"
            ptype="datasource"
          >
            <i class="el-icon-s-marketing"></i>
            <span slot="title">{{ item.name }}</span>
          </el-menu-item>
        </el-menu>
      </el-tab-pane>
      <el-tab-pane label="DB">
        <el-form class="toolbar" :model="form">
          <pro-option-datasource
            :target="dbsSourceOption.target"
            :option="dbsSourceOption.option"
          >
            <template slot-scope="{ scope }">
              <pro-select
                v-model="form.selectDb"
                :dataSource="scope.dataSource"
                label="库"
                labelWidth="30px"
              />
            </template>
          </pro-option-datasource>
        </el-form>
        <el-menu @select="handlerSelect">
          <el-menu-item
            :pdata="item"
            ptype="db"
            :index="item.value"
            v-for="item in findTablesByDb.formatDatas || []"
            :key="item.value"
          >
            <i class="el-icon-s-grid"></i>
            <span slot="title">{{ item.label }}</span>
          </el-menu-item>
        </el-menu>
      </el-tab-pane>
      <el-tab-pane label="集">
        <el-menu @select="handlerSelect">
          <el-menu-item 
          :pdata="item"
          ptype="dataset"
          :index="item._id" 
           v-for="item in ($store.dataSet.formatDatas || [])" 
           :key="item._id">
            <i class="el-icon-coin"></i>
            <span slot="title">{{item.name}}</span>
          </el-menu-item>
        </el-menu>
      </el-tab-pane>
    </el-tabs>
    <transition name="el-left-out">
      <div
        class="popup-datasource-factor-list"
        v-show="visible"
        ref="popupmenu"
      >
        <div class="toolbar">
          <pro-action
            icon="el-icon-plus"
            custom-class="code-gen-dialog"
            :splitButton="true"
            toComponentUrl="datasource"
            text="添加数据源"
            title="新增数据源"
            ui-type="dropdown"
          >
            <template slot="subActions">
              <pro-sub-action
                :disabled="selectptype !== 'datasource'"
                icon="el-icon-edit"
                toComponentUrl="datasource"
                :selectpdata="selectpdata"
                @customerCallback="clearSelect"
                title="编辑"
                >编 辑</pro-sub-action
              >
              <pro-sub-action
                :disabled="!(selectptype === 'dataset' || selectptype === 'datasource')"
                icon="el-icon-delete"
                shouldConfirmTxt="确定删除吗?"
                @asyncHandler="handlerDelete"
                @customerCallback="clearSelect"
                >删 除</pro-sub-action
              >
              <pro-sub-action
                icon="el-icon-setting"
                title="数据库配置"
                toComponentUrl="db"
                >配置数据库数据源</pro-sub-action
              >
            </template>
          </pro-action>
          <pro-action
            text="选择确认"
            icon="el-icon-check"
            type="primary"
            @handler="handSaveSelected"
          />
        </div>
        <pro-option-datasource
          :target="dataSourceOption.target"
          :option="dataSourceOption.option"
        >
          <template slot-scope="{ scope }">
            <pro-full-height :decrease="-80">
              <template slot-scope="{ height }">
                <pro-data-table
                  :border="true"
                  rowKey="prop"
                  :dataSource="scope.dataSource"
                  selectModel="multiple"
                  v-bind:selectRows.sync="selectFactor"
                  :enablePagination="false"
                  :columns="columns"
                  :height="parseInt(height) + 'px'"
                >
                </pro-data-table>
              </template>
            </pro-full-height>
          </template>
        </pro-option-datasource>
      </div>
    </transition>
  </div>
</template>
<script>
import Popper from "mars-pro/src/utils/vue-popper";
import ProOptionDatasource from "mars-pro/packages/pro-option-datasource";
import dataSource from "mars-pro/src/pro/mixins/dataSource";
import { post } from "mars-pro/src/pro/request";
import { objectProperty } from "mars-pro/src/pro/util";
import { normalOptions } from "../util";
export default {
  mixins: [
    Popper,
    dataSource("findTablesByDb", null, {
      params: "findTablesByDbParams",
      dataField: "data",
      fieldMap: {
        value: "code",
      },
      async: true,
    }),
  ],
  components: {
    ProOptionDatasource,
  },
  data() {
    this.columns = [
      { prop: "label", label: "label", minWidth: "100px" },
      { prop: "prop", label: "prop", minWidth: "100px" },
      { prop: "datatype", label: "datatype", width: "80px" },
    ];
    return {
      visible: false,
      selectpdata: null,
      selectptype: null,
      selectFactor: null,
      form: {
        selectDb: null,
      },
    };
  },
  props: {
    offset: {
      type: Number,
      default: 100,
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.$nextTick((_) => {
          this.updatePopper();
        });
      } else {
        this.handleHidePopupMenu();
      }
    },
    "form.selectDb": function () {
      const tablesOption = this.tabsSourceOption;
      this.findTablesByDb.updateOption(
        tablesOption.option || {},
        tablesOption.target
      );
      this.findTablesByDb.loadDatas();
    },
  },
  computed: {
    dataSourceList() {
      return this.$store.dataSourceList.formatDatas || [];
    },
    dataSourceKey() {
      return this.selectpdata ? this.selectpdata._id : "null";
    },
    //构建数据源属性配置
    dataSourceOption() {
      let options = this.selectpdata;
      let dbConfig = objectProperty(this.$store.dbConfig, "datas.data.options");
      if (
        this.selectptype === "datasource" &&
        (options = normalOptions(this.selectpdata.options))
      ) {
        return {
          target: options.target,
          option: options,
        };
      }
      //解析数据库表数据
      if (this.selectptype === "db") {
        let options = objectProperty(
          this.$store.dbConfig,
          "datas.data.options"
        );
        if (dbConfig) {
          dbConfig = normalOptions(dbConfig);
          if (dbConfig && dbConfig.columnSource) {
            return {
              target: dbConfig.columnSource.target,
              option: {
                ...dbConfig.columnSource,
                params: () => ({data: {table: this.selectpdata.value}})
              },
            };
          }
        }
      }

      //解析表格列数据
      if (this.selectptype === 'dataset'){
        return {
          target: (this.selectpdata.datas || [])
        }
      }
      return { target: [] };
    },
    dbsSourceOption() {
      let options = objectProperty(this.$store.dbConfig, "datas.data.options");
      if (options) {
        options = normalOptions(options);
        if (options && options.dbSource) {
          return {
            target: options.dbSource.target,
            option: options.dbSource,
          };
        }
      }
      return { target: [] };
    },
    tabsSourceOption() {
      let options = objectProperty(this.$store.dbConfig, "datas.data.options");
      if (options) {
        options = normalOptions(options);
        if (options && options.tableSource) {
          return {
            target: options.tableSource.target,
            option: options.tableSource,
          };
        }
      }
      return { target: [] };
    },
  },
  methods: {
    findTablesByDbParams() {
      return {
        data: {
          schema: this.form.selectDb,
        },
      };
    },
    handleHidePopupMenu() {
      this.doDestroy();
    },
    handlerSelect(index, indexPath, item) {
      const row = item.$attrs.pdata;
      const type = item.$attrs.ptype;
      if (this.selectpdata === row) {
        this.visible = !this.visible;
        return;
      } else {
        this.visible = true;
        this.selectpdata = row;
        this.selectptype = type;
      }
    },
    //删除
    async handlerDelete() {
      if (this.selectptype === "datasource") {
        const { err } = await post("/mock/api/code-gen/data-source/remove", {
          data: {
            _ids: this.selectpdata._id,
          },
        }).done();
        if (!err) {
          this.$store.dataSourceList.loadDatas();
          this.clearSelect();
        }
        return;
      }
      if (this.selectptype === "dataset") {
        const { err } = await post("/mock/api/code-gen/data-set/remove", {
          data: {
            _ids: this.selectpdata._id,
          },
        }).done();
        if (!err) {
          this.$store.dataSet.loadDatas();
          this.clearSelect();
        }
        return;
      }
    },
    clearSelect() {
      this.selectpdata = null;
      this.selectptype = null;
      this.visible = false;
    },
    handSaveSelected(){
      const s = this.selectFactor || []
      for (let i = 0; i < s.length; i++) {
        this.$store.currentDataSet.datas.push({...s[i]})
      }
      this.selectFactor = []
      this.visible = false
    }
  },
  mounted() {
    this.currentPlacement = "right-start";
    this.referenceElm = this.$el;
    this.popperElm = this.$refs.popupmenu;
  },
};
</script>
<style lang="scss">
.code-gen-datasource {
  height: 100%;
  & > .el-tabs {
    display: flex;
    height: 100%;
    flex-direction: column;
    .el-tabs__content {
      overflow: auto;
      flex: 1 1 0;
      .el-tab-pane {
        height: 100%;

        .el-menu {
          border-right: none;
        }
      }
    }
  }
  .toolbar {
    height: 40px;
    line-height: 40px;
    text-align: right;
    padding: 0px 10px;
  }
}
.popup-datasource-factor-list {
  padding: 10px;
  background: #ffffff;
  box-shadow: 5px 0px 10px -10px #000;
  border: 2px dotted #a1b862;
  width: 500px;
  .toolbar {
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
}
</style>