<template>
  <a-modal width="80%" :visible="visible" :title="$t('lotCard.CardDetails') + Card_info.iccid" :hide-cancel='true'
    :okText="$t('form.Confirm')" :cancelText="$t('form.Cancel')" @ok="handleSubmit" @cancel="visible = false" draggable>
    <!-- 卡片信息 -->
    <a-row class="grid-demo" :gutter="24">
      <a-col :span="12">
        <a-form :model="Card_info" auto-label-width label-align="left" class="toal_Form">
          <a-row :gutter="10">
            <a-col :span="12">
              <a-form-item label="ICCID">
                {{ Card_info.iccid }}
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="IMSI">
                {{ Card_info.currentImsi }}
              </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-item :label="$t('lotCard.currencyBalance')">
                {{ Card_info.moneyBalances }}
              </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-item :label="$t('lotCard.ActivationDate')">
                {{ Card_info.activeTime }}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item :label="$t('lotCard.DueDate')">
                {{ Card_info.expireTime }}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item :label="$t('lotCard.validity')">
                {{ Card_info.expireDay }}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item :label="$t('lotCard.supplier')">
                {{ Card_info.source }}
              </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-item :label="$t('lotCard.UsedpackFlow')">
                {{ Card_info.source }}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item :label="$t('lotCard.FuelPackFlowAvailable')">
                {{ Card_info.source }}
              </a-form-item>
            </a-col> -->
          </a-row>
        </a-form>
        <p>{{ $t('lotCard.CurrentPackageInformation') }}</p>
        <a-form :model="dataPackage" auto-label-width label-align="left">
          <a-row :gutter="10" wrap>
            <a-col :span="12">
              <a-form-item label="资费名称">
                {{ Card_info?.tariffName }}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item :label="$t('lotCard.PackageStatus')">
                {{
                  dataPackage?.status
                }}
              </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-item :label="$t('lotCard.validity')">
                {{ dataPackage?.validDays }} {{ $t('lotCard.month') }}
              </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-item :label="$t('lotCard.WhetherToGive')">
                {{ dataPackage?.present == 0 ? $t('lotCard.No') : $t('lotCard.Yes') }}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item :label="$t('lotCard.PackageActivationDate')">
                {{ dataPackage?.activeTime }}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="流量包过期日期">
                {{ dataPackage?.expiryTime }}
              </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-item :label="$t('lotCard.PackageValidDays')">
                {{ dataPackage?.validDays }}
              </a-form-item>
            </a-col> -->
            <!-- <div class="line"></div>
            <a-col :span="12">
              <a-form-item :label="$t('lotCard.PlaAvailableData')">
                {{ dataPackage?.dataTotal == -1 ? $t('lotCard.UnlimitedFlow') : dataPackage?.dataTotal }}MB
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item :label="$t('lotCard.PlanUsedData')">
                {{ dataPackage?.dataUsage }}MB
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item :label="$t('lotCard.PackageUseTrafficToday')">
                {{ dataPackage?.dataToday }}MB
              </a-form-item>
            </a-col> -->

          </a-row>
        </a-form>
      </a-col>
      <a-col :span="12">
        <a-tabs>
          <a-tab-pane key="1" :title="$t('lotCard.MonthlyConsumption')">
            <div class="chart" style="width:100%" id="chartContainer" />
          </a-tab-pane>
          <a-tab-pane key="2" :title="$t('lotCard.CardPackageInformation')">
            <a-table :columns="columnsCard" :data="dataCard" :scroll="{ x: 'auto' }" :pagination="false">
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="3" :title="$t('lotCard.EarlyWarningInformation')">
            Content of Tab Panel 3
          </a-tab-pane>
          <a-tab-pane key="4" :title="$t('lotCard.RechargeRecord')">
            <a-table :columns="columnsTopup" :data="dataTopup" :scroll="{ x: 'auto' }" :pagination="pagination"
              @page-change="evChangePageCardPuy">
              <template #puyStatus="{ record }">
                <a-tag :color="record.payStatus == 'SUCCESS' ? '#00b42a' : ''">{{ record.puyStatus }}</a-tag>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="5" :title="$t('lotCard.UsageAmount')">
            <a-table :columns="columnsAmount" :data="dataAmount" :scroll="{ x: 'auto' }"
              @page-change="handelChangePageAounmt" :pagination="pageDataAounmt" />
          </a-tab-pane>
          <a-tab-pane key="6" :title="$t('lotCard.OperationRecord')">
            <a-table :columns="columnsOperation" :data="dataOperation" :scroll="{ x: 'auto' }"
              @page-change="evChangePage" :pagination="pageData" />
          </a-tab-pane>
        </a-tabs>
      </a-col>
    </a-row>

    <template #footer>
      <div class="footer_button">
        <!-- <a-button type="primary" status="warning">同步卡信息 V</a-button> -->
        <a-button type="primary" status="warning" @click="SIMCardService(0)">{{ $t('lotCard.SuspensionService')
          }}</a-button>
        <a-button type="primary" status="warning" @click="SIMCardService(1)">{{ $t('lotCard.RestoreService')
          }}</a-button>
        <!-- <a-button type="primary" status="warning" @click="SIMCardService(2)">{{ $t('lotCard.CloseCard') }}</a-button> -->
      </div>
    </template>
  </a-modal>
</template>
<script setup>
import { onMounted, ref, h, toRefs } from "vue";
import { getDataCDR, PauseSIMService, RecoverSIMService, OperationRecord, OffSIMCard, getOrderCard, getFlowData } from '@/api/path/lotCard.api'
import { Getdictionary, filterDict } from '@/mixins/index'
import { Message, Modal } from '@arco-design/web-vue'
// 图表插件
import * as echarts from "echarts";
import { useI18n } from 'vue-i18n'
import { columnsCard, columnsTopup, columnsAmount, columnsOperation } from './config'
const { t } = useI18n();
const userType = ref(JSON.parse(localStorage.getItem('user_login_information'))?.userType) // 1平台 2用户
const emit = defineEmits(['submit']);
const state = ref({
  visible: false,
  Card_info: {},
  dataPackage: null,
  dataSource: [],
  pageData: {
    total: 0,
    size: 10,
    current: 1,
  },
  pageDataAounmt: {
    total: 0,
    size: 10,
    current: 1,
    source: '',
    iccid: ''
  },
  pagination: {
    total: 0,
    size: 10,
    current: 1,
  },
  option: {
    xAxis: {
      type: 'category',
      data: [t('lotCard.Jan'), t('lotCard.February'), t('lotCard.March'), t('lotCard.April'), t('lotCard.May'), t('lotCard.June'), t('lotCard.July'), t('lotCard.August'), t('lotCard.September'), t('lotCard.October'), t('lotCard.November'), t('lotCard.December')]
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        type: 'bar',
      }
    ],
    tooltip: {
      // 触发类型，默认数据触发，可选为：'item' | 'axis'
      trigger: 'axis',
      // 坐标轴触发，支持的坐标轴有：'x' | 'y' | 'radius' | 'angle'
      axisPointer: {
        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
      },
      // 自定义的 formatter 函数
      formatter: function (params) {
        var res = params[0].name + '使用量' + params[0].value.toFixed(2) + 'KB';
        return res
      }
    },
  },
  dataCard: [],
  dataTopup: [],
  dataAmount: [],
  dataOperation: []
})

const {visible,Card_info,dataPackage,dataSource,pageData,pageDataAounmt,pagination,option,dataCard,dataTopup,dataAmount,dataOperation} = toRefs(state.value)

const open = async (data) => {
  if (!data) {
    return
  }
  dataSource.value = []
  Card_info.value = data
  dataPackage.value = data.dataPackage[0]

  // 卡套餐信息
  dataCard.value = (data.dataPackage || []).map(val => {
    return {
      ...val,
      dataTotal: val.dataTotal == -1 ? t('lotCard.UnlimitedFlow') : val.dataTotal,
      tariffName: val.tariffName,
      dataUsage: val.dataUsage + '/MB',
      dataTotal: val.dataTotal + '/MB',
      dataToday: val.dataToday + '/MB',
    }
  })
  pageDataAounmt.value.iccid = data.iccid
  pageDataAounmt.value.source = data.source
  await getAountData()
  await optionsRecordSetting()
  intData()
  ICCIDPuyData(data.iccid)
  visible.value = true
}


const getAountData = async () => {
  let res = await getFlowData(pageDataAounmt.value)
  if (res.code == 200) {
    dataAmount.value = res.data.records || []
  }
  pageDataAounmt.value.total = res.data.total
}

const handelChangePageAounmt = (e) => {
  pageDataAounmt.value.current = e
  getAountData()
}

const ICCIDPuyData = async (id) => {
  let res = await getOrderCard({ iccid: id, ...pagination.value })
  let res1 = await Getdictionary('puyType')
  dataTopup.value = (res.data.records || []).map(val => {
    return {
      ...val,
      puyStatus: filterDict(res1, val.payStatus),
      payAmount: val.payAmount + val.currency
    }
  })

  pagination.value.total = res.data.total
}

const evChangePageCardPuy = (e) => {
  console.log(e);
  pagination.value.current = e
  ICCIDPuyData(Card_info.value.iccid)
}

// 月用量
const intData = async () => {
  // 获取当前年份
  const currentYear = new Date().getFullYear();

  // 获取今年的第一天（2025-01-01）
  const startDate = `${currentYear}-01-01`;

  // 获取今年的最后一天（2025-12-31）
  const endDateTime = `${currentYear}-12-31`;

  // 调用你的 getDataCDR 方法
  let res = await getDataCDR({
    iccid: Card_info.value.iccid,
    source: Card_info.value.source,
    startDate: startDate, // 今年的第一天
    endDate: endDateTime // 今天的日期
  });

  option.value.series[0].data = res.data.yAxis
  initChart()
}

// SIM卡操作
const SIMCardService = async (index) => {
  if (index !== 2) {
    const Inform = {
      iccid: Card_info.value.iccid, source: Card_info.value.source
    }
    // 暂停SIM卡
    let res = index == 0 ? await PauseSIMService(Inform) : (index == 1 ? await RecoverSIMService(Inform) : '')
    if (res.code === 200) {
      Message.success({
        content: res.message,
        duration: 2000,
      })
      handleSubmit()
    }
  } else {
    Modal.info({
      title: '关闭卡',
      cancelText: '关闭',
      content: () => {
        return h('div', { style: 'color:red;text-align: center;font-size:18px' }, '当前操作不可逆,请确定是否关闭当前卡!!')
      },
      onOk: async () => {
        // let res = await OffSIMCard()
      }
    });
  }
}
const handleSubmit = () => {
  emit('submit', true);
  visible.value = false
};


// 图表
const initChart = () => {
  const dom = echarts.init(document.getElementById("chartContainer"));
  dom.setOption(option.value);
  window.addEventListener("resize", () => {
    dom.resize();
  })
}

const evChangePage = (e) => {
  pageData.value.current = e
  optionsRecordSetting()
}

// 操作日志
const optionsRecordSetting = async () => {
  let res = await OperationRecord({
    current: pageData.value.current,
    size: pageData.value.size,
    iccid: Card_info.value.iccid
  })
  let res1 = await Getdictionary('source')
  dataOperation.value = res.data.records.map(res => {
    return {
      ...res,
      source: res1.filter(item => item.value == res.source)[0]?.label
    }
  })
}

defineExpose({ open })


</script>

<style scoped lang="less">
.toal_Form {
  padding-bottom: 10px;
  border-bottom: 1px solid #ccc;
}

p {
  font-size: 20px;
  color: black;
}

.line {
  margin: 15px 0;
  border-bottom: 1px solid #ccc;
  width: 100%;
}

.footer_button {
  display: flex;
  justify-content: start;

  button {
    margin-right: 15px;
  }
}

.chart {
  height: 310px;
  width: 100%;
}
</style>
