<template>
  <div class="app-container">
    <el-header style="height:auto;!improtant">
      <div class="filter-container" style="padding-bottom: 20px;!improtant">
        <el-input v-model="listQuery.whenScript" disabled placeholder="any" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.execSort" placeholder="优先级" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <!-- <el-input-number v-model="listQuery.execSort" label="优先级" :min="1" :max="100" /> -->
        <el-select v-model="listQuery.status" class="filter-item" filterable clearable placeholder="状态">
          <el-option v-for="item in ruleStatus" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <!-- <el-input v-model="listQuery.interfaceName" placeholder="接口类" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" /> -->
        <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: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
        <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
          显示返回值
        </el-checkbox>
        <el-button style="float: right;" type="primary" @click="prev">
          返回
        </el-button>
      </div>
    </el-header>
    <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="custom" align="center" min-width="80px">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接口id" min-width="150px" align="center">
        <!-- <template slot-scope="scope"> -->
        <span>{{ this.$route.query.methodName }}</span>
        <!-- </template> -->
      </el-table-column>
      <el-table-column label="mock结果" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.execSort }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="方法ID" min-width="220px" align="center">
        <span>{{ this.$route.path.split('/')[3] }}</span>
      </el-table-column> -->
      <el-table-column label="规则" min-min-width="60px">
        <template slot-scope="{row}">
          <span>{{ row.whenScript }}</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.execSort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" min-width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ statusMappings.get(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.execSort }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="更新时间" min-width="170px" 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.returnMessage }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="370" class-name="small-padding fixed-width" fixed="right">
        <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 type="primary" size="mini">
            测试
          </el-button>
          <el-button v-if="row.status!=1" size="mini" type="success" @click="handleModifyStatus(row, 1)">
            开启
          </el-button>
          <el-button v-if="row.status!=0" size="mini" type="danger" @click="handleModifyStatus(row, 0)">
            关闭
          </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%">
      <el-form ref="ruleDataForm" :rules="roleDataRules" :model="ruleData" label-position="left" label-width="120px" style="width: 500px; margin-left:80px;">
        <el-form-item label="规则" prop="whenScript">
          <el-input v-model="ruleData.whenScript" placeholder="any" disabled />
        </el-form-item>
        <el-form-item label="优先级" prop="execSort">
          <el-input-number v-model="ruleData.execSort" label="优先级" :min="1" :max="100" title="值越大，优先级越高" />
        </el-form-item>
        <el-form-item label="返回值" prop="returnMessage">
          <el-input v-model="ruleData.returnMessage" :autosize="{ minRows: 3, maxRows: 10}" type="textarea" placeholder="{ 'code': 200, 'data': { 'crowdComposition': 'U_866', 'campaignId': 789, 'id': 4606, 'class': 'com.didi.prado.config.api.dto.CampaignCrowdDTO'}}" @blur="getFormatJsonStrFromStringRule(ruleData.returnMessage)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button v-if="showSubmit" 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>

<script>
import { fetchEnvInfo, fetchRuleById, createRule, updateRule, changeStatus } from '@/api/httpmock'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

// var envSelections = []

const ruleStatus = [
  { key: 1, display_name: '已开启' },
  { key: 0, display_name: '未开启' },
  { key: '', display_name: '全部显示' }
]

export default {
  name: 'Httpmock',
  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, '未开启']]),
      ruleStatus,
      listQuery: {
        curIndex: 1,
        pageSize: 20,
        whenScript: 'any',
        methodId: 0,
        execSort: null,
        status: null,
        methodProtocol: ''
      },
      showSubmit: true,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      ruleData: {
        methodId: 0,
        creator: '',
        updator: '',
        execSort: 1,
        whenScript: '',
        returnMessage: '',
        curIndex: 1,
        pageSize: 20
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增规则'
      },
      dialogPvVisible: false,
      pvData: [],
      roleDataRules: {
        whenScript: [{ required: true, message: '规则不能为空', trigger: 'change' }],
        execSort: [{ required: true, message: '优先级1-100', trigger: 'change' }],
        returnMessage: [{ required: true, message: '不能为空', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    prev() {
      this.$router.go(-1)
    },
    getList() {
      this.listLoading = false
      this.ruleData.methodId = parseInt(this.$route.path.split('/')[3])
      // console.log(this.listQuery.methodId)
      console.log(this.ruleData)
      updateRule(this.ruleData).then(response => {
        this.list = response.data.mockRuleList
        this.total = response.data.total
        // Just to simulate the time of the request
        this.listLoading = false
      })
    },
    getFormatJsonStrFromStringRule: function(jsonStr) {
      console.log(jsonStr)
      var res = ''
      for (var i = 0, j = 0, k = 0, ii, ele; i < jsonStr.length; i++) { // k:缩进，j:""个数
        ele = jsonStr.charAt(i)
        if (j % 2 === 0 && ele === '}') {
          k--
          for (ii = 0; ii < k; ii++) ele = '    ' + ele
          ele = '\n' + ele
        } else if (j % 2 === 0 && ele === '{') {
          ele += '\n'
          k++
          for (ii = 0; ii < k; ii++) ele += '    '
        } else if (j % 2 === 0 && ele === ',') {
          ele += '\n'
          for (ii = 0; ii < k; ii++) ele += '    '
        } else if (ele === '"') j++
        res += ele
      }
      // eslint-disable-next-line no-return-assign
      return this.ruleData.returnMessage = res
    },
    updateEnvChannel(v) {
      console.log(v)
      this.ruleData.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)
        }
      })
    },
    handleFilter() {
      // this.listQuery.page = 1
      this.listQuery.methodStatus = this.listQuery.value
      this.getList()
    },
    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.ruleData = {
        methodId: 0,
        creator: '',
        updator: '',
        execSort: 1,
        whenScript: '',
        returnMessage: '',
        curIndex: 1,
        pageSize: 20
      }
    },
    handleCreate() {
      this.resetServiceData()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.showSubmit = true
      this.$nextTick(() => {
        this.$refs['ruleDataForm'].clearValidate()
      })
    },
    createData() {
      const shouldJson = this.ruleData.returnMessage
      if (this.ruleData.whenScript === '') { this.ruleData.whenScript = 'any' }
      if (typeof shouldJson === 'string') {
        this.$refs['ruleDataForm'].validate((valid) => {
          if (valid) {
            delete this.ruleData.id
            this.ruleData.methodId = parseInt(this.$route.path.split('/')[3])
            createRule(this.ruleData).then(response => {
              // this.list.unshift(this.serviceData)
              if (response.code === 200) {
                this.dialogFormVisible = false
                this.getList()
                this.$notify({
                  title: 'Success',
                  message: 'Created Successfully',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: 'Failed',
                  message: 'Created Failed',
                  type: 'error',
                  duration: 2000
                })
              }
            })
          }
        })
      }
    },
    handleUpdate(row) {
      var queryData = { id: row.id }
      fetchRuleById(queryData).then(response => {
        console.log(response)
        var row_data = response.data.mockRuleList
        // this.ruleData.timestamp = new Date(this.temp.timestamp)
        // console.log(this.ruleData)
        // console.log(row_data)
        this.ruleData = Object.assign({}, row_data[0])
        // console.log(this.ruleData)
        this.ruleData.timestamp = new Date(this.ruleData.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.showSubmit = true
        this.$nextTick(() => {
          this.$refs['ruleDataForm'].clearValidate()
        })
      })
    },
    handleModifyStatus(row, status) {
      var statusData = {
        id: row.id,
        status: status
      }
      // console.log(statusData)
      changeStatus(statusData).then(response => {
        // console.log(response)
        if (response.code === 200) {
          row.status = status
          this.$message({
            message: row.id.toString() + ' 操作成功！',
            type: 'success'
          })
        } else {
          this.$message({
            message: row.id.toString() + ' 操作失败！',
            type: 'danger'
          })
        }
      })
    },
    handleCopy(row) {
      this.ruleData = Object.assign({}, row) // copy obj
      this.ruleData.timestamp = new Date(this.ruleData.timestamp)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.showSubmit = true
      this.$nextTick(() => {
        this.$refs['ruleDataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['ruleDataForm'].validate((valid) => {
        if (valid) {
        //   const tempData = Object.assign({}, this.ruleData)
          const tempData = {
            id: this.ruleData.id,
            methodId: parseInt(this.$route.path.split('/')[3]),
            creator: '',
            updator: '',
            execSort: this.ruleData.execSort,
            whenScript: this.ruleData.whenScript,
            returnMessage: this.ruleData.returnMessage,
            methodName: this.$route.query.methodName
          }
          updateRule(tempData).then(() => {
            this.getList()
            // for (const v of this.list) {
            //   if (v.id === this.ruleData.id) {
            //     const index = this.list.indexOf(v)
            //     this.list.splice(index, 1, this.ruleData)
            //     break
            //   }
            // }
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    handleCheck(row) {
      var queryData = { id: row.id }
      fetchRuleById(queryData).then(response => {
        console.log(response)
        var row_data = response.data.mockRuleList
        // this.ruleData.timestamp = new Date(this.temp.timestamp)
        // console.log(this.ruleData)
        // console.log(row_data)
        this.ruleData = Object.assign({}, row_data[0])
        // console.log(this.ruleData)
        this.ruleData.timestamp = new Date(this.ruleData.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.showSubmit = false
        this.$nextTick(() => {
          this.$refs['ruleDataForm'].clearValidate()
        })
      })
    }
  }
}
</script>

<style>
.el-notification.right{
  position: fixed;
  right: 38.5%;
}
</style>

