<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <template #header>
      <div class="card-header">
        <span>{{ props.primary ? '编辑' : '添加' }}充值模板</span>
      </div>
    </template>
    <el-form :model="dataForm" label-width="120px" ref="form" v-loading="loading" class="pr-6">
      <el-form-item label="模板名称" prop="name"
        :rules="[{ required: true, message: '模板名称必须填写' }, { max: 20, message: '至多输入20个字符', trigger: 'blur' }]">
        <el-input :disabled="Boolean(props.primary)" class="item" v-model="dataForm.name" clearable />
      </el-form-item>
      <el-form-item label="充值档位" prop="options" :rules="[{ required: true, message: '请添加充值档位' }]">
        <el-card class="w-full" shadow="never">
          <div class="pt-5 pl-2">
            <Add @click="openGears(null, null)" />
          </div>
          <el-table :data="tableData" class="w-full mt-3" v-loading="loading">
            <el-table-column prop="price" label="价格">
              <template #default="scope">
                <span>{{ scope.row.price }}元</span>
              </template>
            </el-table-column>
            <el-table-column prop="sequence_text" label="位置" />
            <el-table-column prop="type_name" label="挡位类型" />
            <el-table-column prop="charge_coin" label="充看币">
              <template #default="scope">
                <span v-if="!isShowKb(scope.row)">{{ Math.round(Number(scope.row.price) * 100) }}k币</span>
                <span v-else>{{ scope.row.type_name }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="given" label="充看送币">
              <template #default="scope">
                <span>{{ scope.row.given }}k币</span>
              </template>
            </el-table-column>
            <el-table-column prop="default_text" label="默认项">
              <template #default="scope">
                <span>{{ scope.row.is_default ? '默认项' : '非默认项' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="openGears(scope.$index, scope.row)">编辑</el-button>
                <el-button link type="danger" size="small" @click.prevent="deleteRow(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form-item>
      <el-form-item label="启用状态" prop="status" :rules="[{ required: true, message: '请设置启用状态' }]">
        <el-switch v-model="dataForm.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <div class="flex justify-start ml-9">
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitFormChange(form)">确认</el-button>
      </div>
    </el-form>
    <Dialog v-model="visibleGears" :title="title" width="40%" destroy-on-close>
      <createGears @close="gearsClose" @success="success" :data="tableData" :primary="gearsData" />
    </Dialog>
  </el-card>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import {
  channelPaytemplateShow,
  channelPaytemplateStore,
  channelPaytemplateUpdate,
  channelPaytemplateOptionTypeList
} from '@/api/charge/index'
import { FormInstance } from 'element-plus';
import createGears from './createGears.vue'
const visibleGears = ref(false)
const loading = ref(false)
const gearsData = ref()
const tableData = ref([])
const form = ref()
const emit = defineEmits(['close']);
const dataForm = ref({ status: 1 })

const title = computed(() =>
  gearsData.value ?
    '编辑充值档位' : '添加充值档位'
)

const optionTypeList = ref([]);
const props = defineProps({
  primary: String | Number | Object,
  api: String,
});
const filtersObj = ['MONTH', 'QUARTER', 'YEAR']

const isShowKb = (e) => {
  return filtersObj.includes(e.type)
}
const gearsClose = () => {
  visibleGears.value = false
}
const openGears = (index: number | null, row: object) => {
  if (row) {
    gearsData.value = row
    gearsData.value.index = index
    visibleGears.value = true
  } else {
    if (tableData.value.length >= 6) return ElMessageBox.alert('当前充值档位位置已满')
    gearsData.value = null
    visibleGears.value = true
  }
}
const deleteRow = (index: number) => {
  ElMessageBox.confirm(
    '确定要删除此条充值档位吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      tableData.value.splice(index, 1)
    })
    .catch(() => {

    })
}
const success = (e) => {
  console.log(e, 'successsuccesssuccess');
  const data = {
    ...e,
    ...e.typeObj,
    ...e.sequenceObj
  };
  if (e.index != undefined) {
    tableData.value[e.index] = data
  } else {
    tableData.value.push(data)
  }
}
const cancel = () => {
  emit('close')
}
const submitFormChange = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  dataForm.value.options = tableData.value.map(el => {
    return {
      price: Number(el.price),
      type: el.type,
      given: Number(el.given),
      sequence: el.sequence,
      is_default: el.is_default
    }
  })
  loading.value = true;
  formEl
    .validate(valid => {
      if (valid) {
        const params = {
          name: dataForm.value.name,
          status: dataForm.value.status,
          options: JSON.stringify(dataForm.value.options),
        }
        console.log(params, 'paramsparams');
        if (props.primary) {
          channelPaytemplateUpdate(dataForm.value.id, params).then(res => {
            loading.value = false;
            ElMessage.success(res.message)
            emit('close')
          }).catch(e => {
            loading.value = false;
          })
        } else {
          channelPaytemplateStore(params).then(res => {
            loading.value = false;
            ElMessage.success(res.message)
            emit('close')
          }).catch(e => {
            loading.value = false;
          })
        }
      } else {
        loading.value = false;
      }
    })
    .then(() => { });
}

if (props.primary) {
  console.log(props.primary, 'props.primary');
  channelPaytemplateShow(props.primary).then(res => {
    dataForm.value = res.data.template_info
    console.log(res, 'channelPaytemplateShowchannelPaytemplateShow');
    tableData.value = res.data.template_item_list
  })
}

onMounted(() => {
  channelPaytemplateOptionTypeList().then(res => {
    console.log(res);
    optionTypeList.value = res.data

  })
});
</script>
<style scoped lang="scss">
.item {
  width: 300px;
}

.type-wrapper {
  width: 80%;
  display: flex;

  .btn {
    margin: 0 6px;
  }
}
</style>
