<template>
  <el-form :model="form" label-width="130px" ref="ruleForm" :rules="rules" v-loading="loading" class="pr-4">
    <div class="flex flex-row justify-between">
      <div class="w-full">
        <el-form-item label="小程序名称" prop="email">
          <el-input v-model="form.name" disabled placeholder="请填写登录账号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" disabled :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="分配至投放公司" prop="depotsValue" :rules="[{ required: true, message: '请选择' }]">
          <el-select v-model="form.depotsValue" filterable clearable placeholder="请选择">
            <el-option v-for="item in dataObj" :key="item.id" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>
      </div>
    </div>
    <div class="flex justify-end">
      <el-button type="primary" size="default" @click="doSave(ruleForm)">确定</el-button>
    </div>
  </el-form>
</template>

<script lang="ts" setup>
import { manageMiniprogramAllocationDetail, manageMiniprogramShow, manageMiniprogramAllocation } from '@/api/applet/index'
import type { FormInstance, FormRules } from 'element-plus'
const props = defineProps({
  primary: Object,
});
const ruleForm = ref<FormInstance>()
const loading = ref(false)
const rules = reactive({
  miniProgramIds: [{ required: true, message: '请选择小程序' }],
});
const form = ref({})
const dataObj = ref([])
const emit = defineEmits(['close']);
const params = ref({})
const doSave = (formEl: FormInstance | undefined) => {
  params.value = {
    action: "on",
    uids: form.value.depotsValue
  }
  if (!formEl) return;
  formEl
    .validate(valid => {
      if (valid) {
        manageMiniprogramAllocation(props.primary.id, params.value).then(res => {
          console.log(res);
          ElMessage.success(res.message)
          emit('close', false)
        })
      } else {
        loading.value = false;
      }
    })
    .then(() => { });


}

onMounted(() => {
  manageMiniprogramAllocationDetail(props.primary.id).then(res => {
    console.log(res, 'manageMiniprogramAllocationDetail');
    dataObj.value = res.data.all
    let timer = setTimeout(() => {
      if (res.data.on?.length > 0) {
        form.value.depotsValue = res.data.on.map(el => el.id)[0]
        clearTimeout(timer)
      }
    }, 10);
  });
  manageMiniprogramShow(props.primary.id).then(res => {
    console.log(res, 'props.primary');
    form.value = res.data
  })
})

</script>

<style lang="scss" scoped>
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}
</style>
