<script setup>
import { ref, onMounted, toRefs, toRef, watch } from 'vue';
import { Message } from "@arco-design/web-vue";
import {
  addTrafficPool,
  updateTrafficPool,
  updateCardList
} from "@/api/path/flowPool.api"
import { tariffList } from "@/api/path/tariffManagement.api"
import { Getdictionary } from '@/mixins/index.js'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  status: {
    type: [String, Number],
    default: ''
  },
  typeCurrent: {
    type: [String, Number],
    default: ''
  },
  record: {
    type: [Array, Object],
    default: () => {
    }
  }
})

const modelValue = toRef(props, 'modelValue')
const status = toRef(props, 'status')
const typeCurrent = toRef(props, 'typeCurrent')
const record = toRef(props, 'record')
const emit = defineEmits(['update:modelValue', 'submit'])
const rules = {
  label: [{ required: true, trigger: 'change', }],
  source: [{ required: true, trigger: 'change', }],
  status: [{ required: true, trigger: 'change', }],
  simTariffId: [{ required: true, trigger: 'change', }],
  expireTime: [{ required: true, trigger: 'change', }],
  size: [{ required: true, trigger: 'change', }],
  sizeType: [{ required: true, trigger: 'change', }],
};
const state = ref({
  typeList: [],
  tariffIdList: [],
  formState: {
    "label": "",
    "trafficPoolType": status.value,
    "source": "",
    "status": "",
    "simTariffId": null,
    "expireTime": "",
    // "iccids": [],
    "size": null,
    "sizeType": ""
  },
  card: [],
  formRef: null,
  sourceList: [],
  trafficList: [],
  SelectAll: false
})

const { typeList, tariffIdList, formState, card, formRef, sourceList, trafficList, SelectAll } = toRefs(state.value)

// 提交
const handleSubmit = ({ values, errors }) => {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      values.size = Number(values.size)
      if (status.value == 1) {
        delete formState.value.sizeType
        delete formState.value.size
      }
      if (formState.value.id) {
        const { code, data } = await updateTrafficPool(formState.value)

        if (code == 200) {
          Message.success({
            content: t('setting.editSuccess'),
            duration: 2000,
          })
          resetForm()
          emit('submit', true)
        }
      } else {
        const { code, data } = await addTrafficPool(formState.value)
        if (code == 200) {
          Message.success({
            content: t('setting.addSuccess'),
            duration: 2000,
          })
          resetForm()
          emit('submit', true)
        }
      }
    }
  });
}

// 获取资费列表选择id
const handleTariff = async () => {
  const { code, data } = await tariffList({
    "current": 1,
    "size": 10
  })
  if (code == 200) {
    tariffIdList.value = (data.records || []).map(item => {
      return {
        ...item,
        value: item.id,
        label: item.label + '---' + item.userName
      }
    })
  }
}

// 取消
const resetForm = () => {
  emit('update:modelValue', false)
  formState.value = {
    "label": "",
    "trafficPoolType": "2",
    "source": "",
    "status": "",
    "simTariffId": null,
    "expireTime": "",
    // "iccids": [],
    "size": null,
    "sizeType": ""
  }
}

// 获取字典
const handleDictValue = async () => {
  sourceList.value = await Getdictionary('source')
  trafficList.value = await Getdictionary('trafficPacketStatus')
  typeList.value = await Getdictionary('trafficPoolType')
}


// const selectChange = (val) => {
//   updateCardList({ id: val }).then(res => {
//     if (res.code === 200) {
//       formState.value.iccids = []
//       card.value = res.data
//     }
//   })
// }

watch(() => record.value, val => {
  const datas = JSON.parse(JSON.stringify(val))
  if (props.typeCurrent == 2) {
    formState.value = datas
    // formState.value.iccids = []
    // updateCardList({ id: val.simTariffId }).then(res => {
    //   if (res.code === 200) {
    //     val.iccids.forEach(res => {
    //       formState.value.iccids.push(res.iccid)
    //     })
    //     card.value = res.data
    //   }
    // })
  }
}, { deep: true })

watch(() => modelValue.value, val => {
  if (val) {
    handleDictValue()
    handleTariff()
  }
})


// const changeAll = (e)=>{
//   SelectAll.value = e
//   if (e) {
//     formState.value.iccids = card.value.map(res => res.iccid)
//   } else {
//     formState.value.iccids = []
//   }
// }


</script>

<template>
  <a-modal :render-to-body="false"
    :title="typeCurrent == 1 ? $t('form.Add') : typeCurrent == 2 ? $t('form.Edit') : $t('flowPool.Detail')"
    v-model:visible="modelValue" @cancel="resetForm" centered :maskClosable="false" :footer="null" width="55%">
    <a-tabs v-model:active-key="activeKey">
      <a-tab-pane key="1" :title="$t('flowPool.infoTabs')">
        <a-form ref="formRef" :rules="rules" :model="formState" @submit="handleSubmit" style="width: 620px;">
          <a-form-item :label="$t('flowPool.label')" field="label">
            <a-input v-model="formState.label"
              :placeholder="$t('form.datapoolForm.pleaseSelect') + $t('flowPool.label')" />
          </a-form-item>
          <a-form-item :label="$t('flowPool.source')" field="source">
            <a-select v-model="formState.source"
              :placeholder="$t('form.datapoolForm.pleaseSelect') + $t('flowPool.source')">
              <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 :label="$t('flowPool.trafficPoolStatus')" field="status">
            <a-select v-model="formState.status"
              :placeholder="$t('form.datapoolForm.pleaseSelect') + $t('flowPool.trafficPoolStatus')">
              <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 :label="$t('flowPool.simRariff')" field="simTariffId">
            <a-select v-model="formState.simTariffId" @change="selectChange"
              :placeholder="$t('form.datapoolForm.pleaseSelect') + $t('flowPool.simRariff')">
              <a-option v-for=" item in tariffIdList" :key="item.id" :value="item.value">{{
                item.label
              }}
              </a-option>
            </a-select>
          </a-form-item>
          <!-- <a-form-item :label="$t('flowPool.ICCIDlabel')" v-if="formState?.simTariffId !== null">
            <a-select v-model="formState.iccids" multiple :placeholder="$t('flowPool.ICCIDName')" :max-tag-count="10">
              <a-option v-for=" item in card" :key="item.iccid" :value="item.iccid">{{item.iccid}}
              </a-option>
              <template #header>
                <div style="padding: 6px 12px;">
                  <a-checkbox v-model="SelectAll" @change="changeAll">全选</a-checkbox>
                </div>
              </template>
            </a-select>
          </a-form-item> -->
          <a-form-item :label="$t('flowPool.expireTime')" field="expireTime">
            <a-date-picker v-model="formState.expireTime" show-time :time-picker-props="{ defaultValue: '09:09:06' }"
              format="YYYY-MM-DD HH:mm:ss" />
          </a-form-item>
          <a-form-item :label="$t('flowPool.poolSize')" field="size" v-if="status == 2">
            <a-input v-model="formState.size" :placeholder="$t('flowPool.poolSize')" />
            <a-select v-model="formState.sizeType" style="width: 80px; margin-left: 8px;">
              <a-option value="KB">KB</a-option>
              <a-option value="MB">MB</a-option>
              <a-option value="GB">GB</a-option>
            </a-select>
          </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-tab-pane>
    </a-tabs>

  </a-modal>
</template>

<style scoped lang="less"></style>
