<template>
  <div>
    <div>
      <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 filterable placeholder="请选择应用类型">
              <el-option
                v-for="item in appTypes"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="开发者：">
            <el-select v-model="userId" clearable filterable placeholder="请选择开发者">
              <el-option
                v-for="item in userList"
                :key="item.id"
                :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"
        :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
        border>
        <el-table-column
          prop="id"
          label="AppId"/>
        <el-table-column
          prop="name"
          label="应用名称"/>
        <el-table-column
          prop="appType.name"
          label="应用类型"/>
        <el-table-column
          prop="user.name"
          label="开发者"/>
        <el-table-column
          prop="apiKey"
          label="API Key"/>
        <el-table-column
          prop="secretKey"
          label="Secret Key"/>
        <el-table-column
          :formatter="formatStatus"
          prop="status"
          label="应用状态"/>
        <!-- <el-table-column
          label="剩余次数">
          <template slot-scope="scope">
            <el-button type="text" @click="handleCheck(scope.row)">查看明细</el-button>
          </template>
        </el-table-column> -->
        <!--        <el-table-column-->
        <!--          prop="expireDate"-->
        <!--          label="到期日期"/>-->
        <el-table-column
          prop="createTime"
          label="创建时间"/>
        <el-table-column
          width="200px"
          fixed="right"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleDisable(scope.row)">
              <span v-if="scope.row.status !== 1 && scope.row.status !==99">启用</span>
              <span v-if="scope.row.status === 1 || scope.row.status ==99">停用</span>
            </el-button>
            <el-button type="text" ><router-link :to="{path:'/appmngr/detail',query:{appId:scope.row.id}}" tag="a"><span class="blue">查看</span></router-link></el-button>
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="text"><router-link :to="{path:'/devappreport/appreport',query:{appId:scope.row.id,userId: scope.row.user.id}}" tag="a"><span class="blue">统计</span></router-link></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>

    </div>
    <el-dialog :visible.sync="addFormVisible" title="新增应用">
      <el-form :model="addForm" :rules="rules">
        <el-form-item :label-width="formLabelWidth" label="选择开发者" prop="userName">
          <el-select v-model="addForm.userId" placeholder="请选择开发者">
            <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <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.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="接口选择">
          <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-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="editFormVisible" title="编辑应用" @close="btnUpdateCancel">
      <el-form :model="editForm">
        <el-form-item :label-width="formLabelWidth" label="应用名称">
          <el-input v-model="editForm.name" placeholder="请输入应用名称"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="应用类型">
          <el-select v-model="editForm.appType" placeholder="请选择应用类型">
            <el-option
              v-for="item in appTypes"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="接口选择">
          <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-form-item>
        <!--        <el-form-item :label-width="formLabelWidth" label="到期日期">-->
        <!--          <el-date-picker-->
        <!--            v-model="editForm.expireDate"-->
        <!--            type="date"-->
        <!--            placeholder="选择到期日期"/>-->
        <!--        </el-form-item>-->
        <el-form-item :label-width="formLabelWidth" label="备注">
          <el-input v-model="editForm.description" type="textarea" show-word-limit maxlength="100" placeholder="请输入备注，最长100字"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnUpdateCancel">取 消</el-button>
        <el-button type="primary" @click="btnUpdateSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="showTimesFormVisible"
      title="应用接口剩余次数"
      width="50%">
      <el-table
        :row-style="tableRowStyle"
        :data="selectTimes"
        :highlight-current-row="true"
        border>
        <el-table-column
          prop="apiId"
          label="ApiId"/>
        <el-table-column
          prop="apiName"
          label="接口名称"/>
        <el-table-column
          prop="total"
          label="总计次数"/>
        <el-table-column
          prop="used"
          label="已使用数"/>
        <el-table-column
          :formatter="calculateRemainTimes"
          prop="remain"
          label="剩余次数"/>
        <el-table-column
          :formatter="calculateRemainRate"
          prop="remainRate"
          label="剩余比例"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showTimesFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="showTimesFormVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="disableFormVisible"
      title="提示"
      width="30%">
      <span v-if="status === 1">确定对选择应用进行 <b>停用</b> 处理? </span>
      <span v-if="status !== 1">确定对选择应用进行 <b>启用</b> 处理? </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="disableFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDisable">确 定</el-button>
      </span>
    </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 APP_CONFIG from "../../../public/config";

export default {
  name: 'Index',
  computed: {
    APP_CONFIG() {
      return APP_CONFIG
    }
  },
  data() {
    return {
      rules: {
        userName: [{ required: true, message: '请选择开发者', trigger: 'blur' }],
        name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
        appType: [{ required: true, message: '请选择应用类型', trigger: 'blur' }]
      },
      tag: '',
      expireDate: '', // 到期日期
      appStatus: '', // 应用状态
      alarmStatus: '', // 预警状态
      options: [
        {
          value: '',
          label: '全部'
        }, {
          value: 0,
          label: '停用'
        }, {
          value: 1,
          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宽
      disableFormVisible: false,
      addFormVisible: false,
      editFormVisible: false,
      showTimesFormVisible: false,
      checkAppId: '',
      selectTimes: [],
      users: [],
      addForm: {
        userId: '',
        name: '',
        appType: '',
        expireDate: '',
        description: ''
      },
      editForm: {
        id: '',
        name: '',
        appType: '',
        expireDate: '',
        description: ''
      },
      status: '',
      id: '',
      apiTypes: [],
      appTypes: [],
      deleteDialogVisible: false,
      apiList: [],
      dataModel: [], // 选中的接口列表
      activeNames: [],
      appTypeId: '', // 应用类型id
      userId: '', // 开发者id
      userList: [],
      checkAll: false
    }
  },
  created() {
    if (this.$route.query.developer !== '' && this.$route.query.developer !== undefined) {
      this.tag = this.$route.query.developer
    }
    this.searchAllApiTypes()
    this.searchAllAppTypes()
    this.searchAllApis()
    this.searchAllDevelopers()
    this.btn_search()
    // 获取开发者列表
    this.getUsers()
  },
  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))
      }
    },
    getUsers() {
      // const vm = this
      axios.get(process.env.BASE_API + '/user/listdevbyadmin', {
        params: {
        }
      }).then((response) => {
        this.userList = response.data.data
      })
    },
    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 '有待审接口'
      }
    },
    tableRowStyle({ row, rowIndex }) {
      if (row.remain === '0.0') {
        //  异常
        return 'background-color: red'
      } else if (row.remain > 0 && row.remainRate < 0.2) {
        // 预警
        return 'background-color: orange'
      }
    },
    calculateRemainTimes(ob) {
      if (ob.used === null) {
        ob.used = 0
      }
      return ob.total - ob.used
    },
    calculateRemainRate(ob) {
      if (ob.used === null) {
        ob.used = 0
      }
      var rate = parseFloat((ob.total - ob.used) / ob.total * 100).toFixed(2)
      return rate + '%'
    },
    searchAllDevelopers() {
      const vm = this
      axios.get(process.env.BASE_API + '/user/listdev', {
        params: {
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.users = []
        } else {
          // console.log(obj.data)
          // vm.totalDataNumber = parseInt(obj.total)
          if (vm.totalDataNumber > 0) {
            vm.users = obj.data
          } else {
            vm.users = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    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)
      })
    },
    searchAllApiTypes() {
      const vm = this
      axios.get(process.env.BASE_API + '/apitype/list', {
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          // vm.totalDataNumber = 0
          vm.apiTypes = []
        } else {
          // vm.totalDataNumber = parseInt(obj.total)
          if (vm.totalDataNumber > 0) {
            vm.apiTypes = obj.data
          } else {
            vm.apiTypes = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    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,
          id: this.userId,
          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.appTypeId = ''
      this.userId = ''
      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)
    },
    handleEdit(row) {
      // this.editForm.id = row.id
      // this.editForm.name = row.name
      // if (row.appType !== null) {
      //   this.editForm.appType = row.appType.id
      // }
      // this.editForm.expireDate = row.expireDate
      // this.editForm.description = row.description
      // this.getAppDetail()
      // this.editFormVisible = true
      // this.$router.push({ path: '/devapp/edit', query: { id: row.id }})
    },
    btnAddCancel() {
      this.addFormVisible = false
      this.addForm.name = ''
      this.addForm.userId = ''
      this.addForm.appType = ''
      this.addForm.description = ''
    },
    btnAddSubmit() {
      if (this.addForm.userId === '' || this.addForm.userId === undefined) {
        this.$message.info('请选择开发者，不能为空')
        return
      }
      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
      }
      const vm = this
      const params = new URLSearchParams()
      params.append('userId', vm.addForm.userId)
      params.append('name', vm.addForm.name)
      params.append('appTypeId', vm.addForm.appType)
      params.append('apis', vm.dataModel)
      if (vm.addForm.expireDate === '' || vm.addForm.expireDate === null) {
        params.append('expireDate', '')
      } else {
        params.append('expireDate', moment(vm.addForm.expireDate).format('YYYY-MM-DD'))
      }
      params.append('description', vm.addForm.description)
      axios.post(process.env.BASE_API + '/app/insertbyadmin', 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.pageNo = 1
          vm.btn_search()
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    btnUpdateCancel() {
      this.editFormVisible = false
      this.editForm.name = ''
      this.editForm.appType = ''
      this.editForm.expireDate = ''
      this.editForm.description = ''
      this.dataModel = []
    },
    btnUpdateSubmit() {
      if (this.editForm.name === '' || this.editForm.name === undefined) {
        this.$message.info('请输入应用类型名称，不能为空')
        return
      }
      var vm = this
      var params = new URLSearchParams()
      params.append('id', vm.editForm.id)
      params.append('name', vm.editForm.name)
      params.append('appTypeId', vm.editForm.appType)
      params.append('apis', vm.dataModel)
      if (vm.editForm.expireDate === '' || vm.editForm.expireDate === null || vm.editForm.expireDate === 'Invalid date') {
        params.append('expireDate', '')
      } else {
        params.append('expireDate', moment(vm.editForm.expireDate).format('YYYY-MM-DD'))
      }
      params.append('description', vm.editForm.description)
      axios.post(process.env.BASE_API + '/app/update', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.editFormVisible = false
          vm.pageNo = 1
          vm.btnUpdateCancel()
          vm.btn_search()
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    getAppDetail() {
      // console.log(this.appId)
      const vm = this
      axios.get(process.env.BASE_API + '/app/findbyid', {
        params: {
          id: parseInt(vm.editForm.id)
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.appData = []
        } else {
          vm.appData = obj.data
          vm.dataModel = obj.dataModel
          vm.appDescription = vm.appData[0].description
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    handleDelete(row) {
      this.id = row.id
      this.deleteDialogVisible = true
    },
    submitDelete() {
      var vm = this
      var params = new URLSearchParams()
      params.append('id', vm.id)
      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)
      })
    },
    handleCheck(row) {
      this.showTimesFormVisible = true
      this.checkAppId = row.id
      const vm = this
      axios.get(process.env.BASE_API + '/appapi/selecttimes', {
        params: {
          appId: this.checkAppId
        }
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.selectTimes = []
        } else {
          if (parseInt(obj.total) > 0) {
            vm.selectTimes = obj.data
          } else {
            vm.selectTimes = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    handleDisable(row) {
      this.id = row.id
      this.status = row.status
      this.disableFormVisible = true
    },
    submitDisable() {
      var vm = this
      var params = new URLSearchParams()
      params.append('id', vm.id)
      if (vm.status === 1) {
        params.append('status', 0)
      } else {
        params.append('status', 1)
      }
      axios.post(process.env.BASE_API + '/app/disable', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.btn_search()
        }
      }).catch(function(error) {
        alert(error)
      })
      this.disableFormVisible = false
    },
    searchAllApis() {
      const vm = this
      axios.get(process.env.BASE_API + '/apimngr/listapis', {}).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 => {
              val.isAll = false
              return val
            })
            vm.activeNames = obj.apiTypeNames
          } else {
            vm.apiList = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    }
  }
}
</script>

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

  .mydiv {
    float: right;
    margin-right: 10px;
  }
</style>
