<template>
  <div class="app-container">
    <!--标题-->
    <super-title>
      数据库表
      <span slot="append" class="fr">
        <el-upload
          class="upload-demo fl"
          action=""
          :http-request="uploadFile"
          multiple
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList"
        >
          <div class="btn">
            <el-button size="mini" type="primary">导入Excel</el-button>
          </div>
        </el-upload>
          <div class="fl">
            <el-button size="mini" type="primary" @click="exportExcel">导出Excel</el-button>
            <el-button icon="el-icon-plus" type="primary" plain size="mini" @click="addBtn">新增</el-button>
            <el-button icon="el-icon-edit" type="primary" plain size="mini" @click="alterBtn">修改</el-button>
            <el-button icon="el-icon-edit" type="primary" plain size="mini" @click="delBtn">删除</el-button>
          </div>
      </span>
    </super-title>

   <super-table :table="table" :tableface="mainTableFace" :config="tableconfig" @getSelect="getSelect" @controlFun="controlFun"></super-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery['Page.Index']"
      :limit.sync="listQuery['Page.Size']"
      @pagination="getList"
    />

    <el-dialog
      :title="outerTitle"
      :visible.sync="outerVisible"
      width="1163px"
    >
      <div v-if="switchShow === 0">
        <form-com :formface="mainFormFace" :form="mainfrom"></form-com>
      </div>
      <div v-if="switchShow === 1">
        <form-com :formface="TFormFace" :form="Tfrom"></form-com>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button type="danger" @click="outerVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { createDb } from '../components/utils/CommonRequest'

const $metiiAPI = createDb();


import superTitle from '../components/components-items/super-title.vue';
import superTable from '../components/components-items/super-table.vue';
import formCom from '../components/components-items/form-com.vue';
import pagination from '../components/components-items/pagination.vue';

import pageMintenancePrototype from '../components/js/page-maintenance-prototype'

export default {
  name:"mitee-prototype",
  data() {
    return {
      switchSubmit: '',  // 外弹窗的切换提交
      switchSubmitInner: '',  // 内弹窗的切换提交
      switchDialogCon: '',
      switchShow: '',  // 切换展示
      footbtns: '', // 控制弹窗内按钮（接单/拒接/关闭交易）
      // 通过id获取订单form对象,后端生成
      selectTab: [], // 选中的table行
      fieldface: [],
      fieldform: {}, // 内部弹窗对象
      total: 0,
      formface: [],
      fieldconfig:{
        labelWidth: '150px',
        labelPosition: 'right'
      },
      fieldId: '',
      cid: '',
      field: [],
      listLoading: true, // 控制列表加载动画化
      listQuery: { // 查询条件
        searchTxt: "",
        pageIndex: 0,
        pageSize: 10,
        sidx: ""  // 排序字段
      },
      outerTitle: '弹窗标题', // 控制弹窗
      innerTitle: '内弹窗标题', // 内弹窗标题
      downloadLoading: false, // 控制下拉加载状态
      outerVisible: false, // 控制外弹窗,
      innerVisible: false, // 控制内弹窗
      href: '',
      table:[],  // 主列表数据
      mainTableFace:[],  // 主列表显示控制
      TFormFace:[], // table上弹窗
      Tfrom:{},
      mainFormFace:[],  //主列表form控制
      tableconfig:{
        height: 'calc(100vh - 190px)'
      },
      mainfrom: {}, // 主列表from
      hea: window.location.href,
      url:'',
      fileList: []
    }
  },
  computed: {
    pages() {
      const pages = []
      this.productArr.forEach((item, index) => {
        const page = Math.floor(index / 4)
        if (!pages[page]) {
          pages[page] = []
        }
        pages[page].push(item)
      })
      return pages
    },
    selectMap(){
      const arr = []
      if(this.table.length>0){
        this.table.map(s =>
          {
            arr.push({'name':s.name,'id':s.id})
          }
        )
        return arr
      }
    }
  },
  watch:{
    $route(to,from){
      this.getPageConfig()
      this.getList()
    }
  },
  created() {
    this.getPageConfig()
    this.getList()
  },
  methods: {
    // 给from下拉绑定数据
    addSelectArr(face,arr){
      face.find(s =>
        {
          if(s.english === 'parentid'){
            s.controltype = 'select'
            s.sourcedata = []
            arr.map(w=>
              s.sourcedata.push({label:w.name,value:w.id})
            )
          }
        }
      )
      // console.log('face',face)
    },
    // 内弹窗的删除
    fielddelBtn(){
      const arr = []
      this.selectTab.forEach(s => arr.push(s.id))
      this.$confirm('删除该内容, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        pageMintenancePrototype.delFileds(arr).then(response => {
          let { code, msg, result } = response
          if(Object.is(code,1)){
            this.outerVisible = false
            this.$message.success('修改成功')
            this.getList()
          }else{
            this.$message.error(msg)
          }
          // console.log('response.result', response.result)
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 内弹窗的确定
    submitInner(){
      // console.log('this.switchSubmitInner',this.switchSubmitInner)
      // 0 是添加 1是修改
      if(this.switchSubmitInner === 0){
          pageMintenancePrototype.addFiled(this.fieldform).then(response => {
          console.log('response.result', response)
          let { code, msg, result } = response
          if(Object.is(code,1)){
            this.innerVisible = false
            this.$message.success('添加成功')
            this.getfiledList(this.fieldId)
          }else{
            this.$message.error(msg)
          }
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      }else if(this.switchSubmitInner === 1){
        let data = JSON.stringify(this.fieldform)
        // console.log(data)
        pageMintenancePrototype.updateFiled(this.fieldform).then(response => {
          let { code, msg, result } = response
          if(Object.is(code,1)){
            this.outerVisible = false
            this.$message.success('修改成功')
            this.getfiledList(this.fieldId)
          }else{
            this.$message.error(msg)
          }
          // console.log('response.result', response.result)
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      }
    },
    // 新增字段
    fieldAddBtn(){
      this.innerVisible = true
      this.innerTitle = '添加字段'
      this.switchSubmitInner = 0
      this.fieldform = {}
      this.fieldform.t_system_setid = this.fieldId
    },
    // 获取弹窗配置信息
    getPopPageConfig(){
      pageMintenancePrototype.getPopPageConfig({}).then(response => {
        // console.log('response',response)
        let { code, msg, result } = response
        if(Object.is(code,1)){
          this.fieldface = result
          this.fieldface.map(s => s.enabled = true)
        }else{
          this.$message.error(msg)
        }
        // console.log('this.fieldface', this.fieldface)
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // 获取字段列表数据
    getfiledList(id){
      pageMintenancePrototype.getById({}, this.href, id).then(response => {
        let { code, msg, result } = response
        if(Object.is(code,1)){
          this.outerTitle = '字段详情'
          this.outerVisible = true
          // console.log('result',result)
          this.field = result.details
          // console.log('this.fieldform.t_system_setid',this.fieldform.t_system_setid)
          this.fieldface.map(s => s.enabled = false)
        }else{
          this.$message.error(msg)
        }
        // console.log('response.result', response.result)
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // 获取选中
    getSelect(e){
      // console.log('e',e)
      this.selectTab = e
    },
    // 导入excel
    leadBtn(){

    },
    // 新增
    addBtn(){
      this.outerTitle = '新增'
      this.outerVisible = true
      this.switchShow = 0
      this.switchSubmit = 0
      this.mainfrom = {}
      this.mainFormFace.map(s => s.enabled = true)
      // console.log('this.mainFormFace', this.mainFormFace)
      if(this.href === 'Menu'){
        this.addSelectArr(this.mainFormFace,this.selectMap)
      }
    },
    // 内弹窗修改
    fieldAlterBtn(){
      var that = this
      if(Object.is(this.selectTab.length,1)){
        this.innerTitle = '修改字段详情'
        this.innerVisible = true
        this.switchSubmitInner = 1
        // console.log('this.selectTab[0]',this.selectTab[0])
        this.fieldform = this.selectTab[0]
      }else{
        that.$message.error('请选择一条来修改')
      }
    },
    // 修改
    alterBtn(){
      var that = this
      if(Object.is(this.selectTab.length,1)){
        this.outerTitle = '修改'
        this.outerVisible = true
        this.switchSubmit = 1
        this.switchShow = 0
        this.mainfrom = this.selectTab[0]
        this.mainFormFace.map(s => s.enabled = true)
        if(this.href === 'Menu'){
          this.addSelectArr(this.mainFormFace,this.selectMap)
        }
      }else{
        that.$message.error('请选择一条来修改')
      }
    },
    // 删除
    delBtn(){
      if(this.selectTab.length === 1){
        this.$confirm('删除该内容, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delById(this.selectTab[0].id)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }else{
        this.$message.error('只能选择一个来删除')
      }
    },
    // 确定
    async submit() {
       // 0 是添加 1是修改
      if(this.switchSubmit === 0){
        // console.log('add',this.mainfrom)
        pageMintenancePrototype.add(this.mainfrom, this.href).then(response => {
          // console.log('response.result', response.result)
          let { code, msg, result } = response
          if(Object.is(code,1)){
            this.outerVisible = false
            this.$message.success('添加成功')
            this.getList()
          }else{
            this.$message.error(msg)
          }
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      }else if(this.switchSubmit === 1){
        pageMintenancePrototype.update(this.mainfrom, this.href).then(response => {
          let { code, msg, result } = response
            if(Object.is(code,1)){
              this.outerVisible = false
              this.$message.success('修改成功')
              this.getList()
            }else{
              this.$message.error(msg)
            }
          // console.log('response.result', response.result)
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      }else if(this.switchSubmit === 3){
        await $metiiAPI.getdatabyurl(this.url+'save', this.mainfrom)
        this.$message.success('保存成功')
      }
    },
    // 获取路径的变量
    getField() {
      var that = this
      that.href = []
      var h = window.location.href
      var st = 'pname='
      var st2 = 'tablename='
      var i = h.indexOf(st)
      var j = h.indexOf(st2)
      var L, s
      if (i !== -1) {
        L = st.length
        s = h.substr(i + L, j - L - i - 1)
        // console.log('s1', s)
        that.href.push(s)
      }
      if (j !== -1) {
        L = st2.length
        s = h.substr(j + L)
        // console.log('s2', s)
        that.href.push(s)
      }

      // console.log('that.href', that.href)
    },
    //  获取页面配置
    getPageConfig() {
      this.getField()
      // console.log('this.href', this.href)
      this.switchSubmit = 0 // 0 是保存 1是修改
      pageMintenancePrototype.getPageConfig({}, this.href).then(response => {
        // console.log('response', response)
        let { code, msg, result } = response
        if(Object.is(code,1)){
          this.mainTableFace = result
          this.mainTableFace.map(s => s.enabled = false)
          this.mainFormFace = JSON.parse(JSON.stringify(this.mainTableFace))
        }else{
          this.$message.error(msg)
        }
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    //  通过id数组删除值
    delById(id){
      var that = this
      pageMintenancePrototype.delById({id:id}, that.href).then(response => {
        let { code, msg, result } = response
        if(Object.is(code,1)){
          this.$message.success('删除成功')
          this.getList()
        }else{
          this.$message.error(msg)
        }
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    //  通过id获取值
    getById() {
      var that = this
      const pid = '815b0c9e-ce94-4c74-bd52-2a9a79d9d7ea'
      pageMintenancePrototype.getById({}, that.href, pid).then(response => {
        let { code, msg, result } = response
        if(Object.is(code,1)){
          that.form = result
        }else{
          this.$message.error(msg)
        }
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // 获取所有数据
    getList(){
      this.getField()
      pageMintenancePrototype.getList({}, this.href).then(response => {
        // console.log('responselist',response)
        let { code, msg, result, count } = response
        if(Object.is(code,1)){
          // console.log('result',result)
          this.table = result
          this.total = count
        }else{
          this.$message.error(msg)
        }
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // 遍历赋值
    valuation(form,myJson){
      var that = this
      var arr = []
      for(var p in myJson){//遍历json对象的每个key/value对,p为key
        // console.log('p',myJson[p])
        arr.push(myJson[p])
      }
      if(arr.length>0){
        for(var i=0; i<form.length;i++ ){
          // form[i].value = arr[i]
          that.$set(form[i],'value', arr[i])
        }
      }
      return form
    },
    // 列表操作方法
    async controlFun(e, r) {
      this.switchShow = 1
      this.outerVisible = true
      this.outerTitle = '信息维护-'+ this.tableconfig.tableBtns[e].name
      this.switchSubmit = 3
      this.url = this.tableconfig.tableBtns[e].apiurl
      if(this.tableconfig.tableBtns[e].type === 'link'){
        let href = this.tableconfig.tableBtns[e].apiurl
        href = href.substr(0,href.indexOf('?'))
        const arr = this.$tool.getUrlparams(this.tableconfig.tableBtns[e].apiurl)
        this.$router.push({name: href ,query:{ pname:arr[0],tname:arr[1]}})
        this.outerVisible = false
      }else{
        this.TFormFace = await $metiiAPI.getdatabyurl(this.url, r)
        const arr = await $metiiAPI.getdatabyurl(this.url+'get', r)
        if(typeof arr === "object"){
          this.Tfrom = arr
        }else{
          this.Tfrom = {}
        }
        this.TFormFace.map(s=>s.enabled=true)
      }
    },
    // 改变页数时
    handleCurrentChange(val) {
      // this.params.pageNum = val
      this.listQuery['Page.Index'] = val
      this.getList()
    },
    // 条件查询
    handleFilter() {
      this.listQuery['Page.Index'] = 1
      // console.log('this.listQuery', this.listQuery)
      this.getList()
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    async uploadFile(file) {
      this.fileTemp = file.file
      // console.log('this.fileTemp', this.fileTemp)
      if (this.fileTemp) {
        if ((this.fileTemp.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (this.fileTemp.type === 'application/vnd.ms-excel')) {
          var formData = new FormData()
          // 向 formData 对象中添加文件
          formData.append('file', this.fileTemp)
          // console.log('this.href', this.href)
          const { result } = await $metiiAPI.upFile( this.href[0]+ 'app/'+ this.href[1]+ 'import', formData)
          this.moduleTable = result
        } else {
          this.$message({
            type: 'warning',
            message: '附件格式错误，请删除后重新上传！'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请上传附件！'
        })
      }
    },
    exportExcel(){
      $metiiAPI.post( this.href[0]+ 'app/'+ this.href[1]+ 'export',{})
    }
  },
  components:{
    superTitle,
    superTable,
    formCom,
    pagination
  }
}


</script>


<style lang="scss" scoped>
  // @import url("./style/index.scss");
  .fr {
    float: right;
  }

  .fl {
    float: left;
  }
  .title {
    height: 60px;
    line-height: 60px;
    background-color: #ffffff;
    padding: 0px 16px;
    margin-bottom: 10px;
  }
  .sub{
    font-size: 12px;
    margin-left: 10px;
  } 


  /*产品列表*/
  .proList{
    .el-row{
      margin-bottom: 20px;
      &:last-child {
        margin-bottom: 0;
      }
    }
    .img-con{
      width: 100%;
      height: 132px;
      img{
        width: 100%;
        height: 100%;
        display: block;
      }
    }
    .proInfo{
      background-color: #ffffff;
      padding: 10px 8px;
      .infoOne{
        overflow: hidden;
      }
    }
  }
  .upload-demo >>> .el-upload-list{
    width: 370px;
    position: absolute;
    top: 0px;
  }
  .upload-demo{
    width: 500px;
    height: 60px;
    position: relative;
    .btn{
      width: 100px;
      text-align: right;
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }
</style>

