<template>
  <div class="apply">
    <el-tabs v-model="activeName">
      <el-tab-pane label="接口需求申请" name="first">
        <el-table
          :data="applyList"
          border
          stripe
          style="width: 100%"
          :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
          :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}">
          <el-table-column
            prop="id"
            label="需求ID"/>
          <el-table-column
            prop="apiName"
            label="接口名称"/>
          <el-table-column
            prop="userName"
            label="申请人"/>
          <el-table-column
            prop="applyTime"
            label="申请时间"/>
          <el-table-column
            label="查看申请字段"
          >
            <template slot-scope="scope">
              <el-button type="success" plain @click="handleParam(scope.row)">
                查看申请字段
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="审核状态">
            <template slot-scope="scope">
              <el-tag :type="statusList[scope.row.status].type">{{ statusList[scope.row.status].label }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="action"
            label="操作"
            width="250">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleEdit(scope.row)">更改状态
              </el-button>
              <el-button
                v-if="scope.row.status === 1"
                size="mini"
                type="text"
                @click="handleEditApi(scope.row)">编辑接口
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="接口开发申请" name="second">
        <el-table
          :data="developList"
          style="width: 100%" border
          :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
          :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}">
          <!-- <el-table-column
            prop="id"
            label="需求ID"/> -->
          <el-table-column
            prop="apiName"
            label="接口名称"/>
          <el-table-column
            prop="userName"
            label="申请人"/>
          <el-table-column
            prop="applyTime"
            label="申请时间"/>
          <el-table-column
            prop="status"
            label="审核状态">
            <template slot-scope="scope">
              <el-tag :type="statusList[scope.row.status].type">{{ statusList[scope.row.status].label }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="action"
            label="操作"
            width="250">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleApplyEdit(scope.row)">更改状态
              </el-button>
              <el-button
                v-if="scope.row.status === 1"
                size="mini"
                type="text"
                @click="handleEditApi(scope.row)">编辑接口
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :visible.sync="dialogTableVisible" title="参数查看">
      <el-table :data="fieldJson" border stripe>
        <el-table-column property="param" label="申请参数"/>
        <el-table-column property="desc" label="申请描述"/>
      </el-table>
    </el-dialog>

    <el-dialog :visible.sync="editFormVisible" title="编辑状态" width="30%">
      <el-form :model="formStatus">
        <el-form-item label="审核状态">
          <el-select v-model="formStatus.status" placeholder="活动区域">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formStatus.status === 3" label="驳回描述">
          <el-input v-model="formStatus.disagreeReason" type="textarea" placeholder="请输入驳回问题描述"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnUpdateCancel">取 消</el-button>
        <el-button type="primary" @click="handleApply">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="applyEditFormVisible" title="编辑状态" width="30%">
      <el-form :model="formStatus">
        <el-form-item label="审核状态">
          <el-select v-model="formStatus.status" placeholder="活动区域">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formStatus.status === 3" label="驳回描述">
          <el-input v-model="formStatus.disagreeReason" type="textarea" placeholder="请输入驳回问题描述"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnUpdateCancel">取 消</el-button>
        <el-button type="primary" @click="handleApplyExamine">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="editFormApiVisible" title="编辑接口" width="70%">
      <el-form :model="formStatus">
        <div class="flex">
          <div class="w-30">
            <el-form-item :label-width="formLabelWidth" label="接口名称" prop="name">
              <el-input v-model="editForm.name" placeholder="请输入接口名称"/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="接口地址" prop="address">
              <el-input v-model="editForm.url" placeholder="请输入接口地址"/>
            </el-form-item>
            <!-- <el-form-item :label-width="formLabelWidth" label="调用量限制" prop="callLimit">
              <el-input v-model="editForm.callLimit" placeholder="请输入调用量限制"/>
            </el-form-item> -->
            <el-form-item :label-width="formLabelWidth" label="QPS限制" prop="qpsLimit">
              <el-input v-model="editForm.qpsLimit" placeholder="请输入QPS限制"/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="接口状态" prop="status">
              <el-select v-model="editForm.status" placeholder="请选择接口状态">
                <el-option
                  v-for="item in options"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="接口类型" prop="apiType">
              <el-select v-model="editForm.apiTypeId" placeholder="请选择接口类型">
                <el-option
                  v-for="item in apiTypes"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="接口版本">
              <el-input v-model="editForm.version" 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>
          </div>
          <div class="flex-1 w-70">
            <el-form-item :label-width="formLabelWidth" label="参数录入">
              <json-editor v-model="editForm.extJson" style="height: 100%"/>
            </el-form-item>
          </div>
        </div>
      </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>
  </div>
</template>

<script>
import { apiNeedApplyDetail, apiNeedApplyExamineList, apiNeedApplyUpdate } from '@/api/app'
import axios from 'axios'
import { applyExamine, applyExamineList, findbyid } from '@/api/apimngr'
import JsonEditor from '@/components/JsonEditor/index.vue'
import APP_CONFIG from "../../../public/config";

export default {
  name: 'Apply',
  computed: {
    APP_CONFIG() {
      return APP_CONFIG
    }
  },
  components: { JsonEditor },
  data() {
    return {
      activeName: 'first',
      // 权限申请列表
      applyList: [],
      // 开发申请列表
      developList: [],
      dialogTableVisible: false,
      fieldJson: [],
      formLabelWidth: '120px',
      editFormVisible: false,
      formStatus: {
        status: 0,
        disagreeReason: ''
      },
      editFormApiVisible: false,
      editForm: {
        id: '',
        name: '',
        url: '',
        callLimit: '',
        qpsLimit: '',
        status: '',
        apiTypeId: '',
        version: '',
        docUrl: '',
        description: '',
        extJson: ''
      },
      options: [{
        value: 0,
        label: '未发布'
      }, {
        value: 1,
        label: '发布'
      }],
      apiTypes: [],
      statusList: [{
        value: 0,
        label: '待审核',
        type: 'warning'
      }, {
        value: 1,
        label: '已审核待开发',
        type: 'success'
      }, {
        value: 2,
        label: '已开发完成',
        type: 'success'
      }, {
        value: 3,
        label: '已驳回',
        type: 'danger'
      }],
      applyEditFormVisible: false
    }
  },
  created() {
    // 判断开发者权限
    this.getApplyList()
    this.getDevelopList()
  },
  methods: {
    // 获取权限申请列表
    getApplyList() {
      apiNeedApplyExamineList().then(res => {
        this.applyList = res.data
      })
    },
    // 获取开发申请列表
    getDevelopList() {
      applyExamineList().then(res => {
        this.developList = res.data
      })
    },
    handleParam(item) {
      apiNeedApplyDetail(item.id).then(res => {
        this.dialogTableVisible = true
        this.fieldJson = JSON.parse(res.data.fieldJson)
      })
    },
    btnUpdateCancel() {
      this.applyEditFormVisible = false
      this.editFormVisible = false
      this.editForm.name = ''
      this.editForm.description = ''
    },
    async handleEditApi(row) {
      this.editFormApiVisible = true
      row = await findbyid(row.apiId)
      row = row.data.api
      this.editForm.id = row.id
      this.editForm.name = row.name
      this.editForm.url = row.url
      this.editForm.callLimit = row.callLimit
      this.editForm.qpsLimit = row.qpsLimit
      this.editForm.status = row.status
      this.editForm.apiTypeId = row.apiType.id
      this.editForm.version = row.version
      this.editForm.docUrl = row.docUrl
      try {
        this.editForm.extJson = JSON.parse(JSON.parse(row.extJson))
      } catch (e) {
        this.editForm.extJson = JSON.parse(row.extJson)
      }

      if (row.description === null) {
        this.editForm.description = ''
      } else {
        this.editForm.description = row.description
      }
    },
    btnUpdateSubmit() {
      if (this.editForm.name === '' || this.editForm.name === undefined) {
        this.$message.info('请输入接口名称，不能为空')
        return
      }
      if (this.editForm.url === '' || this.editForm.url === undefined) {
        this.$message.info('请输入接口地址，不能为空')
        return
      }
      if (this.editForm.callLimit === '' || this.editForm.callLimit === undefined) {
        this.$message.info('请输入接口调用量限制，不能为空')
        return
      }
      if (this.editForm.qpsLimit === '' || this.editForm.qpsLimit === undefined) {
        this.$message.info('请输入接口qps限制，不能为空')
        return
      }
      if (this.editForm.status === '' || this.editForm.status === undefined) {
        this.$message.info('请选择接口状态，不能为空')
        return
      }
      if (this.editForm.apiTypeId === '' || this.editForm.apiTypeId === undefined) {
        this.$message.info('请选择接口类型，不能为空')
        return
      }
      const vm = this
      const params = new URLSearchParams()
      params.append('id', vm.editForm.id)
      params.append('name', vm.editForm.name)
      params.append('url', vm.editForm.url)
      params.append('callLimit', vm.editForm.callLimit)
      params.append('qpsLimit', vm.editForm.qpsLimit)
      params.append('status', vm.editForm.status)
      params.append('apiTypeId', vm.editForm.apiTypeId)
      params.append('description', vm.editForm.description)
      params.append('version', vm.editForm.version)
      params.append('docUrl', vm.editForm.docUrl)
      params.append('extJson', JSON.stringify(vm.editForm.extJson))
      axios.post(process.env.BASE_API + '/apimngr/update', params).then(function(response) {
        const obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.editFormApiVisible = false
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    async handleEdit(row) {
      this.editFormVisible = true
      this.formStatus = JSON.parse(JSON.stringify(row))
    },
    handleApplyEdit(row) {
      this.applyEditFormVisible = true
      this.formStatus = JSON.parse(JSON.stringify(row))
    },
    // 提交审核
    async handleApply() {
      // 校验disagreeReason
      if (this.formStatus.status === 3 && (this.formStatus.disagreeReason === '' || this.formStatus.disagreeReason === undefined)) {
        this.$message.info('请填写驳回原因')
        return
      }
      // 二次确认
      this.$confirm('确定更改审核吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const params = new URLSearchParams()
        params.append('id', this.formStatus.id)
        params.append('status', this.formStatus.status)
        params.append('disagreeReason', this.formStatus.disagreeReason)
        const res = await apiNeedApplyUpdate(params)
        if (res.code === 10000) {
          this.$message.success('更改状态成功')
          this.getApplyList()
          this.editFormVisible = false
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 提交审核
    async handleApplyExamine() {
      // 校验disagreeReason
      if (this.formStatus.status === 3 && (this.formStatus.disagreeReason === '' || this.formStatus.disagreeReason === undefined)) {
        this.$message.info('请填写驳回原因')
        return
      }
      const params = new URLSearchParams()
      params.append('apiId', this.formStatus.apiId)
      params.append('status', this.formStatus.status)
      params.append('disagreeReason', this.formStatus.disagreeReason)
      const res = await applyExamine(params)
      if (res.code === 10000) {
        this.$message.success('更改状态成功')
        this.applyEditFormVisible = false
        this.getDevelopList()
      } else {
        this.$message.error(res.message)
      }
    },
    searchAllApiTypes() {
      const vm = this
      axios.get(process.env.BASE_API + '/apitype/list', {}).then(function(response) {
        const obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.apiTypes = []
        } else {
          if (parseInt(obj.total) > 0) {
            vm.apiTypes = obj.data
          } else {
            vm.apiTypes = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    }
  }
}
</script>

<style scoped>

</style>
