<!-- 购卡订单 -->
<template>
  <div class="silent-expire-alarm">
    <!-- 搜索条件区 -->
    <div class="search-section">
      <Search />
    </div>
    <div class="audit-btn" v-if="userType == 2">
      <a-button @click="showAudit = true" type="text">
        <template #icon>
          <icon-plus-circle />
        </template>
        <template #default>{{ $t('order.CardPurchase') }}</template>
      </a-button>
    </div>
    <!-- 数据表格 -->
    <a-table :data="tableData" :pagination="pageData" :columns="columns" @page-change="evChangePage"
      :scroll="{ x: 'auto' }">
      <template #image="{ record }">
        <a-image width="60" height="60" :src="record.contractImg" :preview-props="{
          actionsLayout: ['rotateRight', 'zoomIn', 'zoomOut'],
        }" style="cursor: pointer;">
        </a-image>
      </template>
      <template #id="{ record }">
        <div class="line_heis" @click="openDetail(record)">{{ record.id }}</div>
      </template>
      <template #statusType="{ record }">
        <a-tag color="#ff7d00" v-if="record.moderationStatus == 1">{{$t('order.TobeReviewed')}}</a-tag>
        <a-tag color="#00b42a" v-if="record.moderationStatus == 2">{{ $t('order.PassTheExamination') }}</a-tag>
        <a-tag color="#f53f3f" v-if="record.moderationStatus == 3">{{$t('order.rejected')}}</a-tag>
      </template>
      <template #LogisticsStatus="{ record }">
        <a-tag color="#168cff" v-if="record.tmsStatus == 1">{{$t('order.unshipped')}}</a-tag>
        <a-tag color="#00b42a" v-if="record.tmsStatus == 2">{{$t('order.shipped')}}</a-tag>
      </template>
      <template #operate="{ record }">
        <div class="setting">
          <div v-if="userType == 1">
            <a-button type="text" v-if="record.moderationStatus == 1 && record.status == 1"
              @click="statusOrder(record)">{{$t('order.examine')}}</a-button>
            <a-button @click="uploadModal(record)" type="text">{{ record.contractImg == '' ? $t('order.UploadContract') : $t('order.ViewTheContract')
              }}</a-button>
          </div>
          <div v-if="userType == 2">
            <a-button type="text" @click="adminCancel(record)"
              v-if="record.moderationStatus == 2 && userType !== 1">{{ $t('order.unsubscribe') }}</a-button>
          </div>
          <a-button @click="openPriceing(record)" type="text"
            v-if="record.moderationStatus == 2 && userType == 1 ">{{ $t('order.UploadAmount') }}</a-button>
          <!-- <a-button @click="openDetail(record)" type="text" v-if="userType !== 1">套餐</a-button>
          <a-button @click="openDetail(record)" type="text" v-if="userType !== 1">资费</a-button> -->
          <a-button @click="openEndDate(record)" type="text" v-if="userType==1 && record.moderationStatus == 2">{{ $t('order.ChangeValidity') }}</a-button>
          <a-button @click="openDetail(record)" type="text">{{ $t('order.view') }}</a-button>

        </div>
      </template>
    </a-table>


    <a-modal v-model:visible="uploadContract" width="600px" :title="$t('order.UploadContract')"
      @cancel="closeModal(uploadContract, formContract)" @ok="handleBeforeOk" :okText="$t('form.Confirm')" :cancelText="$t('form.Cancel')">
      <a-form :model="formContract" auto-label-width>
        <a-form-item field="customerName" :label="$t('lotCard.userName')">
          <div class="audit-txt" style="color:#418035;">{{ FormDataList.userName }}</div>
        </a-form-item>
        <a-form-item field="orderNumber" :label="$t('order.OrderNum')">
          <div class="audit-txt">{{ FormDataList.id }}</div>
        </a-form-item>
        <a-form-item field="contractImg" :label="$t('order.SalesContract')">
          <Upload v-model:model-value="formContract.contractImg" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:visible="showPrning" :title="$t('order.UploadAmount')" @cancel="closeModal(showPrning, formPreing)" @ok="handelPriceing"
    :okText="$t('form.Confirm')" :cancelText="$t('form.Cancel')">
      <a-form :model="formPreing" auto-label-width>
        <a-form-item :label="$t('order.PurchaseAmount')">
          <a-input v-model="formPreing.amount" :placeholder="$t('form.datapoolForm.pleaseSelect')+$t('order.PurchaseAmount')" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:visible="showEndDate" :title="$t('order.ChangeValidity')" @cancel="closeModal(showEndDate, formEndDate)"
      @ok="handelEndDate" :okText="$t('form.Confirm')" :cancelText="$t('form.Cancel')">
      <a-form :model="formEndDate" auto-label-width>
        <a-form-item :label="$t('lotCard.validity')">
          <a-date-picker v-model="formEndDate.endDate" style="width: 100%;" />
        </a-form-item>
      </a-form>
    </a-modal>

    <Card v-model:modelValue="showAudit" @submit="intData()" />
    <Status v-model:modelValue="showStatus" @submit="intData()" :FormDataList="FormDataList" />
    <Detaile v-model:modelValue="showDetail" @submit="intData()" :FormDataList="FormDataList" />
    <returnCard v-model:modelValue="showReturn" :ReturnData="ReturnData" :id="id" @submit="intData()"></returnCard>
  </div>
</template>

<script setup>
import { ref, onMounted, toRefs } from 'vue';
import { Message } from '@arco-design/web-vue';
import { purchaseOrderList } from '@/api/path/purchase';
import {tariiffManageDate} from '@/api/path/tariffManagement.api'
import { UploadOrderCardContract, TariffOrderCard, SettingPricing } from '@/api/path/order'
import { Getdictionary } from '@/mixins/index.js'
import Upload from "@/components/upload/index.vue";
import Card from './Card.vue'
import Status from './status.vue'
import Detaile from './detaile.vue'
import Search from '@/components/Search/index.vue'
import returnCard from './returnCard.vue'
import {useI18n} from 'vue-i18n'
const {t} = useI18n();
// 数据层
const state = ref({
  userName: localStorage.getItem('user_login_information')?.username,
  userType: JSON.parse(localStorage.getItem('user_login_information'))?.userType, // 1平台 2用户
  tableData: [],
  currentIndex: null,
  FormDataList: {},
  pageData: {
    total: 0,
    size: 10,
    current: 1,
  },
  showAudit: false,
  showStatus: false,
  formContract: {
    id: null,
    contractImg: []
  }, // 文件上传列表
  showDetail: false,
  uploadContract: false,
  showReturn: false,
  ReturnData: [],
  id: null,
  showPrning: false,
  formPreing: {
    id: '',
    amount: ''
  },
  showEndDate: false,
  formEndDate: {
    id: '',
    endDate: ''
  }
});

const {
  userType,
  tableData,
  FormDataList,
  pageData,
  showAudit,
  showStatus,
  formContract,
  showDetail,
  uploadContract,
  showReturn,
  ReturnData,
  id,
  showPrning,
  formPreing,
  showEndDate,
  formEndDate
} = toRefs(state.value);

const columns = [
  { title: t('order.SerialNumber'), dataIndex: 'index', align: 'center', ellipsis: true },
  { title: t('order.OrderNum'), slotName: 'id', align: 'center', ellipsis: true },
  { title: t('order.AuditStatus'), slotName: 'statusType', align: 'center', ellipsis: true },
  { title: t('order.LogisticsStatus'), slotName: 'LogisticsStatus', align: 'center', ellipsis: true },
  { title: t('lotCard.userName'), dataIndex: 'userName', align: 'center', ellipsis: true },
  { title: t('order.NumberCardsPurchased'), dataIndex: 'quantity', align: 'center', ellipsis: true },
  { title: t('order.SilentPeriod')+(t('lotCard.month')), dataIndex: 'periodOfSilence', align: 'center', ellipsis: true },
  { title: t('order.CardType'), dataIndex: 'cardType', align: 'center', ellipsis: true },
  { title: t('order.CarrierName'), dataIndex: 'sourceName', align: 'center', ellipsis: true },
  { title: t('order.tariff'), dataIndex: 'trafficName', align: 'center', ellipsis: true },
  { title: t('order.PurchaseAmount'), dataIndex: 'amount', align: 'center', ellipsis: true },
  { title: t('order.ContractPhoto'), slotName: 'image', align: 'center', ellipsis: true },
  { title: t('order.OrderTime'), dataIndex: 'createdAt', align: 'center', ellipsis: true },
  { title: t('lotCard.validity'), dataIndex: 'endDate', align: 'center', ellipsis: true },
  { title: t('lotCard.Controls'), slotName: 'operate', align: 'center', ellipsis: true }
];

// 订单列表
const intData = async () => {
  const param = {
    current: pageData.value.current,
    size: pageData.value.size,
  }
  const simTypeList = await Getdictionary('cardType')
  let sourceList = await Getdictionary('source')
  purchaseOrderList(param).then(res => {
    tableData.value = (res.data.records || []).map((item, key) => {
      const sourceName = sourceList.find(val => val.value == item.source)?.label
      const cardType = simTypeList.find(val => val.value == item.simType)?.label
      return {
        ...item,
        index: key + 1,
        sourceName,
        cardType
      }
    });
    pageData.value.total = res.data.total;
  })

}
// 用户退订
const adminCancel = (data) => {
  TariffOrderCard({ id: data.trafficId }).then(res => {
    ReturnData.value = res.data || []
  })
  id.value = data.id
  showReturn.value = true
}
// 分页
const evChangePage = (page) => {
  pageData.value.current = page
  intData()
}

// 订单审核
const statusOrder = (items) => {
  FormDataList.value = items
  showStatus.value = true
}

// 上传合同
const uploadModal = (item) => {
  uploadContract.value = true;
  FormDataList.value = item
  formContract.value = {
    id: item.id,
    contractImg: item.contractImg
  }
};
// 查看订单详情
const openDetail = async (item) => {
  FormDataList.value = item
  showDetail.value = true;
}
// 上传合同
const handleBeforeOk = () => {
  new Promise((resolve, reject) => {
    formContract.value.id = FormDataList.value.id;
    UploadOrderCardContract(formContract.value).then(res => {
      resolve(res)
      Message.success(res.message)
      intData();
    }).catch(error => {
      reject(error)
    })
  })
};
// 模态框取消
const closeModal = (items, obj) => {
  items = false
  Object.keys(obj).forEach(key => {
    if (obj.key) {
      obj[key] = '';
    }
  })
}

const openPriceing = (data) => {
  showPrning.value = true;
  formPreing.value.id = data.id
}

const handelPriceing = async () => {
  if (formPreing.value.amount == '' || formPreing.value.amount == 0) {
    return Message.error(t('order.IncorrectInput'))
  }
  formPreing.value.amount = Number(formPreing.value.amount)
  let res = await SettingPricing(formPreing.value)
  if (res.code === 200) {
    Message.success(res.message)
    closeModal(showPrning.value, formPreing.value)
  }
}

const openEndDate = (data) => {
  formEndDate.value.id = data.trafficId
  formEndDate.value.endDate = data.endDate
  showEndDate.value = true;
}

const handelEndDate = async()=>{
  let res = await tariiffManageDate(formEndDate.value)
  if(res.code === 200) {
    Message.success(res.message)
    closeModal(showEndDate.value, formEndDate.value)
    intData();
  }
}

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

<style scoped lang="less">
.silent-expire-alarm {
  padding: 20px !important;
  // background: #fcf;
}

.setting {
  display: flex;
  align-items: center;
  justify-content: center;
}

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

.arco-table-th {
  white-space: nowrap;
}

.audit-txt {
  display: flex;
  flex-wrap: wrap;

  .audit-tag {
    width: 180px;
    color: #b2b2b2;
    margin-right: 20px;

    span {
      color: #000;
      margin-left: 20px;
    }
  }
}

.audit-btn {
  margin-bottom: 10px;
}



.detail-table {
  margin-top: 20px;
}

.line_heis {
  color: #FF8839;
  cursor: pointer;
  display: inline-block;
}

.line_heis:hover {
  color: #168cff;
}
</style>
