<template>
  <el-card class="box-card">
    <ed-form ref="searchForm" v-model="searchForm" :form-desc="searchFormDesc" :inline="true"
             class="demo-form-inline" @keyup.enter.native="loadData"></ed-form>
    <div v-if="!isChooseModel" class="operator-btn">
      <el-button :loading="operLoading" icon="el-icon-plus" plain size="small" type="primary" @click="showAddView()">
        新增数据源
      </el-button>
      <el-popconfirm
        class="pop-confirm-button"
        title="确定删除所有虚拟列吗？"
        @confirm="deleteAllViCol">
        <el-button slot="reference"  :loading="operLoading" icon="el-icon-minus" plain size="small" type="danger">删除所有虚拟列</el-button>
      </el-popconfirm>
      <el-popconfirm
        class="pop-confirm-button"
        title="确定重载所有虚拟列吗？"
        @confirm="reloadAllViCol">
        <el-button slot="reference" :loading="operLoading" icon="el-icon-refresh-right" plain size="small" type="info">重载所有虚拟列</el-button>
      </el-popconfirm>
      <el-upload :file-list="fileList" :http-request="importDs" :limit="1" :multiple="false"
                 :show-file-list="false" action="" style="display: inline-block;margin-left: 10px">
        <el-button :loading="operLoading" icon="el-icon-upload2" plain size="small" type="primary">导入数据源
        </el-button>
      </el-upload>
    </div>

    <ed-table :columns="tableColumns" :loading="loading" :pagination.sync="pagination" :data="tableData"
              @change="handleTableChange" @current-change="handleCurrentChange">
      <template v-if="!isChooseModel" v-slot:operate="scope">
        <el-button size="mini" type="text" @click="viewPages(scope)">查看页面</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button size="mini" type="text" @click="copyDs(scope.row.id)">复制</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button size="mini" style="color: green" type="text" @click="editDs(scope.row)">编辑</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button size="mini" style="color: red" type="text" @click="openTableOper(scope.row)">表操作</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-dropdown size="mini" trigger="click">
          <span class="el-dropdown-link">
              属性控制<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="openTableModal(scope.row)">表属性</el-dropdown-item>
            <el-dropdown-item @click.native="openViewModal(scope.row)">视图属性</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-divider direction="vertical"></el-divider>
        <el-button :loading="exportLoading" size="mini" type="text"
                   @click="exportDsOne(scope.row.id,scope.row.dataSourceName)">
          导出
        </el-button>
        <el-divider direction="vertical"></el-divider>
        <el-popconfirm
          :title="`确定删除[ ${scope.row.dataSourceName} ]该数据源吗？`"
          @confirm="delDs(scope.row.id)"
        >
          <el-button slot="reference" size="mini" style="color: red" type="text">删除</el-button>
        </el-popconfirm>
      </template>
    </ed-table>

    <ViewPropsModal ref="viewPropsModal"/>
    <TablePropsModal ref="tablePropsModal"/>
    <TableOperationModal ref="tableOperationModal"/>

    <!-- 编辑数据源 -->
    <ed-drawer ref="BasicDrawer" :loading="saveLoading" :visible="visibleDrawer" ok-text="保存并关闭"
               title="编辑数据源"
               @close="visibleDrawer = false;dsForm = {}" @ok="addDsInfo">
      <ed-form ref="dsForm" v-model="dsForm" :form-desc="dsFormDesc" :rules="rules"
               label-position="right"></ed-form>
    </ed-drawer>

  </el-card>
</template>

<script lang="jsx">
import ds from '../../../api/ds'
import ViewPropsModal from './components/ViewPropsModal'
import TablePropsModal from './components/TablePropsModal'
import TableOperationModal from "./components/TableOperationModal";
import useTable from './hooks/useTable'
import {getDictItemByType} from '../../../api/easyData'

export default {
  name: 'DataSourceList',
  props: {
    //是否为选择弹窗,弹窗时只展示部分内容
    isChooseModel: {type: Boolean, default: false},
    columns: {type: Array, default: () => []}
  },
  components: {
    TableOperationModal,
    ViewPropsModal,
    TablePropsModal
  },
  mixins: [useTable],
  data() {
    return {
      exportLoading: false,
      fileList: [],
      loading: false,
      saveLoading: false,
      operLoading: false,
      isEdit: false,
      visibleDrawer: false,
      tableData: [],
      searchForm: {
        dataSourceName: '',
        remark: '',
        classify: '',
        column: '',
        orderBy: 'desc'
      },
      searchFormAttrs: {
        inline: true
      },
      searchFormDesc: [
        {
          label: "数据源名称",
          prop: "dataSourceName",
          children: {
            tags: "el-input",
            attrs: {
              placeholder: "数据源名称",
              size: "small"
            }
          }
        },
        {
          label: "数据源分类",
          prop: "classify",
          children: {
            tags: "el-select",
            attrs: {
              placeholder: "数据源分类",
              size: "small"
            },
            options: []
          }
        },
        {
          label: "数据源备注",
          prop: "remark",
          children: {
            tags: "el-input",
            attrs: {
              placeholder: "数据源备注",
              size: "small"
            }
          }
        },
        {
          btns: [
            {
              text: "查询",
              click: this.searchData,
              attrs: {
                size: "small",
                type: "primary"
              }
            },
            {
              text: "重置",
              click: this.resetForm,
              attrs: {
                size: "small",
              }
            }
          ]
        }
      ],
      dsForm: {
        dataSourceName: '',
        remark: '',
        classify: ''
      },
      dsFormDesc: [
        {
          label: "数据源名称",
          prop: "dataSourceName",
          children: {
            tags: "el-input",
            attrs: {
              placeholder: "数据源名称",
              size: "small"
            }
          }
        },
        {
          label: "数据源分类",
          prop: "classify",
          children: {
            tags: "el-select",
            attrs: {
              placeholder: "数据源分类",
              size: "small"
            },
            options: []
          }
        },
        {
          label: "真实字段",
          prop: "isGeneralColumn",
          children: {
            tags: "el-switch",
            attrs: {
              activeValue: 1,
              inactiveValue: 0,
              size: "small",
            }
          }
        },
        {
          label: "数据源备注",
          prop: "remark",
          children: {
            tags: "el-input",
            attrs: {
              placeholder: "数据源备注",
              size: "small"
            }
          }
        }
      ],
      classifyList: {
        system: '系统',
        other: '其他',
      },
      tableColumns: [],
      // 分页
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [10, 20, 30]
      },
      rules: {
        dataSourceName: [
          {required: true, message: '请输入数据源名称', trigger: 'blur'},
        ],
        remark: [
          {required: true, message: '请选择数据源备注', trigger: 'blur'}
        ],
        classify: [
          {required: true, message: '请选择数据源分类', trigger: 'change'}
        ],
      },
    }
  },
  mounted() {
    this.loadData()
  },
  async created() {
    let res = await getDictItemByType({type: "ed_ds_classify"});
    res.data.forEach(item => {
      this.searchFormDesc[1].children.options.push({
        label: item.itemLabel,
        value: item.itemValue
      })
      this.dsFormDesc[1].children.options.push({
        label: item.itemLabel,
        value: item.itemValue
      })
      this.classifyList[item.itemValue] = item.itemLabel
    })
  },
  methods: {
    /**
     * @name loadData
     * @param param
     * @description 初始化table数据
     */
    async loadData(param) {
      this.loading = true
      let params = param || {}
      Object.assign(params, this.searchForm)
      const resp = await ds.dataSourcePage(params)
      const data = resp.data
      this.tableData = data.records
      this.pagination.current = data.current
      this.pagination.total = data.total
      this.pagination.pageSize = data.size
      this.loading = false
      this.tableColumns = this.columns.length === 0 ? this.getTableColumns() : this.columns
    },

    /**
     * @name searchData
     * @param formName
     * @description 查询
     */
    async searchData(formName) {
      const valid = await this.$refs.searchForm.validate()
      if (valid) {
        let param = {}
        param.pageNo = 1
        param.pageSize = this.pagination.pageSize
        this.loadData(param)
      } else {
        console.log('error submit!!');
        return false;
      }
    },

    /**
     * @name addDsInfo
     * @description 保存并关闭
     */
    addDsInfo() {
      this.$refs.dsForm.validate().then(valid => {
        this.saveLoading = true
        ds.addDsInfo(JSON.stringify(this.dsForm)).then((resp) => {
          if (resp.success) {
            this.$message.success(resp.msg || "操作成功!")
            this.dsForm = {}
            this.visibleDrawer = false
            this.loadData()
          }
        }).finally(() => {
          this.saveLoading = false
        })
      }).catch(err => {
        console.log('error submit!!');
      })
    },

    /**
     * @bane resetForm
     * @description 重置
     */
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.loadData()
    },


    /**
     * @name deleteAllViCol
     * @description 删除所有虚拟列
     */
    deleteAllViCol() {
      this.operLoading = true
      ds.deleteAllViCol({}).then((resp) => {
        if (resp.success) {
          this.$message.success(resp.msg || "操作成功!")
        }
      }).finally(() => {
        this.operLoading = false
      })
    },

    /**
     * @name reloadAllViCol
     * @description 重载所有虚拟列
     */
    reloadAllViCol() {
      this.operLoading = true
      ds.reloadAllViCol({}).then((resp) => {
        if (resp.success) {
          this.$message.success(resp.msg || "操作成功!")
        }
      }).finally(() => {
        this.operLoading = false
      })
    },
    exportDsOne(id, name) {
      this.exportLoading = true
      ds.exportOne({id: id}).then((resp) => {
        if (resp.success) {
          let blob = new Blob([resp.data], {
            type: 'text/plain'
          })
          console.log(blob)
          let fileName = name + '.tex'
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName)
          } else {
            var link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            link.click()
            //释放内存
            window.URL.revokeObjectURL(link.href)
          }
        }
      }).finally(() => {
        this.exportLoading = false
      })
    },
    importDs(param) {
      let reader = new FileReader(); //新建一个FileReader
      reader.readAsText(param.file, "UTF-8"); //读取文件
      reader.onload = (evt) => { //读取完文件之后会回来这里
        let fileString = evt.target.result; // 读取文件内容
        ds.importDs(fileString).then((resp) => {
          this.$message.success(resp.data || "操作成功!")
          this.fileList = []
          this.loadData()
        })
      }
    },
  }
}
</script>
<style lang="scss" scoped>
@import "../../../style/index.scss";

.el-dropdown-link {
  cursor: pointer;
  color: #1890ff;
  font-size: 12px;
}

.el-icon-arrow-down {
  font-size: 12px;
}

.page {
  float: right;
  margin: 20px 0px;
}

.operator-btn {
  margin: 0px 0px 20px 0px;
}
.pop-confirm-button {
  display: inline-block; margin-left: 10px;
}
</style>
