<template>
  <div class="market-data">
    <el-row style="height: 100%">
      <el-col :span="4" class="left" :style="{'height': (tableHeight + 61) + 'px'}">
        <div class="title">
          <p>市场价格</p>
        </div>
        <ul >
          <li v-for="(item) in typeList" :key="item.value" :class="{'selected': item.value === selected}" @click="handleClick(item.value)">
            <span>{{item.text}}</span>
          </li>
        </ul>
      </el-col>
      <el-col :span="20" class="right">
        <div class="title">
          <p>市场价格列表</p>
          <div class="title">
            <div v-if="selected === 'BOND'" class="mg-r-10">
              <span>价格类型：</span>
              <el-select v-model="bondType" style="width: 130px">
                <el-option v-for="item in bondOptions" :key="item.value" :label="item.text" :value="item.value"></el-option>
              </el-select>
            </div>
            <div v-if="selected === 'RATING'" class="mg-r-10 title" >
              <div>
                <span>评级目标：</span>
                <el-select v-model="rateTypeSelected" filterable clearable style="width: 130px;padding-right: 10px" placeholder="" @change="rateTypeChange">
                  <el-option v-for="item in rateTypeOptions" :key="item.value" :label="item.text" :value="item.value"></el-option>
                </el-select>
                <el-select v-model="rateTarget" clearable filterable :filter-method="filterMethod" placeholder="" style="width: 150px;padding-right: 20px">
                  <el-option v-for="item in rateTargetOptions.slice(0, 100)" :key="item.id" :label="item.localName" :value="item.id"></el-option>
                </el-select>
              </div>
              <div>
                <span>评级机构：</span>
                <el-select v-model="rankAgency" clearable filterable multiple collapse-tags placeholder="" style="width: 170px" @change="agencyChange">
                  <el-option v-for="item in rankAgencyOptions" :key="item.id" :label="item.localName" :value="item.id"></el-option>
                </el-select>
              </div>
            </div>
            <div class="mg-r-5">
              <el-button type="primary" size="small" :disabled="selection.length <= 0" class="mg-r-5" @click="saveInBatch">批量保存</el-button>
              <i class="el-icon-setting mg-r-5"></i>
            </div>
          </div>
        </div>
        <el-table v-loading="loading" :data="tableData" :height="tableHeight" border stripe class="table-sty" @selection-change="tableSelect" 
          :row-class-name="tableRowClassName" @cell-dblclick="(row, column) => cellDblclick(row, column)" element-loading-background="rgba(0,0,0,0)" empty-text="暂无数据">
          <el-table-column  width="1" />
          <el-table-column fixed="left" type="selection" width="50" />
          <div v-for="col in columns" :key="col.field">
            <el-table-column v-if="col.field !== 'operations'" :label="col.name" :prop="col.field" :align="col.align || 'center'">
              <template slot-scope="scope">
                <template v-if="col.isEdit">
                  <el-input v-if="scope.row.canEdit" v-model="scope.row[col.field]" type="number" :ref="'input' + scope.row.index" @focus="focus(col.field)" 
                  @blur="inputBlur(scope.row)" :disabled="setDisabled(col.field)" />
                  <span v-else>{{scope.row[col.field]}}</span>
                </template>
                <template  v-else>
                  <span>{{scope.row[col.field]}}</span>
                </template>
              </template>
            </el-table-column>
            <el-table-column v-else fixed="right" label="操作" width="160">
              <template slot-scope="scope">
                <el-button v-if="!scope.row.canEdit" @click="edit(scope.row)" type="text" size="small">修改</el-button>
                <el-button v-if="scope.row.canEdit" @click="save(scope.row)" type="text" size="small">保存</el-button>
                <el-button v-if="scope.row.canEdit" @click="cancel(scope.row, col)" type="text" size="small">取消</el-button>
                <el-button @click="showHistory(scope.row)" type="text" size="small">历史版本</el-button>
              </template>
            </el-table-column>
          </div>
          
          
        </el-table>
        <el-pagination
          ref="pagination"
          class="no-border-top"
          :page-sizes="[15, 30, 50, 100]"
          :page-size.sync="pageSize"
          layout="total,  prev, pager, next,sizes, jumper"
          :current-page.sync="pageNum"
          :total="total"
          :pager-count="7"
          @current-change="currentChange"
          @size-change="sizeChange"
        ></el-pagination>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import request from '@/http/request.js'
import {formateMoney} from '@/utils'
export default {
  components: {
  },
  data() {
    return {
      loading: false,
      typeList: [],
      selected: '',
      pageSize: 15,
      pageNum: 1,
      columns: [],
      tableData: [],
      leftCols: [],
      middleCols: [],
      rightCols: [
        {name: '价格时间', field: 'timeStr'},
        {name: 'MIC', field: 'ricCode'},
        {name: '操作列', field: 'operations'},
      ],
      selection: [],
      total: 0,
      bondType: '',
      bondOptions: [],
      rateTypeSelected: '',
      rateTypeOptions: [],
      rateTarget: '',
      rateTargetOptions: [],
      rankAgency: [],
      rankAgencyOptions: [],
      focusedCol: ''
    }
  },
  props: {
    tableHeight: {
      type: Number,
      default: () => 0
    },
    dataSet: {
      type: String,
      default: () => ''
    },
    priceDate: {
      type: String,
      default: () => ''
    },
    searchWord: {
      type: String,
      default: () => ''
    },
    bondTypeOptions: {
      type: Array,
      default: () => []
    },
    rateType: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    bondTypeOptions: {
      immediate: true,
      handler(newVal, oldVal) {
        if (newVal && newVal.length > 0) {
          this.bondOptions = newVal.filter(i => i.value !== 'RevalResult')
          this.bondType = this.bondOptions.length > 0 ? this.bondOptions[0].value : ''
        }
      }
    },
    rateType: {
      immediate: true,
      handler(newVal, oldVal) {
        if (newVal && newVal.length > 0) this.rateTypeOptions = newVal
      }
    },
  },
  mounted() {
    this.queryTypeList()
  },
  methods: {
    init() {
    },
    query() {
      if (this.selected !== 'RATING') {
        this.queryTableData()
      } else {
        this.queryRatingData()
      }
    },
    queryTypeList() {
      request({
        url: 'mds/baseSds/queryDataType.action',
        method: 'post',
        data: {}
      }).then(res => {
        if (res.success) {
          this.typeList = res.data.result.datals
          this.selected = this.typeList.length > 0 ? this.typeList[0].value : ''
        } else {
          this.$message({
            message: res.message, type: 'error',
          })
        }
        this.handleClick(this.selected)
        this.queryTableData()
      }).catch(e => {
        console.log(e);
      })
    },
    handleClick(val) {
      console.log(val);
      this.selected = val
      if (val !== 'RATING') {
        this.leftCols = this.setLeftCols(val)
        this.middleCols = this.setMiddleCols(val)
        this.columns = this.leftCols.concat(this.middleCols).concat(this.rightCols)
        // console.log(this.columns);
        this.queryTableData()
      } else {
        this.queryRankAgencyData()
      }
    },
    // 指标为评级时单独请求数据
    queryRatingData() {
      const params = {
        // 'queryParam.bondSavePriceType': "DirtyPriceOfDay",
        // 'queryParam.checkDate': '',
        // 'queryParam.code': "HKD_FX_OFFSHORE",
        'queryParam.dataSet': this.dataSet,
        'queryParam.dataType': this.selected,
        'queryParam.pageLimit': this.pageSize,
        'queryParam.pageStart': this.pageNum,
        'queryParam.priceDate': this.priceDate.replace(/-/g, ''),
        // 'queryParam.pvDate': '',
        // 'queryParam.queryDate': '',
        'queryParam.ratingAgencyCodes': this.rankAgency.toString(),
        // 'queryParam.ricCode': '',
        // 'queryParam.siteCode': '',
        'queryParam.targetCode': this.rateTarget,
        'queryParam.targetType': this.rateTypeSelected,
        'queryParam.term': 'C',
        // 'queryParam.timepoint': '',
      }
      this.loading = true
      this.tableData = []
      request({
        url: 'mds/rating/ratingQuery.action',
        method: 'post',
        data: params
      }).then(res => {
        if (res.success) {
          this.tableData = res.data.result.data
          this.total = res.data.result.data.length
          this.columns = res.data.result.column
          this.columns.splice(1, 0, {field: 'targetTypeName', name: '评级类型'})
          this.tableData.forEach(x => x.canEdit = false)
        } else {
          this.$message({
            message: res.message, type: 'error',
          })
        }
      }).catch(e => {
        console.log(e);
      }).finally(() => this.loading = false)
    },
    queryTableData() {
      const params = {
        'queryParam.bondSavePriceType': this.bondType,
        'queryParam.checkDate': '',
        'queryParam.code': '',
        'queryParam.dataSet': this.dataSet,
        'queryParam.dataType': this.selected,
        'queryParam.pageLimit': this.pageSize,
        'queryParam.pageStart': this.pageNum,
        'queryParam.priceDate': this.priceDate.replace(/-/g, ''),
        'queryParam.pvDate': '',
        'queryParam.queryDate': '',
        'queryParam.ratingAgencyCode': ['4827'],
        'queryParam.ricCode': this.searchWord,
        'queryParam.siteCode': '',
        'queryParam.targetCode': '',
        'queryParam.targetType': '',
        'queryParam.term': 'C',
        'queryParam.timepoint': '',
      }
      this.tableData = []
      this.loading = true
      request({
        url: 'mds/hisprice/client/mds/queryHisMarketData.action',
        method: 'post',
        data: params
      }).then(res => {
        if (res.success) {
          this.tableData = JSON.parse(JSON.stringify(res.data.result.datals))
          this.total = res.data.result.total
          this.tableData.forEach(x => {
            if (x.val) {
              const valJson = JSON.parse(x.val)
              for (const key in valJson) {
                this.$set(x, key, valJson[key])
                this.$set(x, 'rawData', valJson[key])
              }
            }
            this.$set(x, 'canEdit', false)
          })
        } else {
          this.$message({
            message: res.message, type: 'error',
          })
        }
      }).catch(e => {
        console.log(e);
      }).finally(() => this.loading = false)
    },
    // 返回列表字段
    setLeftCols(val) {
      switch (val) {
        case 'SPOT':
          return [
            {name: '货币对', field: 'underlying'},
          ]
        case 'NDF':
          return [
            {name: '货币对', field: 'underlying'},
            {name: '期限', field: 'tenor'},
          ]
        case 'RATES' || 'SPREAD' || 'IR':
          return [
            {name: '货币', field: 'underlying'},
            {name: '期限', field: 'tenor'},
            {name: '标识', field: 'symbol'},
          ]
        case 'BOND':
          return [
            {name: '债券', field: 'underlying'},
          ]
        case 'CONTRACT':
          return [
            {name: '合约', field: 'underlying'},
          ]
        case 'FUND':
          return [
            {name: '基金', field: 'underlying'},
          ]
        case 'FINANCIAL':
          return [
            {name: '理财', field: 'underlying'},
          ]
        default:
          return [
            {name: '标的', field: 'underlying'},
          ]
      }
    },
    setMiddleCols(val) {
      const item = this.typeList.filter(e => e.value === val)
      let domain = item[0].domain?.column.split(',').filter(x => x) || []
      let cols = domain.map(x => {
        let arr = x.split('|')
        return {
          name: arr[1], field: arr[0], isEdit: true
        }
      })
      return cols
    },
    // 分页跳转
    currentChange(val) {
      this.pageNum = val
      if (this.selected !== 'RATING') {
        this.queryTableData()
      } else {
        this.queryRatingData()
      }
    },
    // 页数改变
    sizeChange(val) {
      this.pageSize = val
      if (this.selected !== 'RATING') {
        this.queryTableData()
      } else {
        this.queryRatingData()
      }
    },
    setDisabled(col) {
      if (this.selected !== 'BOND') {
        return false
      } else {
        if (this.bondType === 'DirtyPriceOfDay') {
          return col !== 'DirtyPriceOfDay'
        } else if (this.bondType === 'CleanPriceOfDay') {
          return col !== 'CleanPriceOfDay'
        } else if (this.bondType === 'Yield') {
          return col !== 'Duration'
        } else {
          return false
        }
      }
    },
    // 评级目标事件
    async rateTypeChange(val) {
      this.rateTarget = ''
      switch (val) {
        case 'C':
          this.rateTargetOptions = await this.queryRateTargetOptions('mds/sdscounterparty/findAllCptysi18n.action', 'cpty')
          break;
        case 'I':
          this.rateTargetOptions = await this.queryRateTargetOptions('mds/sdscounterparty/findAllIssuerCptysi18n.action', 'cpty')
          break;
        case 'B':
          this.rateTargetOptions = await this.queryRateTargetOptions('mds/sdsbonds/findAllbonds.action', 'bonds')
          break;
        case 'O':
          this.rateTargetOptions = await this.queryRateTargetOptions('mds/sdsthirdparty/findAllCountries.action', 'country')
          break;
        case 'G':
          this.rateTargetOptions = await this.queryRateTargetOptions('mds/sdscounterparty/findAllGuarantees.action', 'guarantee')
          break;
        default:
          this.rateTargetOptions = []
          return
      }
    },
    async queryRateTargetOptions(url, key) {
      const {data: res} = await request({url: url, method: 'post'})
      return res[key] || []
    },
    // 查评级机构数据
    queryRankAgencyData() {
      request({
        url: 'mds/sdsrating/findRatingAgenciesByContainsTermRating.action',
        method: 'post'
      }).then(res => {
        if (res.success) {
          this.rankAgencyOptions = res.data.ratingAgency
          this.rankAgency.push(res.data.ratingAgency[0].id)
        }
        this.queryRatingData()
      }).catch(e => {
        console.log(e);
        
      })
    },
    filterMethod(val) {
      this.rateTargetOptions = this.rateTargetOptions.filter(item => item.localName.indexOf(val) > -1).slice(0, 100);
    },
    tableSelect(selection) {
      this.selection = selection
    },
    saveInBatch() {
      this.save(this.selection)
    },
    // 将行索引加入到row中返回
    tableRowClassName({row, rowIndex}) {
      row.index = rowIndex
    },
    cellDblclick(row, column) {
      // console.log(row, column);
    },
    focus(key) {
      this.focusedCol = key
    },
    inputBlur(row) {
      // this.$set(this.tableData[row.index], 'canEdit', false)
    },
    edit(row) {
      const index = row.index
      this.$set(this.tableData[index], 'canEdit', true)
      this.$nextTick(() => {
        const input = this.$refs['input' + index][0]
        if (input) input.focus()
      })
    },
    save(row) {
      let data = Array.isArray(row) ? row : [row]
      data.forEach(item => {
        let val = JSON.parse(item['val'])
        for (const key in val) {
          if (val.hasOwnProperty(key)) {
            val[key] = item[key]
          }
        }
        item.val = JSON.stringify(val)
      })
      let param = {
        'queryParam.data':data,
        'queryParam.dataSet': this.dataSet,
        'queryParam.dataType': this.selected
      }
      request({
        url: 'mds/marketData/save.action',
        method: 'post',
        data: param
      }).then(res => {
        data.forEach(i => { this.$set(this.tableData[i.index], 'canEdit', false)})
        if (res.success) {
          this.$message({message: '保存成功', type: 'success',})
          this.query()
        } else {
          this.$message({message: res.message, type: 'error',})
        }
      }).catch(e => {
        console.log(e);
      })
    },
    cancel(row, col) {
      this.$set(this.tableData[row.index], this.focusedCol, row.rawData)
      this.$set(this.tableData[row.index], 'canEdit', false)
    }
  }
}
</script>
<style lang="scss" scoped>
.market-data{
  height: 100%;
  color:var(--table-text-color);
  ul {
    height: 100%;
    padding-left: 0px;
    margin-top: 0px;
    font-size: var(--font-size-mini);
    background-color:var(--bg-color-2);
    li {
      padding: 8px 0 8px 16px;
      &:hover {
        background-color:var(--white-7);
        cursor: pointer;
        color: var(--blue-7);
      }
    }
  }
  .selected {
    background-color:var(--white-7);
    color: var(--blue-7);
  }
  .table-sty {
    // margin-top: 10px;
  }
  .left {
     margin-top: 10px;
  }
  .right {
    // padding: 0 5px 0px 10px;
    margin-top: 10px;
    padding-left: 10px;
  }
  .title {
    // margin-top: 10px;
    background-color:var(--bg-color-2);
    font-size: var(--font-size-mini);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 8px;
    .mg-r-5 {
      margin-right: 5px;
    }
    .mg-r-10 {
      margin-right: 10px;
    }
  }
  .no-border-top {
    margin-top: 0px;
    padding: 16px 16px 15px 0;
    text-align: right;
  }
  .mg-r-5 {
    margin-right: 5px;
  }
}
</style>