<template>
  <div>
    <template v-if="AddSet">
      <div class="search">
        <Search :SearchForm="SetMealSearchForm" @query="initData" @reset="reset"></Search>
      </div>

      <div class="addSetMeal">
        <a-button type="primary" @click="visibleSetMeal = true">新增套餐计划</a-button>
      </div>

      <div class="table">
        <a-table row-key="id" :data="tableData" :columns="columnsSetMeal" :pagination="pagination"
          :scroll="{ x: 'auto' }" @page-change="evChangePage">
          <template #status="{ record }">
            <a-tag :color="record.status == 1 ? '#7bc616' : '#86909c'">{{ record.status == 1 ? '上架' : '下架' }}</a-tag>
          </template>
          <template #Controls="{ record }">
            <a-space>
              <a-button type="text" @click="SetUpPackage(record)" v-if="record.isRecharge == 1"> 设置套餐</a-button>
              <a-button type="text" @click="unmount(record)">{{ record.status == 1 ? '下架' : '上架' }}</a-button>
            </a-space>
          </template>
          <template #isRechargeName="{ record }">
            {{ filterDict(SetMealList, record.isRecharge) }}
          </template>
          <template #defaultTrafficName="{ record }">
            {{ record.defaultTraffic.label }}
          </template>
        </a-table>
      </div>
    </template>

    <a-modal v-model:visible="visibleSetMeal" width="600px" @cancel="handelCancel" title="新增套餐计划">
      <div class="Form">
        <a-form ref="formRef" :rules="rules" :model="Form">
          <a-form-item label="套餐计划名称" field="label" validate-trigger="blur">
            <a-input placeholder="请输入套餐计划名称" v-model="Form.label"></a-input>
          </a-form-item>
          <a-form-item label="选择所属客户" field="userId" validate-trigger="blur">
            <a-select :style="{ width: '320px' }" v-model="Form.userId" placeholder="请选择所属客户">
              <a-option v-for="(item, index) in userList" :value="item.id">{{ item.name }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="运营商" field="source" validate-trigger="blur">
            <a-select :style="{ width: '320px' }" v-model="Form.source" placeholder="请选择运营商">
              <a-option v-for="(item, index) in sourceList" :value="item.value">{{ item.label }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="套餐计划类型" field="isRecharge">
            <a-radio-group v-model="Form.isRecharge" :options="SetMealList" />
          </a-form-item>
          <div class="title" v-if="Form.isRecharge==1">此类型下,一个套餐计划代表一个充值二维码请在下载粘贴二维码时仔细核对</div>
          <div class="title" v-if="Form.isRecharge==2">非充值类型套餐计划,则无需用户充值,导卡成功充值后用户可直接使用流量</div>
          <a-form-item label="默认绑定资费" >
            <a-select v-model="Form.defaultTrafficId">
              <a-option v-for="item in tariffListData" :value="item.id" :key="item.id">{{ item.label
                }}</a-option>
            </a-select>
          </a-form-item>
          <!-- <div class="title">
            终端用户充值类该字段必填,非充值类该字段非必填
          </div> -->
        </a-form>
      </div>
      <template #footer>
        <a-button @click="handelCancel">取消</a-button>
        <a-button type="primary" @click="handleSubmit">确定</a-button>
      </template>
    </a-modal>
    <!-- 新增套餐计划 -->
    <AddSetMeal v-if="!AddSet" :list="list" @break="AddSet = true" />
  </div>

</template>

<script setup>
import { ref, onMounted, toRefs, watch } from 'vue';
import Search from '@/components/Search/index.vue'
import { SetMealSearchForm, columnsSetMeal } from '../config.js'
import { getMessUserList, } from '@/api/customer.js';
import { PackageSchedule, addTariffSchedule, PackageTakedown, tariffList } from '@/api/path/tariffManagement.api.js'
import QrcodeVue from 'qrcode.vue'
import { Getdictionary, tableFunction, filterDict } from '@/mixins/index.js'
import { Message, Modal } from '@arco-design/web-vue';
import AddSetMeal from './addSetMeal.vue'
const formRef = ref(null);
const rules = {
  userId: [
    { required: true, message: '请选择所属客户', trigger: 'blur' },
  ],
  label: [
    { required: true, message: '请输入套餐计划名称', trigger: 'blur' },
  ],
  source: [
    { required: true, message: '请选择运营商', trigger: 'blur' },
  ],
};


const state = ref({
  pagination: {
    total: 0,
    pageSize: 10,
    current: 1,
  },
  visibleSetMeal: false,
  Form: {
    userId: null,
    label: null,
    isRecharge: '1',
    defaultTrafficId: null,
    source: null
  },
  userList: [],
  SetMealList: [],
  tariffListData: [],
  sourceList:[],
  AddSet: true,
  list: {}
})
const { pagination, visibleSetMeal, userList, Form, AddSet, SetMealList, tariffListData, sourceList, list } = toRefs(state.value)


const { tableData, evChangePage, initData, reset } = tableFunction(pagination.value, PackageSchedule)

const fetchCustomerList = async (item) => {
  const response = await getMessUserList({
    current: 1,
    pageSize: 99999,
  });
  if (response.code === 200 && response.data) {
    userList.value = response.data.records
  }
};


const handleSubmit = ({ values, errors }) => {
  formRef.value.validate(async (values, errors) => {
    if (!errors) {
      if (Form.value.isRecharge == 1 && Form.value.defaultTrafficId == null) return Message.error('请选择充值绑定资费')
      Form.value.isRecharge = Number(Form.value.isRecharge)
      const response = await addTariffSchedule(Form.value)
      if (response.code === 200) {
        Message.success('添加成功')
        visibleSetMeal.value = false
        initData()
      } else {
        console.log(response)
      }
    }
  })
}

const unmount = async (record) => {
  Modal.info({
    title: `确定要${record.status == 1 ? '下架' : '上架'}吗?`,
    content: '',
    onOk: async () => {
      let res = await PackageTakedown({ id: record.id, status: record.status == 1 ? 2 : 1, label: record.label, userId: record.userId })
      if (res.code === 200) {
        Message.success(`${record.status == 1 ? '下架' : '上架'}成功`)
        initData()
      }
    }
  });
}

const SetUpPackage = (item) => {
  list.value.id = item.id
  list.value.source = item.source
  list.value.userId = item.userId
  AddSet.value = false
}

const handelCancel = () => {
  Object.keys(Form.value).forEach(res => {
    Form.value[res] = null
  })
  visibleSetMeal.value = false
  Form.value.isRecharge = "1"
}


watch(() => Form.value.userId, val => {
  getTarrife(val)
}, { deep: true })

watch(() => Form.value.source, val => {
  getTarrife(Form.value.userId, val)
}, { deep: true })

// 资费
const getTarrife = async (item, sourceId) => {
  let res = await tariffList({ current: 1, size: 99999, userId: item, source: sourceId })
  tariffListData.value = []
  Form.value.defaultTrafficId = null
  if (res.code === 200) {
    tariffListData.value = (res.data.records || []).map(item => {
      return {
        ...item,
        value: item.id,
        label: item.label + '---' + item.userName
      }
    })
  }
}

onMounted(async () => {
  let dict = await Getdictionary(['setMeal', 'source'])
  SetMealList.value = dict[0]
  sourceList.value = dict[1]
  initData()
  fetchCustomerList()
  getTarrife()
})
</script>
<style lang="less" scoped>
.search,
.table {
  margin-top: 1rem;
}

.code {
  justify-content: center;
  display: flex;
}

.title {
    font-size: 14px;
    color: #ccc;
    margin-left: 120px;
    margin-top: -15px;
    margin-bottom: 10px;
}
</style>