<template>
  <div class="h-100">
    <el-form :inline="true" class="orderform" size="mini">
      <el-row>
        <el-form-item label="应用名称:">
          <el-input v-model="tag" style="width: 250px" placeholder="请输入..." class="search_tag" clearable/>
        </el-form-item>
        <el-form-item label="应用状态:">
          <el-select v-model="appStatus" clearable placeholder="请选择应用状态" size="mini">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="应用类型:">
          <el-select v-model="appTypeId" clearable placeholder="请选择应用类型">
            <el-option
              v-for="item in appTypes"
              :key="item.name"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>

        <!--        <el-form-item>-->
        <!--          <el-select v-model="alarmStatus" clearable placeholder="请选择预警状态" size="mini">-->
        <!--            <el-option-->
        <!--              v-for="item in statusOptions"-->
        <!--              :key="item.value"-->
        <!--              :label="item.label"-->
        <!--              :value="item.value"/>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item>-->
        <!--          <el-date-picker-->
        <!--            v-model="expireDate"-->
        <!--            type="date"-->
        <!--            placeholder="选择到期日期"/>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="btn_search()"><i class="el-icon-search"/> 搜索</el-button>
          <el-button @click="btn_clear()"><i class="el-icon-remove-outline"/> 重置</el-button>
          <el-button type="primary" @click="addFormVisible = true"><i class="el-icon-plus"/> 创建应用</el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <el-table
      ref="multipleTable"
      :data="tableData"
      :highlight-current-row="true"
      height="calc(100% - 161px)"
      stripe
      border>
      <el-table-column
        prop="name"
        label="应用名称"/>
      <el-table-column
        prop="id"
        label="AppID"/>
      <el-table-column
        prop="apiKey"
        label="API Key"/>
      <el-table-column
        prop="secretKey"
        label="Secret Key"/>
      <el-table-column
        label="应用状态">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 1">正常</span>
          <span v-else-if="scope.row.status == 0">停用</span>
          <span v-else-if="scope.row.status == 2">应用待审核</span>
          <span v-else-if="scope.row.status == 3">审核被拒绝</span>
          <span v-else-if="scope.row.status == 99">有待审接口</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="应用启停状态">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 1">正常</span>
          <span v-else-if="scope.row.status == 0">停用</span>
        </template>
      </el-table-column> -->
      <el-table-column
        prop="appType.name"
        label="应用类型"/>
      <!--      <el-table-column-->
      <!--        prop="expireDate"-->
      <!--        label="到期日期"/>-->
      <el-table-column
        prop="createTime"
        label="创建时间"/>
      <el-table-column
        prop="description"
        label="备注"/>
      <el-table-column
        fixed="right"
        label="操作">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status != 3" type="text"><router-link :to="{path:'/devappreport/appreport',query:{appId:scope.row.id}}" tag="a"><span class="blue">报表</span></router-link></el-button>
          <el-button v-if="scope.row.status != 3" type="text"><router-link :to="{path:'/devappdetail/appdetail',query:{appId:scope.row.id}}" tag="a"><span class="blue">管理</span></router-link></el-button>
          <el-button v-if="scope.row.status == 3" type="text"><router-link :to="{path:'/devappdetail/viewdetail',query:{appId:scope.row.id}}" tag="a"><span class="blue">查看详情</span></router-link></el-button>
          <el-button type="text" @click="handleDelete(scope.row)"><span style="color: red">删除</span></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="mydiv">
      <el-pagination
        :current-page.sync="pageNo"
        :page-sizes="[10, 50, 100, 300,1000]"
        :page-size="pageSize"
        :total="totalDataNumber"
        layout="sizes,total, prev, pager, next"
        class="table-pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>

    <el-dialog :visible.sync="addFormVisible" title="新增应用">
      <el-form :model="addForm" :rules="rules" >
        <el-form-item :label-width="formLabelWidth" label="应用名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入应用名称"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="应用类型" prop="appType">
          <el-select v-model="addForm.appType" placeholder="请选择应用类型">
            <el-option
              v-for="item in appTypes"
              :key="item.name"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="接口选择" prop="apis">
          <!-- <el-transfer
            v-model="activeNames"
            :data="apiList"
            filterable/> -->
          <div style="margin-left: 20px;color: #409EFF;">已选择接口:{{ dataModel.length }}</div>
          <el-tabs tab-position="left" style="height: 300px;">
            <el-tab-pane v-for="(book,index) in apiList" :key="index" :label="book.name">
              <el-checkbox :indeterminate="!book.isAll&&dataModel.length>0" v-model="book.isAll" @change="handleCheckAllChange(book)">全选当前分类</el-checkbox>
              <el-checkbox-group v-model="dataModel">
                <el-checkbox
                  v-for="api in book.apis"
                  :key="api.value"
                  :label="api.value"
                  @change="($event)=>{
                    if(!$event){
                      book.isAll = false
                    }
                  }"
                >{{ api.label }}</el-checkbox>
              </el-checkbox-group>
            </el-tab-pane>
          </el-tabs>
          <!-- <el-collapse
            v-for="book in apiList"
            v-model="activeNames"
            :key="book.name">
            <el-collapse-item :title = "book.name" :name="book.name">
              <el-checkbox-group v-model="dataModel">
                <el-checkbox
                  v-for="api in book.apis"
                  :key="api.value"
                  :label="api.value"
                >{{ api.label }}</el-checkbox>
              </el-checkbox-group>
            </el-collapse-item>
          </el-collapse> -->

        </el-form-item>
        <!--el-form-item :label-width="formLabelWidth" label="到期日期">
          <el-date-picker
            v-model="addForm.expireDate"
            type="date"
            placeholder="选择到期日期"/>
        </el-form-item-->
        <el-form-item :label-width="formLabelWidth" label="备注">
          <el-input v-model="addForm.description" type="textarea" show-word-limit maxlength="100" placeholder="请输入备注，最长100字"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnAddCancel">取 消</el-button>
        <el-button type="primary" @click="btnAddSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="提示"
      width="30%">
      <span>确定删除选择应用? </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'
import { mapState } from 'vuex'

export default {
  name: 'Index',
  data() {
    return {
      rules: {
        name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
        appType: [{ required: true, message: '请选择应用类型', trigger: 'blur' }],
        apis: [{ required: true, message: '请选择应用所需接口', trigger: 'blur' }]
      },
      dataModel: [],
      apiList: [],
      tag: '',
      appStatus: '', // 应用状态
      alarmStatus: '', // 预警状态
      select_value: '', // 用户状态
      expireDate: '', // 到期日期
      options: [{
        value: 1,
        label: '正常'
      }, {
        value: 0,
        label: '停用'
      }, {
        value: 2,
        label: '应用待审核'
      }, {
        value: 3,
        label: '审核被拒绝'
      }
      ],
      statusOptions: [{
        value: 1,
        label: '预警应用'
      }, {
        value: 2,
        label: '异常应用'
      }],
      allData: [], // 所有前端分页数据
      tableData: [], // 表格数据 仅展示当前页的数据
      pageNo: 1, // 当前页数
      totalDataNumber: 0, // 总记录数
      pageSize: 10,
      formLabelWidth: '100px', // 弹出框form宽
      addFormVisible: false,
      editFormVisible: false,
      addForm: {
        name: '',
        appType: '',
        expireDate: '',
        description: ''
      },
      editForm: {
        id: '',
        name: '',
        appType: '',
        expireDate: '',
        description: ''
      },
      status: '',
      id: '',
      appTypes: [],
      deleteId: '',
      deleteDialogVisible: false,
      activeNames: [],
      checkAll: false,
      appTypeId: ''
    }
  },
  computed: {
    ...mapState(['user'])
  },
  created() {
    if (this.$route.query.addFormVisible === true) {
      this.addFormVisible = true
    } else {
      this.addFormVisible = false
    }
    this.searchAllAppTypes()
    this.searchAllApis()
    this.btn_search()
  },
  mounted() {
  },
  methods: {
    // 全选
    handleCheckAllChange(row) {
      const apis = row.apis
      const List = apis.map(item => item.value)
      this.dataModel = this.dataModel.filter(item => !List.includes(item))
      if (row.isAll) {
        this.dataModel.push(...List)
      } else {
        this.dataModel = this.dataModel.filter(item => !List.includes(item))
      }
    },
    handleChange(value) {
      console.log(value)
      console.log(this.dataModel)
    },
    onChangeCheck(value) {
      console.log(value)
    },
    formatStatus(ob) {
      if (ob.status === 1) {
        return '正常'
      } else if (ob.status === 0) {
        return '停用'
      } else if (ob.status === 2) {
        return '待审核'
      } else if (ob.status === 3) {
        return '拒绝'
      } else if (ob.status === 99) {
        return '有待审接口'
      }
    },
    searchAllAppTypes() {
      const vm = this
      axios.get(process.env.BASE_API + '/apptype/list', {
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.appTypes = []
        } else {
          if (parseInt(obj.total) > 0) {
            vm.appTypes = obj.data
          } else {
            vm.appTypes = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    searchAllApis() {
      const vm = this
      axios.get(process.env.BASE_API + '/apimngr/listapis', {
        params: {
          roleId: vm.user.roleId
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.apiList = []
        } else {
          if (parseInt(obj.total) > 0) {
            vm.apiList = obj.data.map(val => {
              if (val.apis) {
                val.isAll = false
                return val
              }
            }).filter(val => val !== undefined)
            vm.activeNames = obj.apiTypeNames
          } else {
            vm.apiList = []
          }
        }
      })
    },
    btn_search() {
      const vm = this
      if (this.expireDate !== '') {
        this.expireDate = moment(this.expireDate).format('YYYY-MM-DD')
      }
      axios.get(process.env.BASE_API + '/app/list', {
        params: {
          tag: this.tag,
          status: this.appStatus,
          alarmStatus: this.alarmStatus,
          expireDate: this.expireDate,
          appTypeId: this.appTypeId
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.totalDataNumber = 0
          vm.allData = []
          vm.tableData = []
        } else {
          vm.totalDataNumber = parseInt(obj.total)
          if (vm.totalDataNumber > 0) {
            vm.allData = obj.data
            vm.tableData = obj.data.slice(0, vm.pageSize)
          } else {
            vm.allData = []
            vm.tableData = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    btn_clear() {
      this.tag = ''
      this.appStatus = ''
      this.alarmStatus = ''
      this.expireDate = ''
      this.btn_search()
    },
    handleCurrentChange() {
      this.tableData = this.allData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.tableData = this.allData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    },
    btnAddCancel() {
      this.addFormVisible = false
      this.addForm.name = ''
      this.addForm.expireDate = ''
      this.addForm.description = ''
    },
    btnAddSubmit() {
      if (this.addForm.name === '' || this.addForm.name === undefined) {
        this.$message.info('请输入应用类型名称，不能为空')
        return
      }
      if (this.addForm.appType === '' || this.addForm.appType === undefined) {
        this.$message.info('请选择应用类型，不能为空')
        return
      }
      if (this.dataModel.length === 0) {
        this.$message.info('请选择应用所需接口，不能为空')
        return
      }
      var vm = this
      var params = new URLSearchParams()
      params.append('name', vm.addForm.name)
      params.append('appTypeId', vm.addForm.appType)
      params.append('apis', vm.dataModel)
      params.append('expireDate', moment(vm.addForm.expireDate).format('YYYY-MM-DD'))
      params.append('description', vm.addForm.description)
      axios.post(process.env.BASE_API + '/app/insert', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.addForm.name = ''
          vm.addForm.description = ''
          vm.addFormVisible = false
          vm.btn_search()
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    handleDelete(row) {
      this.deleteId = row.id
      this.deleteDialogVisible = true
    },
    submitDelete() {
      var vm = this
      var params = new URLSearchParams()
      params.append('id', vm.deleteId)
      axios.post(process.env.BASE_API + '/app/delete', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.deleteDialogVisible = false
          vm.btn_search()
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    handleReport() {
    }
  }
}
</script>

<style scoped>
  .orderform {
    padding-top: 20px;
    padding-left: 10px;
    padding-right: 10px;
  }

  .mydiv {
    display: flex;
    padding: 10px;
    background: #ffffff;
  }
</style>
