<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="供应商编号" prop="supplierNo" label-width="100px">
              <el-input v-model="queryParams.supplierNo" placeholder="请输入供应商编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['customer:address:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['customer:address:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['customer:address:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['customer:address:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="addressList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
        <el-table-column label="供应商编号" align="center" prop="supplierNo" />
        <el-table-column label="企业名称" align="center" prop="enterpriseName" width="250"/>
        <el-table-column label="地址编码" align="center" prop="addressNo" />
        <el-table-column label="姓名" align="center" prop="shipperName" />
        <el-table-column label="手机号" align="center" prop="shipperPhone" />
        <el-table-column label="邮政编码" align="center" prop="shippingPostCode" />
        <el-table-column label="省" align="center" prop="shippingProvincial" />
        <el-table-column label="市" align="center" prop="shippingCity" />
        <el-table-column label="区" align="center" prop="shippingCounty" />
        <el-table-column label="详细地址" align="center" prop="shippingAddress" />
        <el-table-column label="默认地址" align="center" prop="isSelf">
          <template #default="scope">
            <span>{{ scope.row.isSelf === 1 ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改供应商地址对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="650px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addressFormRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        :disabled="false"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="企业名称：" prop="supplierId" required>
              <el-select 
                v-model="form.supplierId" 
                placeholder="请选择企业名称" 
                clearable 
                filterable
                @change="handleSupplierChange"
              >
                <el-option
                  v-for="item in supplierOptions"
                  :key="item.id"
                  :label="item.enterpriseName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商编号：" prop="supplierNo">
              <el-input v-model="form.supplierNo" disabled placeholder="自动带出" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收货人：" prop="shipperName" required>
              <el-input v-model="form.shipperName" placeholder="请输入收货人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码：" prop="shipperPhone" required>
              <el-input v-model="form.shipperPhone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮政编码：" prop="shippingPostCode">
              <el-input v-model="form.shippingPostCode" placeholder="请输入邮政编码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="地址：" prop="shippingProvincial" required>
              <el-cascader
                v-model="selectedAddressRegion"
                :options="regionOptions"
                placeholder="请选择"
                clearable
                filterable
                style="width: 100%;"
                @change="handleAddressRegionChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="详细地址：" prop="shippingAddress">
              <el-input
                v-model="form.shippingAddress"
                type="textarea"
                :rows="3"
                placeholder="请输入详细地址"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="默认地址：">
              <el-switch v-model="form.isSelf" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="buttonLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Address" lang="ts">
import { listAddress, getAddress, delAddress, addAddress, updateAddress } from '@/api/supplier/address';
import { AddressVO, AddressQuery, AddressForm } from '@/api/supplier/address/types';
import { listNameInfo } from '@/api/supplier/info';
import { regionData, codeToText } from 'element-china-area-data';
import { useRoute } from 'vue-router';
import { useUserStore } from '@/store/modules/user';

const regionOptions = ref(regionData);
const selectedAddressRegion = ref<string[]>([]);
const supplierOptions = ref<any[]>([]);

const route = useRoute();
const userStore = useUserStore();

const getSupplierNameList = async () => {
  const res = await listNameInfo();
  supplierOptions.value = res.data || res.rows || [];
};

const handleSupplierChange = (val: string | number) => {
  const selected = supplierOptions.value.find(item => item.id === val);
  if (selected) {
    form.value.supplierNo = selected.supplierNo;
    form.value.enterpriseName = selected.enterpriseName;
  } else {
    form.value.supplierNo = undefined;
    form.value.enterpriseName = undefined;
  }
};

const handleAddressRegionChange = (value: any) => {
  if (value && value.length === 3) {
    form.value.shippingProvincial = codeToText[value[0]];
    form.value.shippingCity = codeToText[value[1]];
    form.value.shippingCounty = codeToText[value[2]];
  } else {
    form.value.shippingProvincial = undefined;
    form.value.shippingCity = undefined;
    form.value.shippingCounty = undefined;
  }
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const addressList = ref<AddressVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const addressFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AddressForm = {
  id: undefined,
  supplierNo: undefined,
  supplierId: undefined,
  shippingCompany: undefined,
  shipperName: undefined,
  shipperPhone: undefined,
  shippingPostCode: undefined,
  shippingProvincial: undefined,
  shippingCity: undefined,
  shippingCounty: undefined,
  shippingAddress: undefined,
  pushStatus: undefined,
  isSelf: undefined,
  type: undefined,
  addressNo: undefined,
  status: undefined,
  remark: undefined,
}
const data = reactive<PageData<AddressForm, AddressQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    supplierNo: undefined,
    params: {
    }
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询供应商地址列表 */
const getList = async () => {
  loading.value = true;
  if (!userStore.supplierId) {
    await userStore.getSupplierInfo();
  }
  queryParams.value.supplierId = (userStore.supplierId ?? route.query?.supplierId ?? route.query?.id ?? route.params?.supplierId ?? route.params?.id) as any;
  if (!queryParams.value.supplierId) {
    loading.value = false;
    return;
  }
  const res = await listAddress(queryParams.value);
  addressList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  selectedAddressRegion.value = [];
  addressFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AddressVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加供应商地址";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AddressVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getAddress(_id);
  Object.assign(form.value, res.data);
  if (res.data.shippingProvincial && res.data.shippingCity && res.data.shippingCounty) {
    try {
      // Find region codes using element-china-area-data
      let pCode = '';
      let cCode = '';
      let dCode = '';

      for (const p of regionOptions.value) {
        if (p.label === res.data.shippingProvincial) {
          pCode = p.value;
          for (const c of p.children || []) {
            if (c.label === res.data.shippingCity) {
              cCode = c.value;
              for (const d of c.children || []) {
                if (d.label === res.data.shippingCounty) {
                  dCode = d.value;
                  break;
                }
              }
              break;
            }
          }
          break;
        }
      }

      if (pCode && cCode && dCode) {
        selectedAddressRegion.value = [pCode, cCode, dCode];
      }
    } catch (e) {
      console.error('Failed to parse region codes', e);
    }
  }
  dialog.visible = true;
  dialog.title = "修改供应商地址";
}

/** 提交按钮 */
const submitForm = () => {
  addressFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAddress(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addAddress(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: AddressVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除供应商地址编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAddress(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('customer/address/export', {
    ...queryParams.value
  }, `address_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  getSupplierNameList();
});
</script>
