<template>
  <el-dialog v-model="props.visible" :title="props.configItemId ? '编辑配置项' : '新增配置项'" width="500"
    :close-on-click-modal="false" :before-close="dialogClose">
    <el-form class="ls-form" ref="formRef" :model="formData" label-width="100px">
      <el-form-item label="配置项名称" prop="name" :rules="{ required: true, message: '请输入配置项名称', trigger: 'blur' }">
        <el-input v-model="formData.name" placeholder="请输入配置项名称" clearable />
      </el-form-item>
      <el-form-item label="配置项编码" prop="code" :rules="{ required: true, message: '请输入配置项编码', trigger: 'blur' }">
        <el-input v-model="formData.code" placeholder="请输入配置项编码" clearable />
      </el-form-item>

      <el-form-item label="配置项类型" prop="type" class="flex-1"
        :rules="{ required: true, message: '请选择配置项类型', trigger: 'change' }">
        <el-select v-model="formData.type" class="flex-1" placeholder="请选择配置项类型" @change="handleTypeChange">
          <el-option v-for="(item, index) in typeList" :key="index" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="配置项源" prop="options">
        <el-icon :size="25" color="#165DFF" style="cursor:pointer;" @click="addOptions"><CirclePlusFilled /></el-icon>
        <div v-for="(item,index) in optionsData" :key="index" style="margin-top:8px;">
          <div class="flex item-center">
            <el-input v-model="item.name" placeholder="请输入name" clearable />
            <div style="margin:0 10px;">-</div>
            <el-input v-model="item.value" placeholder="请输入value" clearable />
            <el-icon :size="25" color="#f56c6c" style="cursor:pointer;margin-left:10px;"  @click="delOptions(index)"><RemoveFilled /></el-icon>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="配置项值" prop="value">
        <template
          v-if="formData.type == 'text' || formData.type == 'readonly' || formData.type == 'textarea' || formData.type == 'password'">
          <el-input v-model="formData.value"
            :type="formData.type == 'textarea' ? 'textarea' : (formData.type == 'password' ? 'password' : '')"
            placeholder="请输入配置项值" clearable />
        </template>
        <template v-else-if="formData.type == 'number'">
          <el-input-number v-model="formData.value" placeholder="请输入配置项值" />
        </template>
        <template v-else-if="formData.type == 'icon'">
          <IconPicker  class="flex-1" v-model="formData.value" />
        </template>
        <template v-else-if="formData.type == 'radio'">
          <el-radio-group v-model="formData.value">
            <el-radio v-for="(item,index) in optionsData" :value="item.value" :key="index">
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </template>
        <template v-else-if="formData.type == 'checkbox'">
          <el-checkbox-group v-model="formData.values">
            <el-checkbox :value="item.value" :key="index" v-for="(item, index) in optionsData">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </template>
        <template v-else-if="formData.type == 'select'">
          <el-select v-model="formData.value">
            <el-option v-for="(item, index) in optionsData" :key="index" :value="item.value" :label="item.name" />
          </el-select>
        </template>
        <template v-else-if="formData.type == 'selects'">
          <el-select v-model="formData.values" :multiple="true">
            <el-option v-for="(item, index) in optionsData" :key="index" :value="item.value" :label="item.name" />
          </el-select>
        </template>
        <template v-else-if="formData.type == 'date' || formData.type == 'datetime'">
          <el-date-picker  :type="formData.type"
          placeholder="请选择日期" v-model="formData.value" style="width:100%;"
          :value-format="formData.type == 'date' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'"
          :format="formData.type == 'date' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'" />
        </template>
        <template v-else-if="formData.type  == 'image'">
          <UploadImg
                  @changeFileName="(name)=>formData.fileName=name"
                    :fileType=" ['image/jpeg', 'image/png', 'image/jpg', 'image/gif']"
                    name="config"
                    :fileSize="200"
                    v-model:image-url="formData.filePath">
            <template v-slot:tip>支持扩展名: jpg png jpeg;文件大小不超过200M</template>
          </UploadImg>
        </template>
        <template v-else-if="formData.type  == 'images'">
          <UploadImgs @upload="fileUploads" file-type=".jpeg,.png,.jpg,.gif" name="config" 
          :fileSize="200" :multiple="true" :fileList="formData.fileList"/>
        </template>
        <template v-else-if="formData.type  == 'file'">
          <UploadFile @upload="fileUploadFile" file-type=".xlsx.xls.doc.docx" name="config"
          :file-list="formData.filePath?[{name:formData.fileName,url:formData.filePath}]:[]"/>
        </template>
        <template v-else-if="formData.type  == 'files'">
          <UploadFile @upload="fileUploads" file-type=".xlsx.xls.doc.docx" name="config" :multiple="true"
          :file-list="formData.fileList"/>
        </template>
        <template v-else-if="formData.type  == 'ueditor'">
          <Editor ref="editorRef" :height="fwbHeight" class="flex-1" name="config"/>
        </template>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" />
      </el-form-item>
      <el-form-item label="配置项状态" prop="status">
        <el-radio-group v-model="formData.status" name="status">
          <el-radio :value="1">正常</el-radio>
          <el-radio :value="2">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <el-input v-model="formData.note" type="textarea" placeholder="请输入备注" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import type { FormInstance } from "element-plus";
import { getConfigItemDetail, configItemAdd, configItemUpdate } from "@/api/data/config";
import { onMounted, ref, reactive, shallowRef } from "vue";
import { message } from "@/utils/auth";
import IconPicker from "@/components/icon/picker.vue";
import { useLockFn } from "@/utils/useLockFn";
import Editor from '@/components/Editor/tinymce.vue'
import UploadImg from '@/components/Upload/Image.vue';
import UploadImgs from '@/components/Upload/Images.vue';
import UploadFile from '@/components/Upload/file.vue';

const emit = defineEmits(["success", "update:visible"]);
const formRef = shallowRef<FormInstance>();
const formData = reactive({
  id: "",
  name: "",
  code: "",
  value: "",
  values:[],
  fileName:'',
  filePath:'',
  fileList:[],
  valueList:[],
  sort: 0,
  options: '',
  type: 'text',
  status: 1,
  note: ''
});
const fwbHeight=document.body.clientHeight -400
const optionsData=ref([])
const typeList = ref([
  {
    name: '隐藏',
    value: 'hidden'
  },
  {
    name: '只读文本',
    value: 'readonly'
  },
  {
    name: '数字',
    value: 'number'
  },
  {
    name: '单行文本',
    value: 'text'
  },
  {
    name: '多行文本',
    value: 'textarea'
  },
  {
    name: '密码',
    value: 'password'
  },
  {
    name: '单选框',
    value: 'radio'
  },
  {
    name: '复选框',
    value: 'checkbox'
  },
  {
    name: '下拉框(单选)',
    value: 'select'
  },
  {
    name: '下拉框(多选)',
    value: 'selects'
  },
  {
    name: '字体图标',
    value: 'icon'
  },
  {
    name: '日期',
    value: 'date'
  },
  {
    name: '时间',
    value: 'datetime'
  },
  {
    name: '单张图片',
    value: 'image'
  },
  {
    name: '多张图片',
    value: 'images'
  },
  {
    name: '单个文件',
    value: 'file'
  },
  {
    name: '多个文件',
    value: 'files'
  },
  {
    name: '富文本编辑器',
    value: 'ueditor'
  },
])

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  configId: {
    type: Number,
    required: true,
    default: 0
  },
  configItemId: {
    type: Number,
    required: true,
    default: 0
  }
});
const handleTypeChange = ()=>{
  formData.fileList = []
  formData.fileName = ''
  formData.filePath = ''
  formData.values = []
  formData.value=''
}

const handleSubmit = async () => {
  await formRef.value?.validate();
  formData.options = ''
  optionsData.value.map((item,index)=>{
    formData.options+=`${item.value}=${item.name}${index<optionsData.value.length-1?',':''}`
  })
 
  if(formData.type=='checkbox' || formData.type=='selects'){
    formData.value = formData.values.join(',')
  }
  if(formData.type=='image'){
    formData.value = formData.filePath
  }
  if(formData.type=='file'){
    formData.value = formData.fileName +'|'+ formData.filePath
  }
  if(formData.type=='images'){
    formData.value =''
    formData.fileList.map((item,index)=>{
      formData.value+=`${item.filePath}${index<formData.fileList.length-1?',':''}`
    })
  }
  if(formData.type=='files'){
    formData.value =''
    formData.fileList.map((item,index)=>{
      formData.value+=`${item.fileName}|${item.filePath}${index<formData.fileList.length-1?',':''}`
    })
  }
  console.log(formData)
  props.configItemId ? await configItemUpdate({ ...formData, configId: props.configId }) : await configItemAdd({ ...formData, configId: props.configId });
  message("操作成功");
  emit("update:visible", false);
  emit("success");
};

const dialogClose = () => {
  emit("update:visible", false);
};

const { isLock: subLoading, lockFn: submit } = useLockFn(handleSubmit);


const setFormData = async () => {
  const data = await getConfigItemDetail(props.configItemId);
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key];
    }
  }
  if(formData.options) {
    let arr = formData.options.split(',')
    let kk = []
    arr.map(item=>{
      let v = item.split('=')
      kk.push({name:v[1],value:v[0]})
    })
    optionsData.value = kk
  }
  if(formData.type=='checkbox' || formData.type=='selects'){
    if(formData.value) {
      formData.value = formData.value.split(',')
      formData.values = formData.value
    }
  }
  if(formData.type=='image'){
    if(formData.value) {
      formData.filePath = formData.value
    }
  }
  if(formData.type=='file'){
    if(formData.value) {
      formData.fileName = formData.value.split('|')[0]
      formData.filePath = formData.value.split('|')[1]
    }
  }
  if(formData.type=='images'){
    formData.valueList.map(item=>{
      formData.fileList.push({
        filePath:item
      })
    })
  }
  if(formData.type=='files'){
    formData.valueList.map(item=>{
      let kk = item.split('|')
      formData.fileList.push({
        fileName:kk[0],
        filePath:kk[1],
        name:kk[0],
        url:kk[1]
      })
    })
  }
};
const addOptions = ()=>{
  optionsData.value.push({name:'',value:''})
}
const delOptions = (index)=>{
  optionsData.value.splice(index,1)
}
const fileUploads = (list: any) => {
  formData.fileList = list
};
const fileUploadFile = async (filePath: any, fileName: any) => {
  formData.filePath = filePath;
  formData.fileName = fileName;
};
onMounted(() => {
  if (props.configItemId) {
    setFormData();
  }
});

</script>
