<template>
  <el-form ref="formRef" :model="formData" :rules="ruleForm" :label-width="store.state.themeConfig.themeConfig.globalI18n === 'en' ? '170px' : '100px'">
    <el-form-item :label="$t('message.projects.list.addOrEdit.form.name')" prop="name">
      <el-input v-model.trim="formData.name" :placeholder="$t('message.projects.list.addOrEdit.placeholders.name')" />
    </el-form-item>
    <el-form-item :label="$t('message.projects.list.addOrEdit.form.addressCode')" prop="addressCode">
      <el-cascader :options="data" :props="{ emitPath: true, value: 'code', label: 'name' }" :placeholder="$t('message.projects.list.addOrEdit.placeholders.select')" clearable class="w100" v-model="formData.addressCode"> </el-cascader>
    </el-form-item>
    <el-form-item :label="$t('message.projects.list.addOrEdit.form.addressDetail')" prop="addressDetail">
      <el-input v-model.trim="formData.addressDetail" :placeholder="$t('message.projects.list.addOrEdit.placeholders.addressDetail')" />
    </el-form-item>
    <el-form-item :label="$t('message.projects.list.addOrEdit.form.channelMerchants')" prop="channelMerchants">
      <el-input v-model.trim="formData.channelMerchants" :placeholder="$t('message.projects.list.addOrEdit.placeholders.channelMerchants')" />
    </el-form-item>
    <el-form-item :label="$t('message.projects.list.addOrEdit.form.customName')" prop="customName">
      <el-input v-model.trim="formData.customName" :placeholder="$t('message.projects.list.addOrEdit.placeholders.customName')" />
    </el-form-item>
    <el-form-item :label="$t('message.projects.list.addOrEdit.form.repairCompany')" prop="repairCompany">
      <el-input v-model.trim="formData.repairCompany" :placeholder="$t('message.projects.list.addOrEdit.placeholders.repairCompany')" />
    </el-form-item>
    <el-form-item :label="$t('message.projects.list.addOrEdit.form.repairMobile')" prop="repairMobile">
      <el-input v-model.trim="formData.repairMobile" :placeholder="$t('message.projects.list.addOrEdit.placeholders.repairMobile')" />
    </el-form-item>
    <el-form-item label="" prop="">
      <el-button @click="cancel">{{ $t("message.projects.list.addOrEdit.buttons.cancel") }}</el-button>
      <el-button type="primary" @click="onSubmit">{{ $t("message.projects.list.addOrEdit.buttons.confirm") }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed } from "vue";
import api from "/@/api/projects";
import { ruleRequired } from "/@/utils/validator";
import { ElMessage } from "element-plus";
import data from "province-city-china/dist/level.json";
import { useI18n } from "vue-i18n";
import { useStore } from "/@/store/index";

const store = useStore();

const emit = defineEmits(["getList", "cancel"]);

const showDialog = ref(false);
const formRef = ref();
const { t } = useI18n();

// 从省市区的的树形结构中获取省市区名称
function getNames(code: string) {
  const provinceItem = data.find((item: any) => item.province === code.substring(0, 2));
  const provinceName = provinceItem.name;
  const cityItem = provinceItem.children.find((item: any) => item.city === code.substring(2, 4));
  const cityName = cityItem.name;

  if (!cityItem.children) {
    const areaItem = provinceItem.children.find((item: any) => item.area === code.substring(4, 6));
    const areaName = areaItem.name;
    return `${provinceName}/${areaName}`;
  } else {
    const areaItem = cityItem.children.find((item: any) => item.area === code.substring(4, 6));
    const areaName = areaItem.name;
    return `${provinceName}/${cityName}/${areaName}`;
  }
}

const baseForm = {
  id: undefined,
  address: "",
  addressCode: [],
  name: "",
  addressDetail: "",
  channelMerchants: "",
  customName: "",
  repairCompany: "",
  repairMobile: "",
};

const formData = reactive({
  ...baseForm,
});

const ruleForm = computed(() => {
  return {
    name: [ruleRequired(t("message.projects.list.addOrEdit.validation.name"))],
    addressCode: [ruleRequired(t("message.projects.list.addOrEdit.validation.addressCode"))],
    addressDetail: [ruleRequired(t("message.projects.list.addOrEdit.validation.addressDetail"))],
    channelMerchants: [ruleRequired(t("message.projects.list.addOrEdit.validation.channelMerchants"))],
    customName: [ruleRequired(t("message.projects.list.addOrEdit.validation.customName"))],
    repairCompany: [ruleRequired(t("message.projects.list.addOrEdit.validation.repairCompany"))],
    repairMobile: [ruleRequired(t("message.projects.list.addOrEdit.validation.repairMobile"))],
  };
});

const onSubmit = async () => {
  await formRef.value.validate();

  const { addressCode } = formData;
  formData.address = JSON.stringify({
    name: getNames(addressCode[2] || addressCode[1]),
    code: addressCode,
  });

  const theApi = formData.id ? api.edit : api.add;

  await theApi(formData);

  ElMessage.success(t(`message.projects.list.addOrEdit.messages.${formData.id ? "editSuccess" : "addSuccess"}`));
  // resetForm();
  showDialog.value = false;
  emit("getList");
};

const resetForm = async () => {
  Object.assign(formData, { ...baseForm });
  formRef.value && formRef.value.resetFields();
};

const cancel = () => {
  emit("cancel");
};

const open = async (row?: any) => {
  resetForm();
  showDialog.value = true;
  nextTick(() => {
    Object.assign(formData, { ...row, addressCode: JSON.parse(row.address)?.code });
  });
};

defineExpose({ open });
</script>
