<template>
  <div>
    <el-dialog v-model="visible" :z-index="99" :title="title" width="100%" align-center fullscreen>
      <el-form :inline="true" :rules="rules" :model="modalForm" class="demo-form-inline" ref="ruleFormRef">
        <div class="barbox" style="margin-top: -10px;">
          <div class="bar"></div>
          <div class="name">分类信息</div>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="分类名称：" prop="class_name">
              <el-input v-model="modalForm.class_name" style="width: 240px" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序序号：" prop="sort">
              <el-input min="1" v-model.number="modalForm.sort" style="width: 240px" placeholder="请输入排序序号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="是否推荐搜索：" prop="is_recommend_search">
              <el-select style="width:230px" v-model="modalForm.is_recommend_search" placeholder="请选择是否推荐搜索" clearable>
                <el-option label="否" :value="0" />
                <el-option label="是" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="展示图标：" prop="class_icon">

              <div style="display:flex;align-items: center;">
                <el-image  v-if="modalForm.class_icon" style="width: 100px; height: 100px;margin-right: 10px;" fit="cover" :src="modalForm.class_icon" :preview-src-list="srcList">
                </el-image>
                <el-upload class="upload-demo" accep="image/*" :limit="1" :show-file-list="false" ref="upload" :auto-upload="true" :before-upload="beforeUpload" :http-request="handleOss">
                  <el-button size="default" type="primary">点击上传</el-button>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="分类简介：" prop="class_brief">
              <ueditor v-if="visible" v-model="modalForm.class_brief" :id="'class_brief'"></ueditor>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider />
      <div class="barbox">
        <div class="bar"></div>
        <div class="name">操作</div>
      </div>
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form-item label="" style="padding-left:30px">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="submit(ruleFormRef)">
              确定
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submit">
          确定
        </el-button>
      </div>
    </template> -->
    </el-dialog>
    <el-dialog v-model="dialogVisible" title="温馨提示" width="400">
      <span>确定取消该订单？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import { onBeforeMount, reactive, ref, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import userApi from "../api/user";
import { ElMessage,dayjs } from "element-plus";
import { formatOrderStatus, formatRefundStatus, formatDate } from '../utils/format'
import { rowKey } from 'element-plus/es/components/table-v2/src/common';
const ruleFormRef = ref(null);
const method = ref(null);
const emit = defineEmits(['refreshList']);
const upload=ref(null);
const srcList=ref([]);
const modalForm = reactive({
  class_id: '',
  class_brief: ''
})
const rules = reactive({
  class_name: [
    {
      required: true,
      message: '请输入分类名称',
      trigger: 'blur',
    }
  ],
  sort: [
    {
      required: true,
      message: '请输入排序序号',
      trigger: 'blur',

    },
    {
      type: 'number',
      message: '请输入数字',
      trigger: 'blur'
    }
  ],
  class_icon: [
    {
      required: true,
      message: '请上传展示图标',
      trigger: 'blur',
    }
   
  ],
  class_brief: [
    {
      required: true,
      message: '请输入分类简介',
      trigger: 'blur',
    }
  ]
});

const handleAdd = () => {
  userApi.saveClassify(modalForm).then((res) => {
    let result = res;

    if (result.code == 200) {
      ElMessage.success("添加成功");
      visible.value = false;
      emit('refreshList')
    }

  })
};
const handleEdit = () => {
  userApi.editClassify(modalForm.class_id, modalForm).then((res) => {
    let result = res;

    if (result.code == 200) {
      ElMessage.success("修改成功");
      visible.value = false;
      emit('refreshList')
    }

  })
};
const generateRandomNumber=()=> {
				let randomNumber = Math.floor(1000 + Math.random() * 9000);
				return randomNumber;
	};
 const getImageFormat=(imageUrl)=>{
			  const lastDotIndex = imageUrl.lastIndexOf('.');
			  if (lastDotIndex !== -1) {
			    return imageUrl.substring(lastDotIndex + 1);
			  }
			  return 'unknown';
			};
const beforeUpload=(file)=>{
  console.log(file)  
  if (file.size >= 10 * 1024 * 1024) {
       ElMessage.warning("图片大小不能超过10M");
       return  false
  };
  if(!(/\.(jpg|jpeg|png|gif|webp)(?:\?.*)?$/i.test(file.name))){
    ElMessage.warning("图片格式不正确");
    return  false
  }

    return  true
};
 const handleOss=(file)=> {
     let File = file.file;
     console.log(File)
     userApi.getOssSign({
					scene: 1
				}).then(rep => {
					if (rep.code == 200) {
						let {
							access_id,
							dir,
							policy,
							signature,
							host
						} = rep.data;
						let filename = File.name;
						let time = dayjs().format("YYYYMMDDHHmmss");
						let random = generateRandomNumber();
						let imgType='.'+getImageFormat(filename);
            // let formData={
						// 		key: dir + time + random +imgType ,
						// 		OSSAccessKeyId: access_id,
						// 		policy,
						// 		signature,
						// 		success_action_status: '200',
						// 	};
            let formData = new FormData();
            formData.append('OSSAccessKeyId', access_id);
            formData.append('policy', policy);
            formData.append('signature', signature);
            formData.append('key', dir + time + random +imgType);
            formData.append('file', File, filename);
            formData.append('success_action_status',200);
             
              userApi.ossUpload(host,formData).then(res => {
             
                 ElMessage.success('上传成功')
									modalForm.class_icon=host+"/"+ dir + time + random + imgType;
                 srcList.value = [modalForm.class_icon]
                 upload.value.clearFiles()

							}).catch((err) => {
                console.log(err)
              })
			};
   });
 }
const submit = async (form) => {
  await form.validate((valid, fields) => {
    if (valid) {
      method.value === 'edit' ? handleEdit() : handleAdd()
    } else {
      console.log('error submit!', fields)
    }

  });
}
const visible = ref(false);
const dialogVisible = ref(false);
const title = ref('订单详情')
const route = useRoute();
const router = useRouter();


const cancelOrder = () => {

};
const confirmCancel = () => {
  dialogVisible.value = false;
  cancelOrder()

}

const init = (type, id) => {
  visible.value = true;
  method.value = type;
  modalForm.class_id = id;
  if (method.value === 'edit') {
    title.value = '编辑分类'
  } else if (method.value === 'view') {
    title.value = '新建分类'
  }

  nextTick(() => {
    ruleFormRef.value.resetFields();
    modalForm.class_brief = '';
    if (method.value === 'edit') {
      userApi.getClassifyDetail(modalForm.class_id).then((res) => {
        let result = res.data;
        Object.assign(modalForm, result);
        srcList.value = [result.class_icon]

      })
    }
  })

}

defineExpose({
  init
});
</script>

<style lang="scss" scoped>
.barbox {
  margin: 10px 0;
  display: flex;
  align-items: center;

  .bar {
    width: 4px;
    height: 25px;
    background: var(--el-color-primary);
  }

  .name {
    margin-left: 8px;
    font-size: 16px;
  }
}
</style>