<!-- 资费管理 -->
<template>
  <div class="container">
    <div class="head-title">
      <span>{{ route.meta.title }} </span>
      <span class="head-title-right">
                <!-- <a-button class="m-r-10" type="primary" @click="dictShowModel(1, null)">{{ $t('form.Add') }}</a-button> -->
            </span>
    </div>
    <!-- 搜索条件区 -->
    <div class="search-section">

      <a-form :model="searchForm" layout="inline">
        <!--        资费名称-->
        <a-form-item field="label" :label="$t('tariffManagement.label')">
          <a-input v-model="searchForm.label"
                   :placeholder="$t('lotCard.please') + $t('tariffManagement.label')" allow-clear/>
        </a-form-item>
        <!--        供应商-->
        <a-form-item field="label" :label="$t('tariffManagement.soundName')">
          <a-select v-model="value" :style="{width:'320px'}" :placeholder="$t('lotCard.soundName')">
            <a-option v-for=" item in sourceList" :key="item.id" :value="item.value">{{
                item.label
              }}
            </a-option>
          </a-select>
        </a-form-item>
        <!--         流量类型-->
        <a-form-item field="label" :label="$t('tariffManagement.FlowType')">
          <a-select v-model="value" :style="{width:'320px'}" :placeholder="$t('lotCard.FlowTypeName')">
            <a-option v-for=" item in trafficList" :key="item.id" :value="item.value">{{
                item.label
              }}
            </a-option>
          </a-select>
        </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>

    <div class="audit-btn">
      <a-button type="text" @click="dictShowModel(1, null)" v-if="role.getRole == 1">
        <template #icon>
          <icon-plus-circle/>
        </template>
        <template #default>{{ $t('form.Add') }}</template>
      </a-button>
    </div>
    <a-table row-key="id" :data="dataSource" :columns="role.getRole == 1 ? columns : columnsCustomer"
             :pagination="pagination" :scroll="{ x: 'auto' }" @page-change="evChangePage">
      <template #id="{ record }">
        <!-- 修改 -->
        <a class="a-link" href="javascript:;" style="margin-right: 1rem" @click="dictShowModel(2, record)">{{
            $t('form.Edit')
          }}</a>
        <!-- 删除 -->
        <a-popconfirm :content="$t('form.Delete')" :ok-text="$t('form.Confirm')"
                      :cancel-text="$t('form.Cancel')" @ok="handleDel(record.id)">
          <a class="a-link" href="javascript:;" style="margin-right: 1rem">{{
              $t('form.Delete')
            }}</a>
        </a-popconfirm>
      </template>

    </a-table>


    <!--资费 弹框 -->
    <a-modal :title="typeCurrent == 1 ? $t('form.Add') : $t('form.Edit')" v-model:visible="visible"
             @onCancel="resetForm" centered :maskClosable="false" :footer="null" width="700px">
      <a-form ref="formRef" :rules="rules" :model="formState" @submit="handleSubmit">
        <div class="formTitle">基本信息</div>
        <a-form-item :label="$t('tariffManagement.source')" field="source">
          <a-select v-model="formState.source">
            <a-option v-for=" item in sourceList" :key="item.id" :value="item.value">{{
                item.label
              }}
            </a-option>
          </a-select>
        </a-form-item>
        <template v-if="formState.source">
          <a-form-item :label="$t('tariffManagement.simDataPlanId')" field="simDataPlanId">
            <a-select v-model="formState.simDataPlanId">
              <a-option v-for=" item in planList" :key="item.superior_id" :value="item.id"> 流量包{{
                  item.id
                }}
              </a-option>
            </a-select>
          </a-form-item>
        </template>
        <a-form-item :label="$t('tariffManagement.label')" field="label">
          <a-input v-model="formState.label"/>
        </a-form-item>
        <a-form-item :label="$t('tariffManagement.userId')" field="userId">
          <a-select v-model="formState.userId">
            <a-option v-for=" item in userIdList" :key="item.id" :value="item.id">{{
                item.name
              }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="$t('tariffManagement.billingMethod')" field="billingMethod">
          <a-select v-model="formState.billingMethod">
            <a-option v-for=" item in methodList" :key="item.id" :value="item.value">{{
                item.label
              }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="$t('tariffManagement.currency')" field="currency">
          <a-select v-model="formState.currency">
            <a-option v-for=" item in currency" :key="item.id" :value="item.value">{{
                item.label
              }}
            </a-option>
          </a-select>
        </a-form-item>
        <div class="formTitle">计费信息</div>
        <a-form-item field="billingCycle" :label="$t('tariffManagement.billingCycle')" required>
          <a-radio-group v-model="formState.billingCycle">
            <a-radio value="1">按天</a-radio>
            <a-radio value="2">按月</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="" :label="$t('tariffManagement.pricing')" required>
          <a-input v-model="formState.pricing" v-if="formState.billingMethod==2">
            <template #append>
              {{ formState.currency === '0' ? '元' : '美金' }}
            </template>
          </a-input>
          <a-input v-model="formState.trafficBilling" v-if="formState.billingMethod==1"></a-input>
          <a-select v-model="formState.trafficBillingType" style="width: 80px; margin:0 8px;"
                    v-if="formState.billingMethod==1">
            <a-option value="KB">KB</a-option>
            <a-option value="MB">MB</a-option>
            <a-option value="GB">GB</a-option>
          </a-select>
          <a-input v-model="formState.trafficBillingAmount" v-if="formState.billingMethod==1">
            <template #append>
              {{ formState.currency === '0' ? '元' : '美金' }}
            </template>
          </a-input>
        </a-form-item>
        <a-form-item field="settlementCycle" :label="$t('tariffManagement.cycleBuy')">
          <a-input v-model="formState.settlementCycleMap.starTime">
            <template #prepend>
              最短
            </template>
            <template #append>
              个月，最长
            </template>
          </a-input>
          <a-input v-model="formState.settlementCycleMap.endTime" style="width: 50%;">
            <template #append>
              个月
            </template>
          </a-input>
        </a-form-item>
        <a-form-item :label="$t('tariffManagement.MRCName')" field="mrcAmount">
          <a-input v-model="formState.mrcAmount">
            <template #append>
              {{ formState.currency === '0' ? '元' : '美金' }}
            </template>
          </a-input>
        </a-form-item>
        <a-form-item :label="$t('tariffManagement.networkName')" field="networkAccessFee">
          <a-input v-model="formState.networkAccessFee">
            <template #append>
              {{ formState.currency === '0' ? '元' : '美金' }}
            </template>
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" style="margin-right: 10px;">{{
              $t('form.Confirm')
            }}
          </a-button>
          <a-button @click="resetForm">{{ $t('form.Cancel') }}</a-button>
        </a-form-item>
      </a-form>
    </a-modal>


    <a-modal width="70%" :visible="planVisible" title="选择流量包" @ok="handleSubmitPlan" @cancel="handleCancel">
      <!-- 搜索条件区 -->
      <div class="search-section">
        <a-form :model="formData" layout="inline">
          <a-form-item field="label" :label="$t('tariffManagement.label')">
            <a-input v-model="formData.label"
                     :placeholder="$t('lotCard.please') + $t('tariffManagement.label')" allow-clear/>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleSearchPlan">{{ $t('form.Search') }}</a-button>
              <a-button @click="resetSearchPlan">{{ $t('form.Reset') }}</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>
      <a-table row-key="id" :data="planList" :columns="planColumns" :scroll="{ x: 'auto' }"
               :row-selection="rowSelectionPlan" v-model:selectedKeys="selectedKeysPlan">

      </a-table>

    </a-modal>
  </div>
</template>

<script setup>
import {onMounted, ref, reactive, getCurrentInstance, nextTick, watch} from "vue";
import {useRoute} from "vue-router";
import {columns, columnsCustomer, planColumns} from "./config";
import {Message} from '@arco-design/web-vue'
import {deleteTariff, updateTariff, addTariff, tariffList} from "@/api/path/tariffManagement.api"
import {getDataPlanList} from "@/api/path/lotCard.api"
import {getSTSInfoList} from '@/api/path/system.api'
import {Getdictionary} from '@/mixins/index.js'
import {useSystemStore} from '@/store/modules/systemStore'

const role = useSystemStore()


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

const currency = ref([])


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

const intData = async () => {
  const param = {
    current: pagination.value.current,
    size: pagination.value.pageSize,
    ...searchForm.value,
  }
  const {data} = await tariffList(param)
  dataSource.value = (data.records || []).map((item, index) => {
    const sourceName = sourceList.value.find(val => val.value == item.source)?.label
    const billingCycleName = cycleist.value.find(val => val.value == item.billingCycle)?.label
    const pricingCurrty = currency.value.find(val => val.value == item.currency)?.label
    const Activated = item.trafficBilling+'/'+item.trafficBillingType

    return {
      ...item,
      sourceName,
      pricingName: item.pricing !== '' ? item.pricing + '/' + pricingCurrty : '',
      billingCycleName,
      Activated:Activated,
      status: "正常"
    }
  })
  pagination.value.total = data.total
}


// 删除
const handleDel = async (id) => {
  const {code} = await deleteTariff({id})
  if (code == 200) {
    Message.success({
      content: "删除成功！",
      duration: 2000,
    })
    intData()
  }
};

const evChangePage = (page) => {
  pagination.value.current = page
  intData()
}

const handleSearch = () => {
  intData()
}
const resetSearch = () => {
  searchForm.value.label = ""
  intData()
}


// -------------------弹窗数据------------------------------------
const planList = ref([])
const userIdList = ref([])


const visible = ref(false);
const typeCurrent = ref(null);
const sourceList = ref([])
const trafficList = ref([])
const cycleist = ref([])
const typeList = ref([])
const methodList = ref([])
const settlementCycleMap = ref([])

const formState = ref({
  id: "",
  // 资费名称（必填）
  "label": "",
  // 流量包ID（必填）
  "simDataPlanId": null,
  // 用户ID（必填）
  "userId": null,
  // 来源（必填）
  "source": "",
  // 计费周期（必填）
  "billingCycle": "",
  // 计费方式（必填）
  "billingMethod": "1",
  // 结算周期（必填）
  "settlementCycle": "",
  // 价格（必填）
  "pricing": "",
  // 币种（必填）
  "currency": "0",
  // 流量资费计费
  "trafficBilling": '',
  // 流量资费计费类型
  "trafficBillingType": '',
  // 流量资费计费金
  "trafficBillingAmount": '',
  // MRC金额
  "mrcAmount": '',
  // 网络接入费
  "networkAccessFee": '',

  "settlementCycleMap": {
    "starTime": '',
    "endTime": ''
  }
});

const rules = {
  label: [{required: true, trigger: 'change',}],
  simDataPlanId: [{required: true, trigger: 'change',}],
  userId: [{required: true, trigger: 'change',}],
  source: [{required: true, trigger: 'change',}],
  billingCycle: [{required: true, trigger: 'change',}],
  billingMethod: [{required: true, trigger: 'change',}],
  currency: [{required: true, trigger: 'change',}],
  trafficBilling: [{required: true, trigger: 'change',}],
  trafficBillingType: [{required: true, trigger: 'change',}],
  trafficBillingAmount: [{required: true, trigger: 'change',}],
  mrcAmount: [{required: true, trigger: 'change',}],
  networkAccessFee: [{required: true, trigger: 'change',}],
};


// 提交
const handleSubmit = ({values, errors}) => {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      const formVal = JSON.parse(JSON.stringify(values))
      delete formVal.settlementCycleMap
      formVal.userId = Number(values.userId)
      formVal.simDataPlanId = String(values.simDataPlanId)
      if (values.settlementCycleMap.starTime && values.settlementCycleMap.starTime) {
        formVal.settlementCycle = values.settlementCycleMap.starTime + '~' + values.settlementCycleMap.endTime
      } else {
        Message.warning({
          content: "请选择订购周期！",
          duration: 2000,
        })
      }

      if (formState.value.id!=='') {
        const {code, data} = await updateTariff(formVal)

        if (code == 200) {
          Message.success({
            content: "修改成功！",
            duration: 2000,
          })
          visible.value = false;
          intData()
        }
      } else {
        const {code, data} = await addTariff(formVal)
        if (code == 200) {
          Message.success({
            content: "添加成功！",
            duration: 2000,
          })
          visible.value = false;
          intData()
        }
      }
    }
  });

}
// 弹框
const dictShowModel = (type, data) => {
  handleModelId()
  formRef.value.resetFields();
  if (formState.value.settlementCycleMap) {
    formState.value.settlementCycleMap.starTime = ''
    formState.value.settlementCycleMap.endTime = ''
  }

  typeCurrent.value = type;

  // 编辑
  if (type == 2) {
    Object.keys(formState.value).forEach(key => {
      if (data[key]) {
        formState.value[key] = data[key]
      }
    })
    formState.value.simDataPlanId = Number(formState.value.simDataPlanId)
    formState.value.userId = Number(formState.value.userId)
    if (data.pricing !== '') {
      formState.value.pricing = data.pricing.match(/\d+/)[0] || ''
    }
    if (data.settlementCycle) {
      formState.value.settlementCycleMap.starTime = data.settlementCycle.split('~')[0] || ''
      formState.value.settlementCycleMap.endTime = data.settlementCycle.split('~')[1] || ''
    }
  }
  nextTick(() => {
    visible.value = true;
  })
}

// 获取id数组
const handleModelId = async () => {
  const param = {
    current: 1,
    size: 999,
  }
  getSTSInfoList(param).then(res => {
    userIdList.value = (res.data.records || [])
  })
}
const handleDataPlan = async () => {
  const param = {
    current: 1,
    size: 999,
    source: formState.value.source
  }
  getDataPlanList(param).then(res => {
    planList.value = res.data.records || []
  })
}
// 取消
const resetForm = () => {
  visible.value = false;
  Object.keys(formState.value).forEach(key => {
      formState.value[key] = ''
  })

  formState.value.settlementCycleMap = {
    starTime:'',
    endTime:''
  }
}

// --------------------------------------------------------

// 资费弹窗------------------------------------------------
const planVisible = ref(false)
const formData = ref({})
const selectedKeysPlan = ref([])
const rowSelectionPlan = reactive({
  type: 'radio',
  showCheckedAll: true,
  onlyCurrent: false,
});


const resetSearchPlan = () => {

}
const handleSearchPlan = () => {

}
const handleCancel = () => {
  planVisible.value = false
}
const handleSubmitPlan = () => {
  if (selectedKeysPlan.value.length > 0) {
    formState.value.simDataPlanId = String(selectedKeysPlan.value[0])
    planVisible.value = false
  }

}

watch(
    () => formState.value.source,
    (newValue, oldValue) => {

      if (newValue != oldValue) {
        handleDataPlan()
      }
    },
    {immediate: true}
);

watch(()=>formState.value.billingMethod,val=>{
   if(val==2){
      formState.value.trafficBillingType = ''
      formState.value.trafficBilling = ''
      formState.value.trafficBillingAmount = ''
   }
})

// -------------------------------------------------------
// 获取字典
const handleDictValue = async () => {
  sourceList.value = await Getdictionary('source')
  cycleist.value = await Getdictionary('Billingcycle')
  typeList.value = await Getdictionary('Billingcycle')
  methodList.value = await Getdictionary('billingMethod')
  currency.value = await Getdictionary('currencyType')
}


onMounted(async () => {
  await handleDictValue()
  await 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;
      }
    }
  }
}

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

.formTitle {
  font-size: 18px;
  margin-bottom: 20px;
  display: flex;
  align-items: center
}

.formTitle::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 20px;
  background-color: green;
  margin-right: 10px;

}
</style>
