<template style="height=0px;improtanent">
  <div class="app-container">
    <el-header style="height: auto;!improtant">
      <div class="filter-container" style="padding-bottom: 20px;!improtant">
        <el-input v-model="listQuery.id" placeholder="ID" style="width: 80px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.customName" placeholder="服务名" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.interfaceName" placeholder="接口类" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.methodName" placeholder="方法名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.serviceVersion" placeholder="版本" style="width: 100px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-select v-model="listQuery.value" placeholder="状态" style="width: 100px;" class="filter-item" @change="handleFilter">
          <el-option v-for="item in listQuery.options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" style="margin-left: 1px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
        <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:1px;" @change="tableKey=tableKey+1">
          备注
        </el-checkbox>
      </div>
    </el-header>
    <!-- <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" /> -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      fit
      highlight-current-row
      style="width: 100%;"
      :header-cell-style="styleObj"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable align="center" min-width="60">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务名" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.customName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接口类" min-width="220px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.interfaceName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="版本" min-min-width="60px">
        <template slot-scope="{row}">
          <span>{{ row.serviceVersion }}</span>
          <!-- <el-tag>{{ row.type | typeFilter }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="方法名" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.methodName }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="Imp" width="80px">
        <template slot-scope="scope">
          <svg-icon v-for="n in +scope.row.importance" :key="n" icon-class="star" class="meta-item__icon" />
        </template>
      </el-table-column>
      <el-table-column label="Readings" align="center" width="95">
        <template slot-scope="{row}">
          <span v-if="row.pageviews" class="link-type" @click="handleFetchPv(row.pageviews)">{{ row.pageviews }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" class-name="status-col" min-width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.methodStatus | statusFilter">
            {{ statusMappings.get(row.methodStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTimeStr }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="showReviewer" label="备注" min-width="110px" align="center">
        <template slot-scope="scope">
          <span style="color:red;">{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="370px" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleCheck(row)">
            查看
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="primary" size="mini" @click="handleCopy(row)">
            复制
          </el-button>
          <el-button v-if="row.methodStatus!=1" size="mini" type="success" @click="handleModifyStatus(row, 1)">
            开启
          </el-button>
          <el-button v-if="row.methodStatus!=0" size="mini" type="danger" @click="handleModifyStatus(row, 0)">
            关闭
          </el-button>
          <el-button type="primary" size="mini" @click="redirectTo(row.id, row.methodName)">
            规则 >>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.curIndex" :limit.sync="listQuery.pageSize" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="65%" @open="dialogOpenInit()">
      <el-form ref="serviceDataForm" :rules="serviceDataRules" :model="serviceData" label-position="left" label-width="120px" style="width: 500px; margin-left:80px;">
        <el-form-item label="名称" prop="customName">
          <el-input v-model="serviceData.customName" placeholder="dj_order_圈司机" title="自定义，供配置人员查看,建议”业务线_模块_功能" />
        </el-form-item>
        <div style="display:flex; margin-left:0px;">
          <el-form-item label="环境配置" prop="envChannel" style="flex:1;">
            <el-select v-model="serviceData.envChannel" class="filter-item" style="width: 190px;" filterable placeholder="环境配置" @change="updateEnvChannel(serviceData.envChannel)">
              <el-option v-for="item in envTypeSelections" :key="item.key" :label="item.display_name" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item prop="envId" style="flex:1; margin-left:-120px;">
            <el-select v-model="serviceData.envId" class="filter-item" style="width: 190px;" filterable placeholder="环境" @change="showZkAddress">
              <el-option v-for="item in envSelections" :key="item.key" :label="item.display_name" :value="item.key" />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="接口类名" prop="interfaceName">
          <el-input v-model="serviceData.interfaceName" placeholder="com.didi.prado.config.api.CampaignRemoteServce" title="包名.接口类名" />
        </el-form-item>
        <el-form-item label="方法名" prop="methodName">
          <el-input v-model="serviceData.methodName" placeholder="addCampaign" />
        </el-form-item>
        <el-form-item label="服务版本" prop="serviceVersion">
          <el-input v-model="serviceData.serviceVersion" placeholder="1.0.0_test" />
        </el-form-item>
        <el-form-item label="协议" prop="protocol">
          <el-select v-model="serviceData.protocol" class="filter-item" filterable clearable placeholder="协议">
            <el-option v-for="item in protocols" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="消费者" prop="consumerIds">
          <el-select v-model="serviceData.consumerIds" class="filter-item" multiple placeholder="消费者">
            <el-option v-for="item in consumerSelections" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="Date" prop="timestamp">
          <el-date-picker v-model="temp.timestamp" type="datetime" placeholder="Please pick a date" />
        </el-form-item>
        <el-form-item label="Status">
          <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="Imp">
          <el-rate v-model="temp.importance" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :max="3" style="margin-top:8px;" />
        </el-form-item> -->
        <el-form-item label="入参类型" prop="methodParamsTypes">
          <el-input v-model="serviceData.methodParamsTypes" :autosize="{ minRows: 2, maxRows: 8}" type="textarea" title="列表形式,参数有序，多个参数类型以英文”,“分隔" placeholder="[java.lang.Integer, com.didi.prado.config.api.param.CampaignRequest]" />
        </el-form-item>
        <el-form-item label="返回值类型" prop="returnDataStructure">
          <el-input v-model="serviceData.returnDataStructure" :autosize="{ minRows: 2, maxRows: 8}" type="textarea" title="key:每个自定义类型在返回结构中的节点树，以英文“.“分隔；value:自定义类型的全限定类名" placeholder="{'data':'com.didi.order.api.response.BaserOrderInfoResult','data.feeInfo':'com.didi.order.api.response.FeeInfoResult'}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button v-if="showSubmitBtn" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped>
.filter-item {
  margin-top: 10px;
}
</style>

<script>
import { fetchEnvInfo, fetchServiceById, fetchServiceList, fetchConsumerList, createService, updateService, changeStatus } from '@/api/interface'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const envTypeSelections = [
  { key: 1, display_name: '自定义环境配置' },
  { key: 2, display_name: '环境平台' }
]

var envSelections = []
var consumerSelections = []

const protocols = [
  { key: 'dubbo', display_name: 'dubbo' }
  // { key: 'http', display_name: 'http' }
]

// var envTypeID = 1;
// arr to obj, such as { CN : "China", US : "USA" }
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
//   acc[cur.key] = cur.display_name
//   return acc
// }, {})

export default {
  name: 'Interface',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        draft: 'info',
        0: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      styleObj: {
        'color': 'rgba(0, 0, 0, 0.726)'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      statusMappings: new Map([[1, '已开启'], [0, '未开启']]),
      statusOperateMap: new Map([[1, '开启'], [0, '关闭']]),
      listQuery: {
        options: [{ value: '0', label: '未开启' }, { value: '1', label: '已开启' }],
        value: '',
        curIndex: 1,
        pageSize: 20,
        customName: '',
        interfaceName: '',
        // page: 1,
        // limit: 20,
        // importance: undefined,
        // title: undefined,
        // type: undefined,
        sort: '+id',
        id: null,
        methodName: '',
        serviceVersion: '',
        methodStatus: null
      },
      importanceOptions: [1, 2, 3],
      envTypeSelections,
      envSelections,
      consumerSelections,
      protocols,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      showSubmitBtn: true,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      serviceData: {
        // bizLine: 0,
        // bizModuleId: 0,
        customName: '',
        interfaceName: '',
        protocol: '',
        serviceVersion: '',
        envChannel: 1,
        envId: 0,
        methodName: '',
        methodParamsTypes: '',
        returnDataStructure: '',
        methodStatus: 1,
        consumerIds: [],
        remark: '',
        updator: ''
      },
      // ConsumerIdsStr: this.serviceData.consumerIds.replace('[', '').replace(']', '').split(',').map(Number),
      serviceDataExt: {
        id: 0,
        bizLine: 0,
        bizModuleId: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增服务'
      },
      dialogPvVisible: false,
      pvData: [],
      serviceDataRules: {
        customName: [{ required: true, message: '名称不能为空', trigger: 'change' }],
        envChannel: [{ required: true, message: '请选择环境配置', trigger: 'change' }],
        envId: [{ required: true, message: '请选择环境', trigger: 'change' }],
        interfaceName: [{ required: true, message: '接口名称不能为空', trigger: 'change' }],
        serviceVersion: [{ required: true, message: '服务版本不能为空', trigger: 'change' }],
        protocol: [{ required: true, message: '请选择协议类型', trigger: 'change' }],
        consumerIds: [{ required: false, message: '请选择消费者', trigger: 'change' }],
        methodName: [{ required: true, message: '方法名称不能为空', trigger: 'change' }]
        // methodParamsTypes: [{ required: true, message: '入参类型不能为空', trigger: 'change' }],
        // returnDataStructure: [{ required: true, message: '返回值类型不能为空', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchServiceList(this.listQuery).then(response => {
        console.log(this.listQuery)
        this.list = response.data.mockMethodList
        this.total = response.data.total
        // Just to simulate the time of the request
        this.listLoading = false
        // setTimeout(() => {
        //   this.listLoading = false
        // }, 1.5 * 1000)
      })
    },
    updateEnvChannel(v) {
      // console.log(v)
      this.serviceData.envChannel = v
      this.envSelections = []
      fetchEnvInfo(v).then(response => {
        for (var sel of response.data) {
          var envSel = {}
          envSel.key = sel.envId
          envSel.display_name = sel.envName
          this.envSelections.push(envSel)
        }
      })
    },
    getConsumers() {
      this.consumerSelections = []
      fetchConsumerList().then(response => {
        for (var sel of response.data) {
          var consumerSel = {}
          consumerSel.key = sel.dubboConsumerId
          consumerSel.display_name = sel.customizeName
          this.consumerSelections.push(consumerSel)
        }
        // console.log(this.serviceData.consumerIds)
        // for (var op of this.consumerSelections) {
        //   if (op.key in this.serviceData.consumerIds) {
        //     this.consumerSelected.push(op)
        //     // this.consumerSelected = op.display_name
        //   }
        // }
        // console.log(this.consumerSelected)
      })
    },
    dialogOpenInit() {
      this.updateEnvChannel(this.serviceData.envChannel)
      this.getConsumers()
    },
    handleFilter() {
      // this.listQuery.page = 1
      this.listQuery.methodStatus = this.listQuery.value
      this.getList()
    },
    handleModifyStatus(row, status) {
      var statusData = {
        id: row.id,
        methodStatus: status
      }
      // console.log(statusData)
      changeStatus(statusData).then(response => {
        // console.log(response)
        if (response.code === 200) {
          row.methodStatus = status
          this.$message({
            message: row.id.toString() + ' ' + this.statusOperateMap.get(status) + '成功！',
            type: 'success'
          })
        } else {
          this.$message({
            message: row.id.toString() + ' ' + this.statusOperateMap.get(status) + '失败！',
            type: 'danger'
          })
        }
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetServiceData() {
      this.serviceData = {
        // bizLine: 0,
        // bizModuleId: 0,
        customName: '',
        interfaceName: '',
        protocol: '',
        serviceVersion: '',
        envChannel: 1,
        envId: 0,
        methodName: '',
        methodParamsTypes: '[]',
        returnDataStructure: '',
        methodStatus: 1,
        consumerIds: [],
        remark: '',
        updator: ''
      }
    },
    handleCreate() {
      this.resetServiceData()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.showSubmitBtn = true
      this.$nextTick(() => {
        this.$refs['serviceDataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['serviceDataForm'].validate((valid) => {
        if (valid) {
          // this.serviceData.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          delete this.serviceData.id
          delete this.serviceData.bizLine
          delete this.serviceData.bizModuleId
          delete this.serviceData.bizName
          delete this.serviceData.consumerCustomizeName
          delete this.serviceData.consumerNames
          delete this.serviceData.createTime
          delete this.serviceData.createTimeStr
          delete this.serviceData.envName
          delete this.serviceData.updateTime
          delete this.serviceData.updateTimeStr
          delete this.serviceData.zkAddress
          if (typeof this.serviceData.consumerIds === 'object') {
            this.serviceData.consumerIds = '[' + this.serviceData.consumerIds.toString() + ']'
          }
          // console.log('#######################')
          // console.log(this.serviceData)
          // console.log('#######################')
          createService(this.serviceData).then(response => {
            // this.list.unshift(this.serviceData)
            // console.log(response)
            if (response.code === 200) {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: 'Success',
                message: response.msg,
                type: 'success',
                duration: 10000
              })
            } else {
              this.$notify({
                title: 'Failed',
                message: response.msg,
                type: 'error',
                duration: 10000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      var queryData = { id: row.id }
      fetchServiceById(queryData).then(response => {
        // console.log(response)
        var rowData = response.data.mockMethodList
        // this.serviceData.timestamp = new Date(this.temp.timestamp)
        // console.log(this.serviceData)
        // console.log(row_data[0])
        this.serviceData = Object.assign({}, rowData[0])
        this.serviceDataExt.id = row.id
        this.serviceDataExt.bizLine = row.bizLine
        this.serviceDataExt.bizModuleId = row.bizModuleId
        // console.log(this.serviceData.consumerIds.split('[')[1].split(']')[0].split(','))
        if (this.serviceData.consumerIds === '[]') {
          this.serviceData.consumerIds = []
        } else {
          this.serviceData.consumerIds = this.serviceData.consumerIds.split('[')[1].split(']')[0].split(',').map(value => { return parseInt(value) })
        }
        // console.log(this.serviceData)
        // this.serviceData.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.showSubmitBtn = true
        this.$nextTick(() => {
          this.$refs['serviceDataForm'].clearValidate()
        })
      })
    },
    handleCheck(row) {
      var queryData = { id: row.id }
      fetchServiceById(queryData).then(response => {
        // console.log(response)
        var rowData = response.data.mockMethodList
        // this.serviceData.timestamp = new Date(this.temp.timestamp)
        // console.log(this.serviceData)
        // console.log(row_data[0])
        this.serviceData = Object.assign({}, rowData[0])
        this.serviceDataExt.id = row.id
        this.serviceDataExt.bizLine = row.bizLine
        this.serviceDataExt.bizModuleId = row.bizModuleId
        // console.log(this.serviceData.consumerIds.split('[')[1].split(']')[0].split(','))
        if (this.serviceData.consumerIds === '[]') {
          this.serviceData.consumerIds = []
        } else {
          this.serviceData.consumerIds = this.serviceData.consumerIds.split('[')[1].split(']')[0].split(',').map(value => { return parseInt(value) })
        }
        // console.log(this.serviceData)
        // this.serviceData.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.showSubmitBtn = false
        this.$nextTick(() => {
          this.$refs['serviceDataForm'].clearValidate()
        })
      })
    },
    handleCopy(row) {
      var queryData = { id: row.id }
      fetchServiceById(queryData).then(response => {
        // console.log(response)
        var rowData = response.data.mockMethodList
        // this.serviceData.timestamp = new Date(this.temp.timestamp)
        // console.log(this.serviceData)
        // console.log(row_data[0])
        this.serviceData = Object.assign({}, rowData[0])
        this.serviceDataExt.id = row.id
        this.serviceDataExt.bizLine = row.bizLine
        this.serviceDataExt.bizModuleId = row.bizModuleId
        // console.log(this.serviceData.consumerIds.split('[')[1].split(']')[0].split(','))
        if (this.serviceData.consumerIds === '[]') {
          this.serviceData.consumerIds = []
        } else {
          this.serviceData.consumerIds = this.serviceData.consumerIds.split('[')[1].split(']')[0].split(',').map(value => { return parseInt(value) })
        }
        // console.log(this.serviceData)
        // this.serviceData.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['serviceDataForm'].clearValidate()
        })
      })
    },
    updateData() {
      this.$refs['serviceDataForm'].validate((valid) => {
        if (valid) {
          const tempData = {
            id: this.serviceDataExt.id,
            bizLine: this.serviceDataExt.bizLine,
            bizModuleId: this.serviceDataExt.bizModuleId,
            customName: this.serviceData.customName,
            interfaceName: this.serviceData.interfaceName,
            protocol: this.serviceData.protocol,
            serviceVersion: this.serviceData.serviceVersion,
            envChannel: this.serviceData.envChannel,
            envId: this.serviceData.envId,
            methodName: this.serviceData.methodName,
            methodParamsTypes: this.serviceData.methodParamsTypes,
            returnDataStructure: this.serviceData.returnDataStructure,
            methodStatus: this.serviceData.methodStatus,
            consumerIds: '[' + this.serviceData.consumerIds.toString() + ']',
            remark: this.serviceData.remark,
            updator: ''
          }
          // console.log(tempData)
          updateService(tempData).then(response => {
            if (response.code === 200) {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: 'Success',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'Failed',
                message: response.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    redirectTo(id, methodName) {
      // console.log(id,methodName)
      this.$router.push({
        path: `/mock/interface/${id}`,
        query: {
          methodName: methodName
        }
      })
    }
  }
}
</script>
