<template>
  <!-- 卡清单管理 -->
  <div class="container">
    <div class="head-title">
      <span>{{ route.meta.title }} </span>
      <span class="head-title-right">
        <a-popconfirm :content="$t('form.ImportConfirm')" :ok-text="$t('form.Confirm')" :cancel-text="$t('form.Cancel')"
          @ok="handleImport()">
          <!-- <a-button class="m-r-10" type="primary"> {{ $t('form.Import') }}</a-button> -->
        </a-popconfirm>
      </span>

    </div>
    <!-- 搜索条件区 -->
    <div class="search-section">
      <a-form :model="searchForm" ref="formRef" layout="inline">
        <a-form-item field="iccid" :label="$t('lotCard.iccid')">
          <a-input v-model="searchForm.iccid" :placeholder="$t('lotCard.please') + $t('lotCard.iccid')" allow-clear />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">{{ $t('form.Search') }}</a-button>
            <a-button @click="resetSearch">{{ $t('form.Reset') }}</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <a-table row-key="iccid" :data="dataSource" :columns="columns" :pagination="pagination"
      :row-selection="rowSelection" v-model:selectedKeys="selectedKeys" :scroll="{ x: 'auto' }" :expandable="expandable"
      @page-change="evChangePage">
      <template #id="{ record }">
        <!-- 查看流量消耗 -->
        <a class="a-link" href="javascript:;" style="margin-right: 1rem" @click="handletrafficUseDialog(record)">{{
          $t('lotCard.trafficUse') }}</a>
      </template>

    </a-table>
    <!-- 查看流量消耗 -->
    <trafficUseDialog ref="trafficUseDialogRef" />
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, h } from "vue";
import { useRoute } from "vue-router";
import { columns } from "./config";
import { Message, Notification } from '@arco-design/web-vue'
import { cardInfoList, cardInfoImport, orderList, orderFlowData } from "@/api/path/lotCard.api"
import trafficUseDialog from "./trafficUseDialog.vue";
import { enum_dict } from "@/hooks/enum";
import list from "./list.vue";

const { proxy } = getCurrentInstance()
const formRef = ref()
const searchForm = ref({
  "iccid": "",
});

const statusList = ref([]);
const sourceList = ref([]);
const serviceList = ref([]);
const dataSource = ref([]);
const route = useRoute();
const pagination = ref({
  total: 0,
  pageSize: 10,
  current: 1,
})

const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
});
const selectedKeys = ref([])

const trafficUseDialogRef = ref()


const intData = async () => {
  const param = {
    current: pagination.value.current,
    size: pagination.value.pageSize,
    ...searchForm.value,
  }
  const { data } = await cardInfoList(param)

  dataSource.value = (data.records || []).map((item) => {
    // 卡下级信息
    let orderArr = []
    orderList({ current: 1, size: 999, ICCID: item.iccid }).then(res => {

      res.data.records?.forEach(async (orderItem, index) => {
        // const dictList = JSON.parse(window.localStorage.getItem('dictList')) ?? []
        // const orderType = dictList.filter((item) => item.type_key == enum_dict.SOURCE)
        const params = {
          iccid: orderItem.ICCID,
          childOrderId: orderItem.id,
          subscriptionKey: orderItem.subscription_key,
        }

        let trafficList = []

        // if (item.iccid == '89852342022040149139' && index < 5 || !(item.iccid == '89852342022040149139')) {
        //   const { data } = await orderFlowData(params)
        //   trafficList = data.historyData || []
        //   orderArr.push({
        //     ...orderItem,
        //     trafficList
        //   })
        // }
        orderArr.push({
          ...orderItem,
        })
      })
    })

    // 处理卡列表信息
    const sourceName = sourceList.value.find(sourceItem => sourceItem.value == item.source)?.label || ''
    const serviceName = serviceList.value.find(serviceItem => serviceItem.value == item.service_usage_mode)?.label || ''
    const statusName = statusList.value.find(statusItem => statusItem.value == item.status)?.label || ''
    return {
      ...item,
      sourceName,
      serviceName,
      statusName,
      orderArr
    }

  })
  pagination.value.total = data.total
}


// const { data: orderData } = await orderList({ current: 1, size: 999, ICCID: ICCID.value })
//     orderData.records?.forEach(async (orderItem) => {

//         const params = {
//             // iccid: orderItem.ICCID,
//             iccid: '89852342022040149139',
//             childOrderId: orderItem.id,
//             subscriptionKey: "1824754463183432097",
//         }

//         let trafficList = []
//         const { data } = await orderFlowData(params)
//         trafficList = data.historyData || []

//         dataSource.value.push({
//             ...orderItem,
//             trafficList
//         })
//     })


const expandable = {
  expandedRowRender: (record) => {
    if (record.orderArr && Array.isArray(record.orderArr) && record.orderArr.length > 0) {
      return h('div', {}, [
        h(list, { 'data': record.orderArr })
      ]);
    }
    return h('div', {}, '暂无数据')


  },
};

const handleImport = async () => {
  if (!searchForm.value.iccid) {
    Message.warning({
      content: '请先输入ICCID,可输入多个以逗号分隔,然后再点击导入！',
      duration: 2000,
    })
    return
  }
  const iccids = searchForm.value.iccid.split(',')
  const iccidList = iccids.map(item => {
    return {
      iccid: item
    }
  })
  const { code, data } = await cardInfoImport({ iccidList })
  if (code == 200) {
    Message.success({
      content: data,
      duration: 2000,
    })
    intData()
  }

};

const handletrafficUseDialog = (data) => {
  console.log(data.iccid, "data.iccid")
  trafficUseDialogRef.value.open(data.iccid)
}


const evChangePage = (page) => {
  pagination.value.current = page
  intData()
}
const handleSearch = () => {
  formRef.value.validate((errors) => {
    if (!errors) {
      intData()
    }
  });
}


// 获取字典
const handleDictValue = () => {
  const dictList = JSON.parse(window.localStorage.getItem('dictList')) ?? []
  sourceList.value = dictList.filter((item) => item.type_key == enum_dict.SOURCE)
  statusList.value = dictList.filter((item) => item.type_key == enum_dict.MAIN_CARD_STATUS)
  serviceList.value = dictList.filter((item) => item.type_key == enum_dict.ACTIVATION_PACKAGE)
}

const resetSearch = () => {
  proxy.$refs.formRef.resetFields()
  intData()
}

onMounted(() => {
  handleDictValue()
  intData()
})
</script>

<style scoped lang="less">
.head-title-right {
  .m-r-10 {
    margin-right: 10px;
  }

}

.search-section {
  margin-top: 20px;
  margin-bottom: 20px;
}

.container {
  .head-title {
    display: flex;
    justify-content: space-between;
  }

  .form-row {
    display: flex;

    .form-row-col {
      width: 25%;
      display: flex;
      align-items: center;

      .form-row-label {
        width: 120px;
        text-align: right;
      }
    }
  }
}
</style>