<script setup lang="ts">
import { httpCreate, httpUpdate, httpSpecs } from "/@/api/serviceParam/sort";
import { computed, ref, watch } from "vue";
import { useVModel } from "@vueuse/core"

import { ElMessage } from "element-plus";
import { useTask } from "/@/hooks/core";

const initialData = {
  im: [],
}

const emit = defineEmits(['refresh'])
const props = withDefaults(
  defineProps<{ 
    data: any; 
    pid: string; 
    visible: boolean, 
    breadcrumb: any[],
    type: string
  }>(),
  { data: {  companyNo: '',name: '', pid: '', id: '' } }
)

const title = computed(() => {
  const { type } = props
  const mapType2TitlePrefix = {
    update: '编辑',
    create: '添加',
    preview: '查看'
  }
  return `${mapType2TitlePrefix[type]}商品组织分类`
})


const visible = useVModel(props, 'visible')
const data = useVModel(props, 'data')
const loading = ref(false)

const specTask = useTask<any>({ initialData: {} })

const formRef = ref<any | null>(null)

const rules = { 
  cat_name: [{ required: true,message: '请输入分类名称',trigger: 'blur' }], 
  specs_id: [{ required: true,message: '请选择分类规格',trigger: 'blur' }], 
}

function handleClose(){
  data.value = {...initialData}
  visible.value = false
}

async function onSubmit(){
  try {
    await formRef.value.validate();
    const { 
      id, 
      fund_code,
      cat_desc,
      cat_name,
      specs_id,
      pid
    } = props.data
    
    const parameter = { 
      id, 
      fund_code,
      cat_desc,
      cat_name,
      specs_id,
      pid
    }


    if(specs_id.length === 0){
      ElMessage.warning('至少选择一个份额里')
      return 
    }

    const isCreate = id === undefined || !id
    if(!isCreate) parameter.id = id
    const api = isCreate ? httpCreate : httpUpdate
    loading.value = true
    const res = await api(parameter)
    loading.value = false
    if (res.code === 0) {
      visible.value = false
      ElMessage.success(`${isCreate ? '添加' : '更新'}成功`)
      emit('refresh')
    } else {
      ElMessage.warning(`${isCreate ? '添加' : '更新'}失败`)
    }
  } catch (err) {
    console.log(err);
  }
}


watch(() => visible.value,() => {
  if(!visible.value) {  return }
  const { 
    im = [], 
    fund_code = '', 
    cat_desc = '', 
    cat_name = '', 
    pid = props.pid, 
    id = ''
  } = data.value

  data.value = {
    specs_id: im.map(({specs_id}) => specs_id),
    fund_code,
    cat_desc,
    cat_name,
    pid,
    id
  }


  specTask.run(httpSpecs({}))
})
</script>


<template>
  <ElDialog v-model="visible" :title="title" center @close="handleClose">
    <ElForm 
      :model="data" 
      :rules="rules" 
      size="small" 
      ref="formRef" 
      :disabled="type === 'preview'"
      label-width="80px"
     >
      <ElFormItem label="分类名称" prop="cat_name">
        <ElInput 
          v-model="data.cat_name" 
          style="width:100%" 
          placeholder="分类名称"  
        >
          <template #prepend v-if="data.pid !== '0'">
            {{ breadcrumb.map(({cat_name}) => cat_name).join(' / ') }}
          </template>
        </ElInput>
      </ElFormItem>

      <ElFormItem label="分类规格" prop="specs_id">
        <ElSelect
          :loading="specTask.loading"
          v-model="data.specs_id" 
          style="width:100%" 
          placeholder="分类规格" 
          multiple
        >
          <ElOption 
            v-for="im in specTask.data" 
            :label="im.spec_name" 
            :value="im.id"
            :disabled="String(im.status) === '0'" 
           />
        </ElSelect>
      </ElFormItem>

      <ElFormItem label="售后说明" prop="cat_desc">
        <ElInput
          type="textarea"
          v-model="data.cat_desc" 
          style="width:100%" 
          placeholder="售后说明"  
        />
      </ElFormItem>


      <div class="flex justify-end w-full">
        <ElButton 
          type="primary" 
          @click="onSubmit"
          :loading="loading"
          >保存</ElButton>
      </div>
    </ElForm>
  </ElDialog>
</template>
