<template>
  <div>
    <el-drawer v-model="openDrawer" :title="props.drawerType === 'add' ? '添加模板' : '编辑模板'">
      <el-form ref="ruleDrawerRef" :model="form" label-width="100px">
        <el-form-item
          label="模板名称"
          prop="name"
          :rules="[
            {
              required: true,
              message: '输入模板名称',
              trigger: 'blur',
            },
          ]"
        >
          <el-input placeholder="请输入模板名称" v-model="form.name" />
        </el-form-item>

        <el-form-item
          label="模板编码"
          prop="code"
          :rules="[
            {
              required: true,
              message: '输入模板编码',
              trigger: 'blur',
            },
          ]"
        >
          <el-input placeholder="请输入模板编码" v-model="form.code" />
        </el-form-item>

        <el-form-item label="看板组件">
          <el-select v-model="form.component" disabled>
            <el-option label="Zone one" value="shanghai" />
            <el-option label="Zone two" value="beijing" />
          </el-select>
        </el-form-item>

        <el-form-item
          label="预览图片"
          prop="thumbnail"
          :rules="[
            {
              required: true,
              message: '上传预览图片',
              trigger: 'blur',
            },
          ]"
        >
          <el-upload
            ref="uploadRef"
            :class="{ 'no-el-upload': fileList.length > 0 }"
            :action="actionUrl"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleUploadRemove"
            :on-success="handleUploadSuccess"
            :before-upload="beforeThumbnailUpload"
            :limit="1"
            :headers="getHeaders()"
            :data="{ bizType: 'COMPANY_THUMBNAIL' }"
            list-type="picture-card"
            v-model:file-list="fileList"
          >
            <!-- <img v-if="ruleForm.thumbnail" :src="ruleForm.thumbnail" />
            <el-icon v-else><Plus /></el-icon> -->
            <el-icon v-if="!form.thumbnail || form.thumbnail.length === 0"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input placeholder="请输入备注" v-model="form.remark" />
        </el-form-item>

        <!-- <el-form-item label="模板上传">
        <el-upload>
          <el-button disabled>上传</el-button>
        </el-upload>
      </el-form-item> -->

        <!-- <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" :active-value="0" :inactive-value="1" />
      </el-form-item> -->

        <!-- <el-form-item label="状态" label-position="right">
          <el-radio-group v-model="status" aria-label="label position">
            <el-radio-button :value="0">启用</el-radio-button>
            <el-radio-button :value="1">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item> -->

        <el-form-item style="margin-top: 100px">
          <el-button style="margin-left: auto" @click="resetForm(ruleDrawerRef)">重置</el-button>
          <el-button @click="submitDrawer(ruleDrawerRef)" type="primary">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, defineExpose } from 'vue';
  import { FormInstance, ElMessage } from 'element-plus';
  import { onMounted } from 'vue';
  // import { cloneDeep, isEqual } from 'lodash-es';
  import type { UploadRawFile, UploadFile } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import { getHeaders } from '@/utils/http/axios';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';
  import { SceneModule } from '@/api/template/template';
  // import { uid } from 'uid';

  export interface FormModelCommon {
    id?: number | null;
    code: string;
    name: string;
    component: string;
    remark: string;
    thumbnail: string | null | undefined;
    isDisabled?: number;
  }
  export type CreateType = 'create' | 'edit';
  const props = defineProps<{
    type: string;
    drawerType: string;
    addItem: (data: SceneModule) => unknown;
    editItem: (data: SceneModule) => unknown;
  }>();

  const openDrawer = ref(false);

  const form = ref<FormModelCommon>({
    name: '',
    code: '',
    component: '',
    remark: '',
    thumbnail: null,
  });

  const dataUpload = ref<SceneModule>({
    code: '',
    name: '',
    previewImage: null,
    remark: '',
    // isDisabled: 0,
  });

  const status = ref(0); //el-radio不能绑对象，因此把他独立出来

  const { urlPrefix } = useGlobSetting();

  const actionUrl = computed(() => {
    return urlJoin(urlPrefix!, `admin/minio/uploadFile`);
  });
  const uploadRef = ref();
  const fileList = ref<UploadFile[]>([]);

  // watch(
  //   fileList,
  //   (newVal) => {
  //     form.value.thumbnail = newVal[0]?.url;
  //   },
  //   {
  //     deep: true, // 如果数组中是对象，则需要设置deep选项来深度监听
  //   },
  // );
  const dialogImageUrl = ref('');
  const dialogVisible = ref(false);

  const handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url!;
    dialogVisible.value = true;
  };
  const handleUploadRemove = () => {
    form.value.thumbnail = '';
  };

  const handleUploadSuccess = (res) => {
    form.value.thumbnail = res.data.url;
  };
  const beforeThumbnailUpload = (file: UploadRawFile) => {
    if (file.type !== 'image/png' && file.type !== 'image/jpeg') {
      ElMessage.error('仅支持上传png/jpg/jpeg格式的图片');
      return false;
    } else if (file.size / 1024 / 1024 > 10) {
      ElMessage.error('上传图片大小不能超过10MB');
      return false;
    }
    return true;
  };

  const ruleDrawerRef = ref<FormInstance>();

  function resetForm(formE1: FormInstance | undefined) {
    if (!formE1) return;
    formE1.resetFields();
    form.value.name = '';
    form.value.code = '';
    form.value.remark = '';
    status.value = 0;
    form.value.thumbnail = null;
    reSetFileList();
    // console.log('resetForm');
  }

  const setForm = (details: FormModelCommon) => {
    // console.log('form=====', form.value);
    form.value.id = details.id;
    form.value.name = details.name;
    form.value.code = details.code;
    form.value.remark = details.remark;
    status.value = details.isDisabled ? details.isDisabled : 0;
    form.value.thumbnail = details.thumbnail;
  };

  const drawerSwitch = (index: boolean) => {
    openDrawer.value = index;
  };

  const setFileList = (name: string, url: string) => {
    fileList.value = [];
    fileList.value.push({
      name: name + '模板图片',
      status: 'success',
      uid: 1,
      url: url,
    });
  };

  const reSetFileList = () => {
    fileList.value = [];
  };

  defineExpose({
    setForm,
    drawerSwitch,
    setFileList,
    reSetFileList,
  });

  function submitDrawer(formEl: FormInstance | undefined) {
    if (!formEl) return;
    formEl.validate((valid, fields) => {
      if (valid) {
        if (props.drawerType === 'add') {
          dataUpload.value.code = form.value.code;
          dataUpload.value.name = form.value.name;
          dataUpload.value.previewImage = form.value.thumbnail;
          dataUpload.value.remark = form.value.remark;
          // dataUpload.value.isDisabled = status.value;
          props.addItem(dataUpload.value);
        } else {
          dataUpload.value.id = form.value.id;
          dataUpload.value.code = form.value.code;
          dataUpload.value.name = form.value.name;
          dataUpload.value.previewImage = form.value.thumbnail;
          dataUpload.value.remark = form.value.remark;
          // dataUpload.value.isDisabled = status.value;
          props.editItem(dataUpload.value);
        }
      } else {
        console.log('error submit!', fields);
      }
    });
  }

  onMounted(() => {
    if (props.drawerType === 'add') {
      resetForm(undefined);
    }
  });
</script>

<style scoped>
  :deep(.no-el-upload .el-upload--picture-card) {
    display: none;
  }
</style>

<style></style>
