<template>
  <div>
    <el-drawer
      ref="companyDrawerRef"
      class="test"
      :model-value="true"
      @close="() => emit('onClose')"
      with-header="true"
      size="35%"
      destroy-on-close
    >
      <template #header="{ titleId }">
        <p :id="titleId">{{ title }}</p>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="90px"
        class="demo-ruleForm"
        size="default"
        status-icon
      >
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="ruleForm.name" style="width: 200px" />
        </el-form-item>
        <el-form-item label="所在省市" prop="regionCode" required>
          <el-select v-model="ruleForm.regionCode" placeholder="请选择省市" style="width: 200px">
            <el-option
              v-for="province in provinceList"
              :key="province.regionCode"
              :label="province.regionName"
              :value="province.regionCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="坐标经度" prop="longitude"
          ><el-input v-model="ruleForm.longitude" type="number" style="width: 200px"></el-input
        ></el-form-item>
        <el-form-item label="坐标纬度" prop="latitude"
          ><el-input v-model="ruleForm.latitude" type="number" style="width: 200px"></el-input
        ></el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" style="width: 200px" />
        </el-form-item>
        <!-- <el-form-item label="状态">
          <el-switch
            v-model="ruleForm.isDisabled"
            :active-value="IS_DISABLED.FALSE"
            :inactive-value="IS_DISABLED.TRUE"
            class="switchUse"
          />
        </el-form-item> -->
        <el-form-item label="公司头像">
          <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="!ruleForm.thumbnail || ruleForm.thumbnail.length === 0"
              ><Plus
            /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <div style="position: absolute; left: 108px; bottom: 67px">
        <el-button v-if="!props.detail.id" @click="resetDrawCom">重置</el-button>
        <el-button type="primary" v-if="!props.detail.id" @click="newCompanyAdd"> 提交 </el-button>
        <el-button type="primary" v-if="props.detail.id" @click="editedSub(ruleFormRef)">
          提交
        </el-button>
      </div>
    </el-drawer>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { computed, reactive, ref, defineProps, defineEmits, watch, onMounted } from 'vue';

  import {
    // addCompanyModuleLabel,
    // editCompanyModuleLabel,
    addCompany,
    editCompany,
  } from '@/api/scene/scene.ts';
  // import { SceneLabelType, TemplateType } from '@/types/scene/type.ts';

  // import { IS_DISABLED } from '@/types/scene/constant.ts';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage } from 'element-plus';
  // import { CirclePlus } from '@element-plus/icons-vue';
  import { getProvinceList } from '@/api/system/region';
  import { useRequest } from 'vue-hooks-plus';
  import { Plus } from '@element-plus/icons-vue';
  import { getHeaders } from '@/utils/http/axios';
  import type { UploadRawFile, UploadFile } from 'element-plus';
  import urlJoin from 'url-join';
  import { useGlobSetting } from '@/hooks/setting';

  const props = defineProps<{
    detail: {
      id?: number; //传不传id代表着是不是编辑
      name?: string;
      // orderNum?: number;
      // isDisabled?: IS_DISABLED;
      remark?: string;
      longitude?: number; //经度
      latitude?: number; //纬度
      regionCode?: string; //省市代码
      thumbnail?: string;
    };
  }>();

  const { urlPrefix } = useGlobSetting();

  const actionUrl = computed(() => {
    return urlJoin(urlPrefix!, `/admin/minio/uploadFile`);
  });

  const uploadRef = ref();

  const dialogImageUrl = ref('');
  const dialogVisible = ref(false);
  const fileList = ref<UploadFile[]>([]);

  onMounted(() => {
    if (props.detail.thumbnail) {
      fileList.value.push({
        name: '公司头像',
        status: 'success',
        uid: 1,
        url: props.detail.thumbnail,
      });
    }
  });
  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 handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url!;
    dialogVisible.value = true;
  };

  const handleUploadRemove = () => {
    ruleForm.thumbnail = '';
  };

  const handleUploadSuccess = (res) => {
    ruleForm.thumbnail = res.data.url;
  };

  const title = computed(() => {
    if (props.detail.id) {
      return '编辑公司';
    }
    return '添加公司';
  });
  const emit = defineEmits<{
    (e: 'onOk'): unknown;
    (e: 'onClose'): unknown;
  }>();

  //表格中的规则
  const ruleFormRef = ref<FormInstance>();
  //匹配规则
  // const pattern = /经度\s*[:：]\s*([0-9.]+)\s*[;；]\s*纬度\s*[:：]\s*([0-9.]+)/;

  interface RuleForm {
    name: string; //名称
    // isDisabled?: IS_DISABLED; //状态
    remark?: string; //备注
    longitude?: number; //经度
    latitude?: number; //纬度
    regionCode?: string; //省市代码
    thumbnail?: string; //公司缩略图
  }

  const ruleForm = reactive<RuleForm>({
    name: '',
    // isDisabled: IS_DISABLED.TRUE,
    remark: '',
    longitude: undefined, //经度
    latitude: undefined, //纬度
    regionCode: '',
    thumbnail: '',
  });
  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '公司名称不能为空', trigger: 'blur' },
      { min: 1, max: 100, message: '字符长度在1-100之间', trigger: 'blur' },
    ],
    regionCode: [{ required: true, message: '省市不能为空', trigger: 'blur' }],
  });

  const { data: provinceList } = useRequest(getProvinceList);

  //编辑时需要传入子组件的数据
  watch(
    () => props.detail,
    (data) => {
      ruleForm.name = data.name!;
      // ruleForm.isDisabled = data.isDisabled;
      ruleForm.remark = data.remark;
      ruleForm.latitude = data.latitude;
      ruleForm.longitude = data.longitude;
      ruleForm.regionCode = data.regionCode;
      ruleForm.thumbnail = data.thumbnail;
    },
    { immediate: true },
  );

  //添加新公司的提交
  const newCompanyAdd = () => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid) => {
      if (!valid) {
        return;
      }

      const newComData = {
        name: ruleForm.name,
        // isDisabled: ruleForm.isDisabled,
        // orderNum: props.detail.orderNum,
        remark: ruleForm.remark,
        longitude: ruleForm.longitude,
        latitude: ruleForm.latitude,
        regionCode: ruleForm.regionCode,
        thumbnail: ruleForm.thumbnail,
      };
      //提交数据并重置关闭el-draw
      addCompany(newComData)
        .then(() => {
          console.log('添加成功');
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          emit('onOk');
        });
    });
  };

  //编辑公司时的提交
  const editedSub = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid) => {
      if (!valid) {
        return;
      }

      //新增的数据
      const editNewCom = {
        id: props.detail.id,
        name: ruleForm.name,
        // isDisabled: ruleForm.isDisabled,
        remark: ruleForm.remark,
        longitude: ruleForm.longitude,
        latitude: ruleForm.latitude,
        regionCode: ruleForm.regionCode,
        thumbnail: ruleForm.thumbnail,
      };
      // 编辑上传
      editCompany(editNewCom)
        .then(() => {
          console.log('编辑成功');
        })
        .finally(() => {
          emit('onOk');
        });
    });
  };

  //重置编辑框
  const resetDrawCom = () => {
    ruleForm.name = '';
    // ruleForm.isDisabled = IS_DISABLED.TRUE;
    ruleForm.regionCode = '';
    ruleForm.latitude = undefined;
    ruleForm.longitude = undefined;
    ruleForm.thumbnail = '';
  };
</script>

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