<script setup lang="ts">
import {  ref , watch, computed } from "vue"
import { useVModel } from "@vueuse/core"
import { SupplierQuery, BrandQuey } from "/@/components/BasicForm"
import { ImageSingleUpload } from "/@/components/ImageUpload"
import { httpDetail, httpAdd, httpUpdate } from "/@/api/serviceParam/supplierBrand";
import { useTask, useTasks } from "/@/hooks/core"

import { isEncoded } from "/@/utils/global"

import { rules } from "./config/_options"
import { ElForm } from "element-plus"

const initialData = { 
  gyscode: '',  
  brand_id: '', 
  long: 0, 
  authTimeLongTerm: [], 
  authTime: '', 
  brand_book: '', 
  remark: '',
  status: ''
}

const emit = defineEmits(['refresh'])
const props = defineProps<{ visible: boolean; id: string, type: string }>()

const formRef = ref<InstanceType<typeof ElForm> | null>(null)
const formData = ref({ ...initialData })

const supplierQueryRef = ref<InstanceType<typeof SupplierQuery> | null>(null)
const brandQueyRef = ref<InstanceType<typeof BrandQuey> | null>(null)
const visible = useVModel(props, 'visible')

const title = computed(() => {
  const map = {
    create : '创建',
    preview: '查看',
    update: '编辑'
  }
  return `${map[props.type]}支持品牌`
})

const supportDetailTask = useTask({ success (data){
  const { brand_book, brand_id, brand_name, endtime, starttime, long, gyscode, remark, gysname: name, status } = data
  formData.value = {
    authTimeLongTerm: long === 1 ? [starttime, endtime] : [],
    authTime: long === 0 ? starttime : '',
    brand_book,
    brand_id,
    gyscode,
    remark,
    status,
    long
  }
  supplierQueryRef.value.initialData({ name })
  brandQueyRef.value.initialData({ brand_name })
}})


function success(){
  visible.value = false
  emit('refresh')
}


const supportCreateTask = useTask({ success })
const supportUpdateTask = useTask({ success })
const taskState = useTasks(supportCreateTask, supportUpdateTask)

watch(() => props.visible, (visible) => {
  if(!visible) { return }
  if(props.id){
    supportDetailTask.run(httpDetail({ id: props.id }))
  }else {
    formData.value = { ...initialData }
  }
}, {
  immediate: true
})


async function onSubmit(){
  try{
   await formRef.value.validate()
   let { long, gyscode, brand_id, authTimeLongTerm, authTime, remark, status, brand_book } = formData.value
   const isCreate = !props.id


   if(!isEncoded(brand_book)) { brand_book = encodeURI(brand_book)  }

   const parameters = {
    id: props.id,
    long,
    gyscode,
    brand_id,
    remark,
    status,
    starttime: '',
    endtime: '',
    brand_book
   }

   if(long === 1){
    const [ starttime, endtime ] = authTimeLongTerm
    parameters.starttime = starttime
    parameters.endtime = endtime
   }else{
    parameters.starttime = authTime
    delete parameters['endtime']
   }

   if(isCreate) {
    delete parameters.id
    delete parameters.status
   }

   const task = isCreate ? supportCreateTask : supportUpdateTask
   const api = isCreate ? httpAdd : httpUpdate
   task.run(api(parameters))
  }catch(err){
    console.log(err)
  }
}
</script>

<template>
  <ElDialog v-model="visible" :title="title" center>
    <ElForm v-model="formData" v-loading="supportDetailTask.loading" label-width="100px" :rules="rules" :disabled="type === 'preview'" ref="formRef">
      <ElFormItem label="供应商" prop="gyscode">
        <SupplierQuery v-model="formData.gyscode" placeholder="供应商" ref="supplierQueryRef" />
      </ElFormItem>
      
      <ElFormItem label="支持品牌" prop="brand_id">
        <BrandQuey v-model="formData.brand_id" placeholder="支持品牌" ref="brandQueyRef" />
      </ElFormItem>
      
      <ElFormItem label="授权类型" prop="long">
        <ElRadioGroup v-model="formData.long">
          <ElRadio 
            v-for="(opt, index) in [{ value: 1, label: '非长期' }, { value: 0, label: '长期' }]" :key="index" 
            :label="opt.value"
          >
            {{ opt.label }}
          </ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      
      <ElFormItem label="授权时间" prop="authTimeLongTerm" v-if="formData.long === 1">
        <ElDatePicker
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
          v-model="formData.authTimeLongTerm"
          start-placeholder="开始时间"
          end-placeholder="开始时间"
        />
      </ElFormItem>

      <ElFormItem label="授权时间" prop="authTime" v-else>
        <div class="flex">
          <ElDatePicker type="date"  value-format="YYYY-MM-DD HH:mm:ss" v-model="formData.authTime" placeholder="开始时间" />
          <p class="mx-[10px]">-</p>
          <p>长期有效</p>
        </div>
      </ElFormItem>

      <ElFormItem label="授权图片" prop="brand_book">
        <ImageSingleUpload v-model="formData.brand_book" placeholder="授权图片" />
      </ElFormItem>
      
      <ElFormItem label="备注" prop="remark">
        <ElInput type="textarea" v-model="formData.remark" placeholder="备注" />
      </ElFormItem>

      <ElFormItem>
        <div class="w-full flex justify-end">
          <ElButton type="primary" :loading="taskState.loading" @click="onSubmit">提交</ElButton>
        </div>
      </ElFormItem>
    </ElForm>
  </ElDialog>
</template>
