<template>

  <el-row :gutter="5" style="margin-top:5px;margin-left:5px;">
    <el-col :span="5">
      <el-card class="box-card">
        <div slot="header" class="clearfix" style="text-align: right; ">
          <el-row :gutter="2" style="margin-top:5px; margin-left:5px;">
            <el-col :span="12" style="text-align: left; vertical-align:middle; font-size: 20px">  <span>菜单 </span></el-col>
            <el-col :span="6"> <el-col :span="6">  <el-button type="warning" icon="el-icon-edit-outline" size="mini" @click="jump" /></el-col>
            </el-col>
            <el-col :span="6">  <el-button type="primary" icon="el-icon-refresh" size="mini" @click="getList()" /></el-col>
          </el-row>
        </div>
        <div class="component-item">
          <el-tree
            ref="tree"
            class="filter-tree"
            :data="parent"
            :props="defaultProps"
            @node-click="handleNodeClick"
          />
        </div>
      </el-card>
    </el-col>
    <el-col :span="19">
      <div class="app-container">
        <div class="filter-container">
          <el-button class="success" style="margin-left: 10px;" icon="el-icon-plus" @click="handleCreate"> 新增 </el-button>
          <el-input
            v-model="interfaceName"
            placeholder="接口名称"
            style="width: 250px;"
            class="filter-item"
            clearable
          />
          <el-button class="successBorder" style="margin-left: 10px;" @click="handleFind()"> 查找 </el-button>
        </div>

        <el-table
          v-loading="listLoading"
          element-loading-text="给我一点时间"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable"
          row-key="id"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column label="菜单名称" min-width="100px" header-align="center" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.menuname }}</span>
            </template>
          </el-table-column>
          <el-table-column label="名称" min-width="100px" header-align="center" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="调用方法" header-align="center" width="100px">
            <template slot-scope="scope">
              <span>{{ scope.row.method }}</span>
            </template>
          </el-table-column>
          <el-table-column label="接口名称" header-align="center" width="100px">
            <template slot-scope="scope">
              <span>{{ scope.row.sqlname }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="150px" header-align="center" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.remark }}</span>
            </template>
          </el-table-column>
          <el-table-column label="顺序" min-width="80px" header-align="center" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.sort }}</span>
            </template>
          </el-table-column>
          <el-table-column label="启用" min-width="80px" header-align="center" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enable"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="handleEnableChange(scope.$index, scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" header-align="center" align="center" width="150" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{row}">
              <el-button class="miniSuccess" icon="el-icon-edit-outline" @click="handleUpdate(row)" />
              <span class="centerSpan">|</span>
              <el-button v-if="row.status!='已删'" class="miniDanger" icon="el-icon-delete" @click="handleDelete(row)" />
              <span class="centerSpan">|</span>
              <el-button icon="el-icon-copy-document" class="miniSuccess" @click="handleCopy(row)" />
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>=0" :total="total" :page.sync="getdataListParm.offset" :limit.sync="getdataListParm.pagecount" @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
          <el-form ref="dataForm" :rules="rules" :model="deptform" label-position="left" label-width="100px" style="width: 90%; margin-left:50px;">
            <el-form-item label="菜单名称22" prop="selectmenutree">
              <tree-select
                :disabled="disabled"
                :height="280"
                :width="400"
                size="small"
                :data="parent"
                expand-all
                :default-props="defaultProps"
                collapse-tags
                onlyleaf
                node-key="id"
                :checked-keys="defaultMenuCheckedKeys"
                @popoverHide="menu_popoverHide"
              />
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input
                ref="name"
                v-model="deptform.name"
              />
            </el-form-item>
            <el-form-item label="接口名称" prop="sqlname">
              <el-input
                ref="sqlname"
                v-model="deptform.sqlname"
              />
            </el-form-item>
            <el-form-item label="调用方法" prop="method">
              <el-input
                ref="method"
                v-model="deptform.method"
              />
            </el-form-item>
            <el-form-item label="SQL" prop="sqlstr">
              <el-input
                ref="sqlstr"
                v-model="deptform.sqlstr"
                :autosize="{ minRows: 2, maxRows: 100}"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="参数" prop="params">
              <el-input
                ref="params"
                v-model="deptform.params"
              />
            </el-form-item>

            <el-form-item label="调用示例" prop="request_body">
              <el-input
                ref="request_body"
                v-model="deptform.request_body"
                :autosize="{ minRows: 2, maxRows: 100}"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                ref="remark"
                v-model="deptform.remark"
              />
            </el-form-item>
            <el-form-item label="顺序" prop="sort">
              <el-input
                ref="sort"
                v-model="deptform.sort"
              />
            </el-form-item>
            <el-form-item label="启用" prop="enable">
              <el-switch
                ref="enable"
                v-model="deptform.enable"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item></el-form>
          <div slot="footer" class="dialog-footer">
            <el-button
              v-if="dialogStatus==='create'"
              ref="createb"
              type="success"
              @click="createData_again()"
            >
              确认新增
            </el-button>
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
              确认
            </el-button>
            <el-button @click="dialogFormVisible = false">
              关闭
            </el-button>
            <el-button type="primary" @click="requesttest()">
              调用测试
            </el-button>
          </div>
        </el-dialog>
      </div>
    </el-col>
  </el-row>

</template>

<script>
import TreeSelect from '@/components/TreeSelect'
import waves from '@/directive/waves' // waves directive
import { PostDataByName, GetDataByName, transData, requestbyname } from '@/api/common'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { MessageBox } from 'element-ui'
export default {
  name: 'Apisql',
  components: { Pagination, TreeSelect },
  directives: { waves },
  data() {
    return {
      disabled: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      menuid: 0,
      interfaceName: '',
      list: [{ 'sqlname': '', 'id': 0, 'sqlstr': '' }],
      total: 0,
      listLoading: true,
      requestParam: {
        name: 'createapisql',
        params: []
      },
      deptform: {
        menuid: '',
        apisqlid: '',
        method: '',
        sqlname: '',
        sqlstr: '',
        request_body: '',
        remark: '',
        params: '',
        sort: '',
        enable: '',
        return_body: '',
        name: ''
      },
      getdataListParm: { name: 'getapisqlall',
        offset: 1,
        pagecount: 10,
        params: ['', '', '', ''] },
      getRecuListParm: { name: 'getMenuRecu' },
      rules: {
        sqlname: [{ type: 'string', required: true, message: 'sql名称必填', trigger: 'change' }],
        sqlstr: [{ type: 'string', required: true, message: 'sql内容必填', trigger: 'change' }],
        name: [{ type: 'string', required: true, message: '名称必填', trigger: 'change' }]
      },
      dialogFormVisible: false,
      parentDeptVisible: true,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      parent: [],

      defaultMenuCheckedKeys: [],
      selectedMenu: [],
      rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
      cellStyle: { padding: 0 + 'px' }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    menu_popoverHide(checkedIds, checkedData) {
      console.log(checkedIds)
      this.deptform.menuid = checkedIds
    },
    jump() {
      this.$router.push('/console/menu')
    // 传递的参数用{{ $route.query.goodsId }}获取
    //  this.$router.push({ path: '/cart?goodsId=12' })
    // this.$router.go(-2)
    // 后退两步
    },
    // check-change
    // 节点选中状态发生变化时的回调
    // 共三个参数,依次为:传递给 data 属性的数组中该节点所对应的对象、节点本身是否被选中、节点的子树中是否有被选中的节点
    menuCheckChange(data, checked, indeterminate) {
      console.log(data, '数据')
      console.log(checked, '选中状态')
      console.log(indeterminate, '子树中选中状态')
      // 获取当前选择的id在数组中的索引
      const indexs = this.selectMenu.menuid.indexOf(data.id)
      // 如果不存在数组中,并且数组中已经有一个id并且checked为true的时候,代表不能再次选择。
      if (indexs < 0 && this.selectMenu.menuid.length === 1 && checked) {
        console.log('only one')
        this.$message({
          message: '只能选择一个菜单!',
          type: 'error',
          showClose: true
        })
        // 设置已选择的节点为false 很重要
        this.$refs.selectmenutree.setChecked(data, false)
      } else if (this.selectMenu.menuid.length === 0 && checked) {
        // 发现数组为空 并且是已选择
        // 防止数组有值,首先清空,再push
        this.selectMenu.menuid = []
        this.deptform.menuid = data.id
        this.selectMenu.menuid.push(data.id)
      } else if (
        indexs >= 0 &&
       this.selectMenu.menuid.length === 1 &&
       !checked
      ) {
        // 再次直接进行赋值为空操作
        this.selectMenu.menuid = []
      }
    },
    handleFind() {
      this.listLoading = true
      this.getdataListParm.params = [this.menuid, this.menuid, this.interfaceName, this.interfaceName]
      GetDataByName(this.getdataListParm).then(response => {
        console.log(response)
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    handleNodeClick(data) {
      console.log(data)
      if (data.children === undefined || (data.children !== undefined && data.children.length === 0)) {
        this.listLoading = true
        this.menuid = data.id
        this.getdataListParm.params = [data.id, data.id, '', '']
        GetDataByName(this.getdataListParm).then(response => {
          if (response.data.total > 0) {
            this.list = response.data.list
            this.total = response.data.total
          } else {
            this.list = []
            this.total = 0
          }
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 100)
        })
      }
    },
    getDownList() {
      GetDataByName(this.getRecuListParm).then(response => {
        console.log(response)
        this.parent = response.data
        if (response.data.list !== null) {
          this.parent = transData(response.data.list, 'id', 'parentid', 'children')
        }
      })
    },
    deptenter() {
      this.$nextTick(() => {
        this.$refs['remark'].focus()
      })
    },
    getList() {
      this.menuid = 0
      this.listLoading = true
      this.getDownList()
      GetDataByName(this.getdataListParm).then(response => {
        console.log(response)
        this.list = response.data.list
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    requesttest() {
      this.listLoading = true
      console.log(JSON.parse(this.deptform.request_body))
      requestbyname(JSON.parse(this.deptform.request_body), this.deptform.method).then(response => {
        console.log(response.data)
        this.deptform.return_body = JSON.stringify(response.data)
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    resetRequestParam() {
      this.deptform.sqlid = ''
      this.deptform.menuid = ''
      this.deptform.method = ''
      this.deptform.sqlname = ''
      this.deptform.sqlstr = ''
      this.deptform.params = ''
      this.deptform.remark = ''
      this.deptform.request_body = ''
      this.deptform.sort = '0'
      this.deptform.enable = '1'
      this.deptform.return_body = ''
      this.deptform.name = ''
    },
    handleCreate() {
      this.resetRequestParam()
      this.deptform.menuid = this.menuid
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs.sqlname.focus()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'createapisql'
          // this.requestParam.parammaps = {}
          // this.requestParam.parammaps = this.deptform
          this.requestParam.params = []
          this.requestParam.params[0] = this.deptform.sqlstr
          this.requestParam.params[1] = this.deptform.sqlname
          this.requestParam.params[2] = this.deptform.params
          this.requestParam.params[3] = this.deptform.menuid
          this.requestParam.params[4] = 'tmrgo' // remark
          this.requestParam.params[5] = this.deptform.sort
          this.requestParam.params[6] = this.deptform.enable
          this.requestParam.params[7] = this.deptform.method
          this.requestParam.params[8] = this.deptform.name
          this.requestParam.params[9] = this.deptform.request_body
          this.requestParam.params[10] = this.deptform.return_body
          PostDataByName(this.requestParam).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    createData_again() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'createapisql'
          // this.requestParam.parammaps = {}
          // this.requestParam.parammaps = this.deptform
          this.requestParam.params = []
          this.requestParam.params[0] = this.deptform.sqlstr
          this.requestParam.params[1] = this.deptform.sqlname
          this.requestParam.params[2] = this.deptform.params
          this.requestParam.params[3] = this.menuid
          this.requestParam.params[4] = 'tmrgo'// remark
          this.requestParam.params[5] = this.deptform.sort
          this.requestParam.params[6] = this.deptform.enable
          this.requestParam.params[7] = this.deptform.method
          this.requestParam.params[8] = this.deptform.name
          this.requestParam.params[9] = this.deptform.request_body
          this.requestParam.params[10] = this.deptform.return_body
          PostDataByName(this.requestParam).then(() => {
            this.$nextTick(() => {
              this.$refs['sqlname'].focus()
            })
            this.getList()
            this.resetRequestParam()
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.deptform.sqlid = row.id
      if (row.menuid === null) { this.deptform.menuid = 0 } else { this.deptform.menuid = row.menuid }
      this.deptform.method = row.method
      this.deptform.sqlname = row.sqlname
      this.deptform.sqlstr = row.sqlstr
      this.deptform.params = row.params
      this.deptform.request_body = row.request_body
      this.deptform.return_body = row.return_body
      this.deptform.name = row.name
      this.deptform.remark = row.remark
      this.deptform.sort = row.sort
      this.deptform.enable = row.enable
      if (this.deptform.menuid !== 0) { this.defaultMenuCheckedKeys = [this.deptform.menuid] } else { this.defaultMenuCheckedKeys = [] }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs['sqlname'].focus()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.requestParam.name = 'updateapisql'
          // this.requestParam.parammaps = {}
          // this.requestParam.parammaps = this.deptform
          this.requestParam.params = []
          this.requestParam.params[0] = this.deptform.sqlstr
          this.requestParam.params[1] = this.deptform.sqlname
          this.requestParam.params[2] = this.deptform.params
          this.requestParam.params[3] = this.deptform.menuid
          this.requestParam.params[4] = 'tmrgo'// remark
          this.requestParam.params[5] = this.deptform.sort
          this.requestParam.params[6] = this.deptform.enable
          this.requestParam.params[7] = this.deptform.method
          this.requestParam.params[8] = this.deptform.name
          this.requestParam.params[9] = this.deptform.request_body
          this.requestParam.params[10] = this.deptform.return_body
          this.requestParam.params[11] = this.deptform.sqlid
          PostDataByName(this.requestParam).then(() => {
            this.getList()
            this.resetRequestParam()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleEnableChange(index, row) {
      this.requestParam.name = 'updateapisql'
      this.requestParam.params = []
      this.requestParam.params[0] = row.sqlstr
      this.requestParam.params[1] = row.sqlname
      this.requestParam.params[2] = row.params
      this.requestParam.params[3] = row.menuid
      this.requestParam.params[4] = row.remark
      this.requestParam.params[5] = row.sort
      this.requestParam.params[6] = row.enable
      this.requestParam.params[7] = row.method
      this.requestParam.params[8] = row.name
      this.requestParam.params[9] = row.request_body
      this.requestParam.params[10] = row.return_body
      this.requestParam.params[11] = row.id
      PostDataByName(this.requestParam).then(() => {
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleCopy(row) {
      this.requestParam = {}
      this.requestParam.name = 'copySQL'
      this.requestParam.params = []
      this.requestParam.params[0] = row.id
      PostDataByName(this.requestParam).then(() => {
        this.getList()
        this.resetRequestParam()
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '复制成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleDelete(row) {
      MessageBox.confirm('sql名称:' + row.sqlname, '确认删除?', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.name = 'deleteapisql'
        this.requestParam.params = []
        this.requestParam.params[0] = row.id
        PostDataByName(this.requestParam).then(() => {
          this.getList()
          this.resetRequestParam()
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    }
  }
}
</script>