<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <dmSystemTemp :params.sync="params" @on-change="dmSystemCallbackFunc" />
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="接口名称">
            <el-input v-model="form.apiName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="所属系统" prop="usersList">
            <el-input v-model="systemIds" style="display: none;" />
            <el-input v-model="systemNames" :rows="3" type="textarea" style="width: 370px;" />
            <el-button type="primary" @click="openDmSystem(form)">选择子系统</el-button>
          </el-form-item>
          <el-form-item label="接口地址">
            <el-input v-model="form.apiUrl" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="文件名称">
            <el-input v-model="form.localStorage.name" style="width: 370px;" />
          </el-form-item>
          <!--   上传文件   -->
          <el-form-item v-if="crud.status.add" label="上传接口配置文件">
            <el-upload
              ref="upload"
              :limit="1"
              :before-upload="beforeUpload"
              :auto-upload="true"
              :headers="headers"
              :on-success="handleSuccess"
              :on-error="handleError"
              :action="fileUploadApi + '?name=' + form.localStorage.name"
            >
              <div class="eladmin-upload"><i class="el-icon-upload" /> 添加文件</div>
              <div slot="tip" class="el-upload__tip">可上传任意格式文件，且不超过100M</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="apiName" label="接口名称" />
        <el-table-column prop="dmSystems" label="子系统名称">
          <template slot-scope="{row, column}">
            {{ row[column.property] && row[column.property].map(item => item.systemName).join(',') }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column v-if="checkPer(['admin','dmApi:edit','dmApi:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDmApi from '@/api/dm/api/dmApi'
import { getToken } from '@/utils/auth'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import dmSystemTemp from '@/components/DmSystem/index'

const defaultForm = { id: null, apiName: null, apiUrl: null, dmSystems: [], localStorage: {}, createBy: null, updateBy: null, createTime: null, updateTime: null }
export default {
  name: 'DmApi',
  components: { pagination, crudOperation, rrOperation, udOperation, dmSystemTemp },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '接口管理', url: 'api/dmApi', idField: 'id', sort: 'id,desc', crudMethod: { ...crudDmApi }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'dmApi:add'],
        edit: ['admin', 'dmApi:edit'],
        del: ['admin', 'dmApi:del']
      },
      rules: {
      },
      headers: { 'Authorization': getToken() },
      systemIds: '',
      systemNames: '',
      params: {
        max: 100000, // 可以选择用户个数最大限制
        dmUserIsApprove: null// 是否要查有审批权限的用户
      }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    dmSystemCallbackFunc(dmSystemList, rowId) {
      this.form.dmSystems = dmSystemList
      console.log('dmSystemList:', this.form.dmSystems)
      var systemIds = ''
      var systemNames = ''
      dmSystemList.forEach((item, i) => {
        systemIds += dmSystemList[i]['id'] + ','
        systemNames += dmSystemList[i]['systemName'] + ','
      })
      this.systemIds = systemIds.substring(0, systemIds.length - 1)
      this.systemNames = systemNames.substring(0, systemNames.length - 1)
      console.log('systemIds:', this.systemIds)
      console.log('systemNames:', this.systemNames)
    },
    // 上传文件
    upload() {
      this.$refs.upload.submit()
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.form.name = file.name
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      this.form.localStorage = response
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    openDmSystem(form) {
      this.crud.doOpenDmSystem(form)
    }
  }
}
</script>

<style scoped>

</style>
