<template>
  <div class="trade_trace">
    <div
      v-for="(item, index) in datalArray"
      :key="'trace_' + index"
      class="trace_item"
    >
      <NodeLine
        :show-bottom-mark="index == datalArray.length - 1"
        :show-top-mark="index == 0"
        :point-type="index == 0 ? 'primary' : 'default'"
        :line-type="'default'"
      />
      <div class="date">{{ item.operateDateInfo }}</div>
      <div class="main_content">
        <div class="main">
          <div class="item">
            <div class="label">{{ $t('form.tradeId') }}</div>
            <div
              class="value"
              @click="copyToClipboard"
            >
              <span id="main_tradeid">{{ item?.dealId ?? item?.parentId }}</span>
              <icon-font
                name="icon-copy"
                class="icon-copy"
              />
            </div>
          </div>
          <div class="item">
            <div class="label">{{ $t('field.action') }}</div>
            <div class="value edit">
              <div class="btn">{{ item?.eventName }}</div>
            </div>
          </div>
          <div class="item">
            <div class="label">{{ $t('form.dealStatus') }}</div>
            <div class="value point">
              <span class="success">{{ item?.dealStatusName }}</span>
            </div>
          </div>
          <div class="item">
            <div class="label">{{ $t('field.product') }}</div>
            <div class="value">{{ item?.productShowName }}</div>
          </div>
          <div class="item">
            <div class="label">{{ $t('form.user') }}</div>
            <div class="value">{{ item?.userId }}</div>
          </div>
          <div class="item">
            <div class="label">{{ $t('field.history') }}</div>
            <div class="value">{{ item?.version }}</div>
          </div>
        </div>
        <div class="content_header">
          <icon-font
            name="icon-save"
            class="icon-save"
          />
          <span class="text"> {{ $t('field.content') }}</span>
        </div>
        <div class="content">
          <div
            v-for="(cItem, cIndex) in item.contentArray"
            :key="'trace_' + index + '_content_' + cIndex"
            class="item"
          >
            <div class="label">{{ cItem.label }}</div>
            <div
              :class="{
                'value': true,
                'changed': cItem.localChanged
              }"
            >{{ cItem.value }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { queryDealTrace, queryComboxData } from '@/api/dcsApi';
import NodeLine from '../NodeLine';

export default {
  name: 'TradeTrace',
  components: {
    NodeLine,
  },
  props: {
    dealId: {
      type: String || Number,
      default: '',
    },
  },
  data() {
    return {
      datalArray: null,
    };
  },
  computed: {

  },
  created() {
    this.init();
  },
  methods: {
    init() {
      if (this.dealId) {
        this.getDealTrace(this.dealId);
      }
    },
    async getDealTrace(dealId) {
      debugger;
      const data = await queryDealTrace({ 'dealId': dealId });
      if (data?.success) {
        const { datals } = data?.data.result;
        this.datalArray = await this.platDetails([], datals);
        // console.log('datalArray', this.datalArray);
      }
    },
    async platDetails(datalArray, datals) {
      for (const datal of datals) {
        const detalRes = await this.formatDetail(datal, datalArray.length > 0 ? datalArray[0] : { contentArray: [] });
        datalArray.unshift(detalRes);
        if (datal?.children) {
          await this.platDetails(datalArray, datal?.children);
        }
      }
      return datalArray;
    },
    async formatDetail(detail, lastDetail) {
      const contentArray = await this.compareArrayAddFlag(detail, lastDetail);
      return {
        ...detail,
        contentArray: contentArray,
      };
    },
    async compareArrayAddFlag(detail, lastDetail) {
      const array = lastDetail.contentArray;
      const oriArray = await this.formatContent(detail.content);
      const map = new Map([]);
      for (const index in oriArray) {
        map.set(oriArray[index].label, { index: index, value: oriArray[index].value });
      }
      for (const item of array) {
        if (map.has(item.label) && map.get(item.label).value != item.value) {
          oriArray[map.get(item.label).index]['localChanged'] = true;
        }
      }
      return oriArray;
    },
    async formatContent(data) {
      let str = await this.formatMessageParameters(data);
      // TODO 原有多语言模板逗号中英文混乱配置，对英文逗号转换成中文逗号，并排除金额情况的英文逗号
      str = str.replace(/,([^0-9])/g, '，$1');
      return str.split('，').map(item => {
        const index = item.indexOf(':');
        return {
          label: item.slice(0, index),
          value: item.slice(index + 1, item.length),
        };
      });
    },
    /**
     * 特殊格式多语言字符串处理
     *
     * （迁移自旧项目代码）
     *
     * 适用于以下情况
     * 数据源：info.deal.newTrack|@|25032400000|@|FXOPTION_EUROPEAN|@|1,000,000|@|USDCNY|@|2025-03-24|@|2025-03-26|@|2025-04-24|@|2025-03-24 10:53:15|@|test0001|@|RCS|@|25032400000
     * 多语言配置：'info.deal.newTrack': '金额:{2}，标的:{3}，交易日:{4}，起息日:{5}，到期日:{6}，发生时间:{7}，交易来源:{9}，外部流水号:{10}',
     * 转换结果：金额:1,000,000，标的:USDCNY，交易日:2025-03-24，起息日:2025-03-26，到期日:2025-04-24，发生时间:2025-03-24 10:53:15，交易来源:RCS，外部流水号:25032400000
     * @param {String} msg
     * @return {String}
     */
    async formatMessageParameters(msg) {
      if (msg == null || msg === '') {
        return '';
      }
      msg = msg.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
      var msgs = msg.split('\|@\|');
      var mess = this.$t(msgs[0]);
      for (var i = 1; i < msgs.length; i++) {
        var reg = new RegExp('[{]' + (i - 1) + '[}]', 'g');
        var message = msgs[i];
        if (message != null && message != '') {
          if (message.indexOf(';') > -1) {
            var strings = message.split(';');
            if (strings.length >= 2 && Eui.Share.get('language') == 'en') {
              message = strings[1];
            } else {
              message = strings[0];
            }
          }
        }
        mess = mess.replace(reg, message);
      }
      return mess;
    },
    /**
     * 获取数据字典
     */
    async queryComboxData() {
      const params = {
        codifierGrpCodes: 'typeOfEvent',
      };
      const res = await queryComboxData(params);
      if (res?.success) {
        const result = res.data?.result;
      }
    },
    copyToClipboard() {
      const textToCopy = document.getElementById('main_tradeid').textContent;
      navigator.clipboard.writeText(textToCopy)
        .then(() => {
          console.log('复制成功');
          this.$message.success('复制成功');
        })
        .catch(err => {
          console.error('无法复制文本: ', err);
          this.$message.error('无法复制文本');
        });
    },
  },
};
</script>
<style lang="scss" scoped>
@mixin point-detail($color) {
  color: $color;
  position: relative;
  padding-left: 8px;
  &::before {
    content: "";
    position: absolute;
    height: 4px;
    width: 4px;
    border-radius: 50%;
    left: 0px;
    top: 50%;
    transform: translateY(-50%);
    background-color: $color;
  }
}
@mixin point {
  &.point {
    .success {
      @include point-detail(var(--ancillary-color-success-1))
    }
    .warning {
      @include point-detail(var(---ancillary-color-warning-1))
    }
  }
}
.trade_trace {
  position: relative;
  box-sizing: border-box;
  .trace_item {
    position: relative;
    padding: 6px 0px 6px 32px;
  }
  .date {
   color: var(--application-color-5);
   line-height: 20px;
  }
  .main_content {
    margin-top: 13px;
    border-radius: 4px;
    border: 1px solid var(--application-color-8);
  }
  .main {
    padding: 12px;
    display: flex;
    flex-wrap: wrap;
    background: url('../../assets/trade_trace_main.png') no-repeat center/cover border-box;
    .item {
      width: 25%;
      font-size: 12px;
      display: flex;
      flex-direction: row;
      padding: 6px 0;
      .label {
        width: 80px;
        color: var(--application-color-3);
        line-height: 20px;
        vertical-align: middle;
      }
      .value {
        color: var(--application-color-2);
        line-height: 20px;
        vertical-align: middle;
        .icon-copy {
          margin-left: 4px;
          color: var(--primary-color-1);
        }
        &.edit {
          text-align: center;
          .btn {
            width: 40px;
            height: 22px;
            border-radius: 2px;
            // TODO 待替换全局变量
            color: #FF950B;
            background-color: rgb(255, 149, 11, 0.1);
          }
        }
        @include point;
      }
    }
  }
  .content_header {
    color: var(--primary-color-1);
    margin: 0 12px;
    border-top: 1px solid var(--application-color-8);
    padding-top: 12px;
    .icon-save {
      line-height: 20px;
      text-align: left;
    }
    .text {
      flex-grow: 1;
      line-height: 20px;
      text-align: left;
    }
  }
  .content {
    padding: 8px 12px 12px 12px;
    display: flex;
    flex-wrap: wrap;
    .item {
      width: 25%;
      font-size: 12px;
      display: flex;
      flex-direction: row;
      padding: 6px 0;
      .label {
        width: 80px;
        color: var(--application-color-3);
        line-height: 20px;
        vertical-align: middle;
      }
      .value {
        flex-grow: 1;
        color: var(--application-color-2);
        line-height: 20px;
        vertical-align: middle;
        position: relative;
        &.changed {
          color: var(--ancillary-color-success-1)
        }
      }
    }
  }
}
</style>
